diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index c456f00e10f7..0e1ed32e174f 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,76 +1,20 @@ -CiviCRM is a community-driven open-source project. It has a small, -full-time "core team" which facilitates development and works on critical -issues. However, many improvements are driven by the active contributors. - -This document provides important information about how to contribute. - -## Review/Release Process - -Releases are developed on a monthly cycle. At the start of the month, the -release-manager will send an invitation to developers who have open PRs, -encouraging them to participate in the release-cycle. Participation -provides a way to exchange feedback with other developers, get PRs merged, -and ensure the next release works -- all with a predictable timeline. - - * For a high-level summary of the release process, see the - [Release Management README](https://github.com/civicrm/release-management/blob/master/README.md). - * For an example invitation, see the previous [invitation for the April-May 2016](https://github.com/civicrm/release-management/issues/1). - -## Pull-Request Scope - -A good pull request (PR) addresses a clearly-defined problem. There should be a detailed description logged in the [issue tracker](http://issues.civicrm.org/). Excellent PRs also increase test coverage. If you are tempted to do additional tweaks or code cleanup outside the scope of that issue, you could make a separate commit and include them in the PR if they are minor & non-controversial, or create a seperate PR if they are more complex. - -There is no size limit for PRs as long as they are focused on completely solving a discreet problem. As a practical matter, though, bigger PRs may take longer to review and merge. When possible, split "epic" issues into bite-sized chunks as long as each seperate PR is functionally complete and does not cause merge conflicts with your other PRs. In the latter case, add commits to an existing PR. - -## Pull-Request Subject - -When filing a pull-request, use a descriptive subject. These are good examples: - - * `CRM-12345 - Fix Paypal IPNs when moon is at half-crescent (waxing)` - * `(WIP) CRM-67890 - Refactor SMS callback endpoint` - * `(NFC) CRM_Utils_PDF - Improve docblocks` - -A few elements to include: - - * **CRM-_XXXXX_** - This is a reference to the [CiviCRM issue tracker](http://issues.civicrm.org/) - (JIRA). A bot will setup crosslinks between JIRA and GitHub. - * **Description** - Provide a brief description of what the pull-request does. - * **(WIP)** - "Work in Progress" - If you are still developing a set of - changes, it may be useful to submit a pull-request and flag it as - `(WIP)`. This allows you to have discussion with other developers and - check test results. Once the change is ready, update the subject line - to remove `(WIP)`. - * **(NFC)** - "Non-Functional Change" - Most patches are designed to - change functionality (e.g. fix an error message or add a new button). - However, some changes are non-functional -- e.g. they cleanup the - code-style, improve the comments, or improve the test-suite. - -## Testing - -Pull-requests are tested automatically by a build-bot. Key things to know: - - * If you are a new contributor, the tests may be placed on hold pending a - cursory review. One of the administrators will post a comment like - `jenkins, ok to test` or `jenkins, add to whitelist`. - * The pull-request will have a colored dot indicating its status: - * **Yellow**: The automated tests are running. - * **Red**: The automated tests have failed. - * **Green**: The automated tests have passed. - * If the automated test fails, click on the red dot to investigate details. Check for information in: - * The initial summary. Ordinarily, this will list test failures and error messages. - * The console output. If the test-suite encountered a significant error (such as a PHP crash), - the key details will only appear in the console. - * Code-style tests are executed first. If the code-style in this patch is inconsistent, the remaining tests will be skipped. - * The primary tests may take 20-120 min to execute. This includes the following suites: `api_v3_AllTests`, `CRM_AllTests`, `Civi\AllTests`, `civicrm-upgrade-test`, and `karma` - * There are a handful of unit tests which are time-sensitive and which fail sporadically. See: https://forum.civicrm.org/index.php?topic=36964.0 - * The web test suite (`WebTest_AllTests`) takes several hours to execute. [It runs separately -- after the PR has been merged.](https://test.civicrm.org/job/CiviCRM-WebTest-Matrix/) - -For detailed discussion about automated tests, see http://wiki.civicrm.org/confluence/display/CRMDOC/Testing - -## Updating a pull-request - -During review, there may be some feedback about problems or additional -changes required for acceptance. If you've never updated a pull-request -before, see [Stackoverflow: How to update a pull request](http://stackoverflow.com/questions/9790448/how-to-update-a-pull-request). - -When you push the update to the pull-request, the test suite will re-execute. +CiviCRM is a community-driven open-source project. It has a small, full-time +[core team](https://civicrm.org/core-team) +which facilitates development and works on critical issues. +Additionally, a large community of active contributors and +[partner organizations](https://civicrm.org/partners-contributors) +drive much of the development work. + +For developers, CiviCRM maintains a comprehensive +[Developer Guide](https://docs.civicrm.org/dev/en/latest). +Topics of particular importance while submitting pull requests include: + +* [Contributing to CiviCRM core](https://docs.civicrm.org/dev/en/latest/core/contributing/) +* [Pull requests](https://docs.civicrm.org/dev/en/latest/tools/git/#pr) +* [Git workflow overview](https://docs.civicrm.org/dev/en/latest/tools/git/#contributing) +* [Writing automated tests](https://docs.civicrm.org/dev/en/latest/testing/setup/) +* [Jenkins continuous integration](https://docs.civicrm.org/dev/en/latest/tools/jenkins/) +* [Release Process](https://docs.civicrm.org/dev/en/latest/core/release-process/) +* [Developer Community](https://docs.civicrm.org/dev/en/latest/basics/community/) + +CiviCRM thanks you for your contributions and invites you to [log your time spent](https://civicrm.org/contributor-log) so that you (or your organization) may receive public recognition and promotion for your efforts. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000000..85e7f8f59d2d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ +Overview +---------------------------------------- +_A brief description of the pull request. Try to keep it non-technical._ + +Before +---------------------------------------- +_The current status. Please provide screenshots or gifs ([LICEcap](http://www.cockos.com/licecap/), [SilentCast](https://github.com/colinkeenan/silentcast)) where appropriate._ + +After +---------------------------------------- +_What has been changed. Please provide screenshots or gifs ([LICEcap](http://www.cockos.com/licecap/), [SilentCast](https://github.com/colinkeenan/silentcast)) where appropriate._ + +Technical Details +---------------------------------------- +_If the PR introduces noteworthy technical changes, please describe them here. Provide code snippets if necessary_ + +Comments +---------------------------------------- +_Anything else you would like the reviewer to note_ diff --git a/.gitignore b/.gitignore index 25992eaacb4f..fd86ffe726ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,16 @@ *~ *.bak +.use-civicrm-setup +/ext/ backdrop/ bower_components CRM/Case/xml/configuration CRM/Core/DAO/.listAll.php CRM/Core/DAO/listAll.php -CRM/Core/I18n/SchemaStructure.php bin/setup.conf -civicrm-version.php civicrm-version.txt civicrm.config.php -install/langs.php node_modules -packages/.channels -packages/.depdb -packages/.depdblock -packages/.filemap -packages/.lock -packages/.registry -packages/cache -packages/doc -packages/temp -packages/test settings_location.php sql/case_sample.mysql sql/civicrm.mysql @@ -32,12 +21,12 @@ sql/civicrm_data.mysql sql/civicrm_drop.mysql sql/civicrm_navigation.mysql sql/civicrm_sample.mysql -templates/CRM/common/version.tpl tests/phpunit/CiviTest/CiviSeleniumSettings.php tests/phpunit/CiviTest/civicrm.settings.php tools/stats/config.php authors.txt -drupal/ +/drupal/ +/drupal-8/ WordPress joomla packages/ @@ -54,3 +43,4 @@ civicrm.settings.php sql/dummy_processor.mysql distmaker/distmaker.conf distmaker/out +/tmp diff --git a/.toxic.json b/.toxic.json index 5d1f2a3d854b..d24776f28356 100644 --- a/.toxic.json +++ b/.toxic.json @@ -3,16 +3,79 @@ "toxicAlert": "\n\n(Automated notice) This pull-request modifies {SYMBOLS}. That code has been previously identified as hazardous. For advice on dealing with it, please review [Toxic Code Protocol](http://wiki.civicrm.org/confluence/display/CRM/Toxic+Code+Protocol)." }, "checks": { - "CRM_Contact_Import_Parser_Contact::import()": "toxicAlert", - "CRM_Core_BAO_Mapping::buildMappingForm()": "toxicAlert", - "CRM_Event_Form_Participant::postProcess()": "toxicAlert", - "CRM_Export_BAO_Export::exportComponents()": "toxicAlert", - "CRM_Member_Form_Membership::postProcess()": "toxicAlert", - "CRM_Contribute_Form_Contribution::postProcess()": "toxicAlert", + "CRM_Activity_BAO_Activity::create()": "toxicAlert", + "CRM_Activity_Form_Activity::preProcess()": "toxicAlert", + "CRM_Case_BAO_Case::getCaseActivity()": "toxicAlert", + "CRM_Case_BAO_Case::mergeCases()": "toxicAlert", + "CRM_Contact_BAO_Contact::formatProfileContactParams()": "toxicAlert", + "CRM_Contact_BAO_ContactTest::testCreateProfileContact()": "toxicAlert", + "CRM_Contact_BAO_Individual::format()": "toxicAlert", + "CRM_Contact_BAO_Query::addHierarchicalElements()": "toxicAlert", + "CRM_Contact_BAO_Relationship::relatedMemberships()": "toxicAlert", + "CRM_Contact_Form_Contact::postProcess()": "toxicAlert", "CRM_Contact_Import_Form_MapField::buildQuickForm()": "toxicAlert", + "CRM_Contact_Import_Parser::formatCommonData()": "toxicAlert", + "CRM_Contact_Import_Parser::formatContactParameters()": "toxicAlert", + "CRM_Contact_Import_Parser::run()": "toxicAlert", + "CRM_Contact_Import_Parser_Contact::import()": "toxicAlert", + "CRM_Contribute_BAO_Contribution::recordFinancialAccounts()": "toxicAlert", + "CRM_Contribute_BAO_Contribution::transitionComponents()": "toxicAlert", + "CRM_Contribute_BAO_ContributionPage::sendMail()": "toxicAlert", + "CRM_Contribute_BAO_Query::whereClauseSingle()": "toxicAlert", + "CRM_Contribute_Form_Contribution::buildQuickForm()": "toxicAlert", + "CRM_Contribute_Form_Contribution::submit()": "toxicAlert", + "CRM_Contribute_Form_ContributionBase::preProcess()": "toxicAlert", + "CRM_Contribute_Form_ContributionPage_Amount::postProcess()": "toxicAlert", + "CRM_Contribute_Form_Contribution_Confirm::postProcessMembership()": "toxicAlert", + "CRM_Contribute_Form_Contribution_Confirm::processFormSubmission()": "toxicAlert", + "CRM_Contribute_Form_Contribution_Main::buildQuickForm()": "toxicAlert", "CRM_Contribute_Form_Contribution_Main::formRule()": "toxicAlert", + "CRM_Contribute_Form_Contribution_Main::submit()": "toxicAlert", + "CRM_Contribute_Form_Task_Invoice::printPDF()": "toxicAlert", + "CRM_Contribute_Import_Parser::run()": "toxicAlert", + "CRM_Core_BAO_ActionScheduleTest::setUp()": "toxicAlert", + "CRM_Core_BAO_CustomField::formatCustomField()": "toxicAlert", + "CRM_Core_BAO_CustomGroup::getTree()": "toxicAlert", + "CRM_Core_BAO_Mapping::buildMappingForm()": "toxicAlert", + "CRM_Core_BAO_UFGroup::buildProfile()": "toxicAlert", + "CRM_Core_BAO_UFGroup::getValues()": "toxicAlert", + "CRM_Core_I18n_SchemaStructure::widgets()": "toxicAlert", + "CRM_Core_Permission::getEntityActionPermissions()": "toxicAlert", + "CRM_Core_PseudoConstantTest::testOptionValues()": "toxicAlert", + "CRM_Custom_Form_Field::formRule()": "toxicAlert", + "CRM_Dedupe_Merger::getRowsElementsAndInfo()": "toxicAlert", + "CRM_Dedupe_Merger::moveAllBelongings()": "toxicAlert", + "CRM_Event_Form_ManageEvent_Fee::formRule()": "toxicAlert", + "CRM_Event_Form_Participant::submit()": "toxicAlert", "CRM_Event_Form_Registration_Confirm::postProcess()": "toxicAlert", - "CRM_Event_BAO_Event::displayProfile()": "toxicAlert", - "CRM_Contribute_Form_Contribution_Confirm::postProcess()": "toxicAlert" + "CRM_Event_Form_Registration_Register::buildQuickForm()": "toxicAlert", + "CRM_Event_Form_Registration_Register::postProcess()": "toxicAlert", + "CRM_Export_BAO_Export::exportComponents()": "toxicAlert", + "CRM_Mailing_BAO_Mailing::compose()": "toxicAlert", + "CRM_Mailing_BAO_Mailing::getRecipients()": "toxicAlert", + "CRM_Mailing_BAO_Mailing::report()": "toxicAlert", + "CRM_Member_Form_Membership::formRule()": "toxicAlert", + "CRM_Member_Form_Membership::submit()": "toxicAlert", + "CRM_PCP_Page_PCPInfo::run()": "toxicAlert", + "CRM_Price_BAO_PriceField::addQuickFormElement()": "toxicAlert", + "CRM_Price_Form_Field::formRule()": "toxicAlert", + "CRM_Profile_Form::buildQuickForm()": "toxicAlert", + "CRM_Profile_Form::postProcess()": "toxicAlert", + "CRM_Profile_Form::preProcess()": "toxicAlert", + "CRM_Profile_Page_Dynamic::run()": "toxicAlert", + "CRM_Report_Form_Contact_Detail::__construct()": "toxicAlert", + "CRM_Report_Form_Contribute_Bookkeeping::__construct()": "toxicAlert", + "CRM_Report_Form_Contribute_Detail::__construct()": "toxicAlert", + "CRM_Report_Form_Event_ParticipantListing::__construct()": "toxicAlert", + "CRM_Report_Form_Member_ContributionDetail::__construct()": "toxicAlert", + "CRM_UF_Form_Field::buildQuickForm()": "toxicAlert", + "CRM_Upgrade_Incremental_php_FourThree::createFinancialRecords()": "toxicAlert", + "CRM_Utils_Date::relativeToAbsolute()": "toxicAlert", + "CRM_Utils_Mail_EmailProcessor::_process()": "toxicAlert", + "ImportCiviSeleniumTestCase::importContacts()": "toxicAlert", + "WebTest_Contribute_OnBehalfOfOrganization::_testUserWithMoreThanOneRelationship()": "toxicAlert", + "WebTest_Profile_BatchUpdateTest::testBatchUpdate()": "toxicAlert", + "api_v3_JobTest::getMergeLocations()": "toxicAlert", + "api_v3_JobTest::getMergeSets()": "toxicAlert" } } \ No newline at end of file diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 47253a0e1333..376e56ecbac9 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -1,112 +1,248 @@ The following people and organizations sponsored and/or contributed new and improved features to the project. +************************************************ +Code Contributors for 5.x +************************************************ + +CiviCRM - Coleman Watts, Tim Otten + +AGH Strategies - Alice Frumin, Andrew Hunt, Eli Lisseck +Agileware - Francis Whittle, Justin Freeman, Pengyi Zhang +Andrew Thompson +applicado +Australian Greens - Seamus Lee +Bastien Ho +Blackfly Solutions - Alan Dixon +Calibrate - Wannes De Roy +Caltha - Tomasz Pietrzkowski +CEDC - Laryn Kragt Bakker +Chris Burgess +CiviCoop - Jaap Jansma +CiviDesk - Sunil Pawar, Yashodha Chaku +CompuCorp - Camilo Rodriguez, Davi Alexandre, Debarshi Bhaumik, Michael Devery, + Mukesh Ram, Omar Abu Hussein, René Olivo, Vinu Varshith Sekar +Coop SymbioTIC - Mathieu Lutfy, Samuel Vanhove +Davis Media Access - Darrick Servis +Electronic Frontier Foundation - Mark Burdett +eQuality Technology - Greg Rundlett +Freeform Solutions - Herb van den Dool +Fuzion - Jitendra Purohit +Ginkgo Street Labs - Frank Gómez +Hossein Amin +JMA Consulting - Joe Murray, Monish Deb +Johan Vervloet +John Kingsnorth +Joinery - Allen Shaw +Kanzu Code - Carl Andrew Lema +Kompetenzzentrum Technik-Diversity-Chancengleichheit - Niels Heinemann +Left Join Labs - Sean Madsen +Lighthouse Design and Consulting - Brian Shaughnessy +Łukasz Krutul +Megaphone Technology Consulting - Jon Goldberg +MJW Consulting - Matthew Wire +myDropWizard - David Snopek +Naomi Rosenberg +Olivier Tétard +OSSeed Technologies - Madhavi Malgaonkar +Oxfam Germany - Thomas Schüttler, Yuliyana Liyana +Pradeep Nayak +Progressive Technology Project - Jamie McClelland +Richard van Oosterhout +Romain Thouvenin +Squiffle Consulting - Aidan Saunders +Systopia - Björn Endres +Tadpole Collective - Kevin Cristiano +Third Sector Design - Michael McAndrew +Tom Bloor +Wikimedia Foundation - Eileen McNaughton +Wildsight - Lars Sanders-Green +Will Long + ************************************************ Key Contributors and Sponsors for 4.7 ************************************************ -CiviCRM Team - Atif Shaikh, Coleman Watts, David Greenberg, Eileen McNaughton, - Jitendra Purohit, Josh Gowan, Kurund Jalmi, - Michael McAndrew, Monish Deb, Rohan Ramesh Katkar, Tim Otten, - Yashodha Chaku +CiviCRM - Coleman Watts, Josh Gowans, Tim Otten -AGH Strategies - Andrew Hunt, Tyrell Cook, Nikki Murray -Agileware - Francis Whittle +Aaron Jones +Abhikalak Consultants - Amal Sharma +AGH Strategies - Alice Frumin, Andrew Hunt, Eli Lisseck, Nikki Murray, Tommy + Bobo, Tyrell Cook +Agileware - Alok Patel, Francis Whittle, Iris Abarquez, Justin Freeman, Vaibhav + Sagar +András Molnár Andrew West +AppChecker Aputsiaĸ Niels Janussen -Aron Novak -Backoffice Thinking +Arkadiusz Rzadkowolski +Arun Singh +ATD Fourth World - Véronique Gratioulet +Atif Shaikh +Australian Greens - Seamus Lee +Awebon Technologies - Karthikeyan Balasubramanian +BackOffice Thinking - Hassan Farooq Barbara Miller +Black Brick Software - David Hayes +Blackfly Solutions - Alan Dixon +British Humanist Association - Andrew West Borislav Zlatanov Brian Dombrowski +Brooks Digital - Spencer Brooks Caroline Badley -Christian Wach +CEDC - Laryn Kragt Bakker +Chanun Chirattikanon Charlie DeTar +Chirojeugd Vlaanderen - Johan Vervloet +Chris Burgess +Christian Wach Circle Interactive - Dave Jenkins -CiviCoop - Jaap Jansma -CiviDesk - Nicolas Ganivet, Sunil Pawar, Virginie Ganivet -Compucorp - Guanhuan Chen, Jamie Novick -CiviCoop - Jaap Jansma +CiviCoop - Erik Hommel, Jaap Jansma +CiviDesk - Nicolas Ganivet, Sunil Pawar, Virginie Ganivet, Yashodha Chaku +CiviFirst - John Kirk +Community Builders - Dejan Lukic +Community IT Academy - William Mortada +CompuCorp - Camilo Rodriguez, Guanhuan Chen, Kacper Warda, Jamie Novick, Michael + Devery, Mukesh Ram, Omar Abu Hussein Coop SymbioTIC - Mathieu Lutfy, Samuel Vanhove Dave D +Dave Greenberg David Hayes +Deepak Srivastava +Denver DataMan - Steve Kessler Dhanesh Dhuri +Daniël van Vuuren Dmitry Smirnov +Donald Lobo +E-Dynamics - Franky Van Liedekerke +Eaiman Shoshi +Effy Elden +Electronic Frontier Foundation - Mark Burdett Elin Waring -Emphanos LLC - Allen Shaw +Emphanos LLC +Ergon Logic Enterprises - Christopher Gervais +Erich Schulz Esantanche +Francesc Bassas i Bullich Freeform Solutions - Lola Slade, Stephanie Gray, Herb van den Dool Future First - David Knoll, John Prescott -Fuzion NZ - Chris Burgess, Eileen McNaughton, Peter Davis, Torrance Hodgson +Fuzion - Peter Davis, Torrance Hodgson, Jitendra Purohit Giant Rabbit - Peter Haight -Ginkgo Street Labs - Frank Gomez, Galata Tona, Michael Daryabeygi, Roshani Kothari, Toby Lounsbury +Ginkgo Street Labs - Frank Gómez, Galata Tona, Michael Daryabeygi, Roshani + Kothari +Gizra - Aron Novak +Greenleaf Advancement - Guy Iaccarino, Karen Stevenson +Hartmann Computer Consulting - Peter Hartmann +iXiam - Luciano Spiegel Jake Martin White +JazzMan +jernic +Jérôme Lebleu +JMA Consulting - Edsel Lopez, Joe Murray, Monish Deb Joanne Chester Joe McLaughlin -Johan Vervloet -John P Kirk +John Kingsnorth +Joinery - Allen Shaw +Joost Fock Joris -JMA Consulting - Joe Murray, Pradeep Nayak, Edsel Lopez -gah242s -Greenleaf Advancement - Guy Iaccarino -K Sneed Consulting - Kate Sneed +Kanzu Code - Carl Andrew Lema Kemal Bay Ken West Kevin Levie +Kevin Reynen +Klaas Eikelboom +Klangsoft - David Reedy Jr +Kompetenzzentrum Technik-Diversity-Chancengleichheit - Niels Heinemann Korlon - Stuart Gaston -kreynen -Laryn -Lesley Evensen (zorgalina) +K Sneed Consulting - Kate Sneed +Left Join Labs - Sean Madsen +Lemniscus - Noah Miller +Lesley Evensen Lighthouse Consulting and Design - Brian Shaughnessy +Marc Brazeau Marty Wright -Matthew Wire Mattias Michaux +Megaphone Technology Consulting - Jon Goldberg +Michael Hurwicz +Mihael Mladenov +Milton Zurita +MJW Consulting - Matthew Wire Mohit Aggarwal +MongoDB - A. Jesse Jiryu Davis +mountev +myDropWizard - David Snopek +Nathan Brettell National Urban League - Lisa Taliano +Neuwald Tecnologia da Informação - Arthur Almeida Nicholai Burton Niels Heinemann New York City Council New York State Senate - Ken Zalewski +Noah's Light Foundation - Carlos Loeza Northbridge Digital - Oliver Gibson Olaf Buddenhagen -Palante Technology Cooperative - Jon Goldberg, Joseph Lacey +Olivier Hertrich +Oxfam Germany - Thomas Schüttler +Palante Technology Cooperative - Joseph Lacey Paul Campbell -Progressive Tech Project - Alice Aguilar, Jamie McClelland +Pawel Nowak +PowDevel - Beto Aveiga +Pradeep Nayak +Progressive Technology Project - Alice Aguilar, Jamie McClelland +Randy Tobias +Redfin Solutions - Chris Wells Richard Van Oosterhout -RocXa +Rohan Ramesh Katkar +Romain Thouvenin +Rupal Javiya +Samson Alajede Saurabh Batra -Seamus Lee -Seb35 +Sébastien Beyou Semper IT - Karin Gerritsen +Sharique Ahmed Farooqui Shawn Holt -Skvare - Jeremy Proffitt, Peter Petrik +Skvare - Jeremy Proffitt, Mark Hanna, Peter Petrik Smiling Heart Enterprises - Neil Planchon +Spry Digital - Ellen Hendricks Squiffle Consulting - Aidan Saunders +Stan Dragnev Stephen Palmstrom Symbiotic - Mathieu Lutfy, Samuel Vanhove -Systopia - Björn Endres, Niko Bochan -Tadpole - Dana Skallman, Kevin Cristiano +Systopia - Björn Endres, Niko Bochan, Philipp Batroff +Tadpole Collective - Dana Skallman, Kevin Cristiano +Team Expansion - Greg Harris Tech to the People - Xavier Dutoit +Third Sector Design - Michael McAndrew Thomas Leichtuss +Thomas Schüttler Tim Mallezie +Timbsoft Technologies - Tunbola Ogunwande +Tobias Lounsbury Torenware Networks - Rob Thorne -University of Cambridge – Alex Corr, John Kingsnorth -Veda Consulting - Parvez Saleh, Deepak Srivastava, Kajan +University of Cambridge – Alex Corr +Vasantha Kaje +Veda Consulting - Parvez Saleh, Kajan +Vedant Rathore +Vikas Kumar +Vinu Varshith Sekar Wanna Pixel - Nathan Porter, Marisa Porter -Web Access - Sudha Bisht -Wikimedia Foundation - Adam Wight +We Move Europe/Caltha - Tomasz Pietrzkowski +Web Access - Kurund Jalmi, Sudha Bisht +Wikimedia Foundation - Adam Wight, Eileen McNaughton, Elliott Eggleston, Maggie + Epps +Will Long yurg -zarandras ************************************************ Key Contributors and Sponsors for 4.6 ************************************************ CiviCRM Team - Atif Shaikh, Coleman Watts, David Greenberg, Donald Lobo, - Eileen McNaughton, Jitendra Purohit, Josh Gowan, Kurund Jalmi, + Eileen McNaughton, Jitendra Purohit, Josh Gowan, Kurund Jalmi, Michael McAndrew, Monish Deb, Rohan Ramesh Katkar, Tim Otten, Yashodha Chaku -ADG Communications - Steve Binkowski +ADG Communications - Steve Binkowski AGH Strategies - Andrew Hunt, Jane Hanley, Tommy Bobo, Tyrell Cook +Agileware - Justin Freeman, Francis Whittle, Iris Abarquez, Vaibhav Sagar Alex C Allan Chappell Amnesty International Spain - Carlos Capote @@ -116,6 +252,7 @@ Arete Imagine - Marisa Porter, Nate Porter Asylum Hill Congregational Church Blackfly Solutions - Alan Dixon Botanical Society of America - Toby Lounsbury +Chirojeugd Vlaanderen - Johan Vervloet Christian Wach Chris Ward Circle Interactive - Dave Moreton, Andrew Walker, Dave Jenkins, Maya Gibbs @@ -139,7 +276,6 @@ Gnu.org - David Thompson Jaka Kranjc JMA Consulting - Joe Murray, Pradeep Nayak, Edsel Lopez Joanne Chester -Johan Vervloet John Kingsnorth jsnyder83 Kathryn Benedicto diff --git a/CRM/ACL/API.php b/CRM/ACL/API.php index 3337c4ab9b89..80855ac01b65 100644 --- a/CRM/ACL/API.php +++ b/CRM/ACL/API.php @@ -1,9 +1,9 @@ ts('Contact'), 'civicrm_acl_role' => ts('ACL Role'), - ); + ]; } return self::$_entityTable; } @@ -64,12 +64,12 @@ public static function entityTable() { */ public static function objectTable() { if (!self::$_objectTable) { - self::$_objectTable = array( + self::$_objectTable = [ 'civicrm_contact' => ts('Contact'), 'civicrm_group' => ts('Group'), 'civicrm_saved_search' => ts('Contact Group'), 'civicrm_admin' => ts('Import'), - ); + ]; } return self::$_objectTable; } @@ -79,14 +79,14 @@ public static function objectTable() { */ public static function operation() { if (!self::$_operation) { - self::$_operation = array( + self::$_operation = [ 'View' => ts('View'), 'Edit' => ts('Edit'), 'Create' => ts('Create'), 'Delete' => ts('Delete'), 'Search' => ts('Search'), 'All' => ts('All'), - ); + ]; } return self::$_operation; } @@ -94,6 +94,8 @@ public static function operation() { /** * Construct a WHERE clause to handle permissions to $object_* * + * @deprecated + * * @param array $tables * Any tables that may be needed in the FROM. * @param string $operation @@ -115,16 +117,17 @@ public static function permissionClause( $object_table = NULL, $object_id = NULL, $acl_id = NULL, $acl_role = FALSE ) { + CRM_Core_Error::deprecatedFunctionWarning('unknown - this is really old & not used in core'); $dao = new CRM_ACL_DAO_ACL(); - $t = array( + $t = [ 'ACL' => self::getTableName(), 'ACLRole' => 'civicrm_acl_role', 'ACLEntityRole' => CRM_ACL_DAO_EntityRole::getTableName(), 'Contact' => CRM_Contact_DAO_Contact::getTableName(), 'Group' => CRM_Contact_DAO_Group::getTableName(), 'GroupContact' => CRM_Contact_DAO_GroupContact::getTableName(), - ); + ]; $contact_id = CRM_Core_Session::getLoggedInContactID(); @@ -155,7 +158,7 @@ public static function permissionClause( } } - $query = array(); + $query = []; /* Query for permissions granted to all contacts in the domain */ @@ -258,9 +261,9 @@ public static function permissionClause( $dao->query($union); - $allow = array(0); - $deny = array(0); - $override = array(); + $allow = [0]; + $deny = [0]; + $override = []; while ($dao->fetch()) { /* Instant bypass for the following cases: @@ -335,7 +338,7 @@ public static function permissionClause( public static function getClause($table, $id, &$tables) { $table = CRM_Utils_Type::escape($table, 'String'); $id = CRM_Utils_Type::escape($id, 'Integer'); - $whereTables = array(); + $whereTables = []; $ssTable = CRM_Contact_BAO_SavedSearch::getTableName(); @@ -364,7 +367,7 @@ public static function getClause($table, $id, &$tables) { * Assoc. array of the ACL rule's properties */ public function toArray($format = '%s', $hideEmpty = FALSE) { - $result = array(); + $result = []; if (!self::$_fieldKeys) { $fields = CRM_ACL_DAO_ACL::fields(); @@ -394,7 +397,7 @@ public function toArray($format = '%s', $hideEmpty = FALSE) { * Array of assoc. arrays of ACL rules */ public static function &getACLs($contact_id = NULL, $group_id = NULL, $aclRoles = FALSE) { - $results = array(); + $results = []; if (empty($contact_id)) { return $results; @@ -502,7 +505,7 @@ public static function &getACLRoles($contact_id = NULL, $group_id = NULL) { } } - $results = array(); + $results = []; $rule->query($query); @@ -532,7 +535,7 @@ public static function &getGroupACLs($contact_id, $aclRoles = FALSE) { $acl = self::getTableName(); $c2g = CRM_Contact_BAO_GroupContact::getTableName(); $group = CRM_Contact_BAO_Group::getTableName(); - $results = array(); + $results = []; if ($contact_id) { $query = " @@ -600,7 +603,7 @@ public static function &getGroupACLRoles($contact_id) { AND $c2g.contact_id = $contact_id AND $c2g.status = 'Added'"; - $results = array(); + $results = []; $rule->query($query); @@ -641,7 +644,7 @@ public static function &getGroupACLRoles($contact_id) { * Assoc array of ACL rules */ public static function &getAllByContact($contact_id) { - $result = array(); + $result = []; /* First, the contact-specific ACLs, including ACL Roles */ $result += self::getACLs($contact_id, NULL, TRUE); @@ -680,12 +683,13 @@ public static function retrieve(&$params, &$defaults) { * @param bool $is_active * Value we want to set the is_active field. * - * @return Object - * DAO object on success, null otherwise + * @return bool + * true if we found and updated the object, else false */ public static function setIsActive($id, $is_active) { - // note this also resets any ACL cache - CRM_Core_BAO_Cache::deleteGroup('contact fields'); + Civi::cache('fields')->flush(); + // reset ACL and system caches. + CRM_Core_BAO_Cache::resetCaches(); return CRM_Core_DAO::setFieldValue('CRM_ACL_DAO_ACL', $id, 'is_active', $is_active); } @@ -715,7 +719,7 @@ public static function check($str, $contactID) { AND a.object_table = %1 AND a.id IN ( $aclKeys ) "; - $params = array(1 => array($str, 'String')); + $params = [1 => [$str, 'String']]; $count = CRM_Core_DAO::singleValueQuery($query, $params); return ($count) ? TRUE : FALSE; @@ -733,7 +737,7 @@ public static function whereClause($type, &$tables, &$whereTables, $contactID = $acls = CRM_ACL_BAO_Cache::build($contactID); $whereClause = NULL; - $clauses = array(); + $clauses = []; if (!empty($acls)) { $aclKeys = array_keys($acls); @@ -752,12 +756,12 @@ public static function whereClause($type, &$tables, &$whereTables, $contactID = $dao = CRM_Core_DAO::executeQuery($query); // do an or of all the where clauses u see - $ids = array(); + $ids = []; while ($dao->fetch()) { // make sure operation matches the type TODO if (self::matchType($type, $dao->operation)) { if (!$dao->object_id) { - $ids = array(); + $ids = []; $whereClause = ' ( 1 ) '; break; } @@ -774,60 +778,27 @@ public static function whereClause($type, &$tables, &$whereTables, $contactID = AND g.is_active = 1 "; $dao = CRM_Core_DAO::executeQuery($query); - $staticGroupIDs = array(); - $cachedGroupIDs = array(); + $groupIDs = []; + $groupContactCacheClause = FALSE; while ($dao->fetch()) { - // currently operation is restrcited to VIEW/EDIT - if ($dao->where_clause) { - if ($dao->select_tables) { - $tmpTables = array(); - foreach (unserialize($dao->select_tables) as $tmpName => $tmpInfo) { - if ($tmpName == '`civicrm_group_contact-' . $dao->id . '`') { - $tmpName = '`civicrm_group_contact-ACL`'; - $tmpInfo = str_replace('civicrm_group_contact-' . $dao->id, 'civicrm_group_contact-ACL', $tmpInfo); - } - elseif ($tmpName == '`civicrm_group_contact_cache_' . $dao->id . '`') { - $tmpName = '`civicrm_group_contact_cache-ACL`'; - $tmpInfo = str_replace('civicrm_group_contact_cache_' . $dao->id, 'civicrm_group_contact_cache-ACL', $tmpInfo); - } - $tmpTables[$tmpName] = $tmpInfo; - } - $tables = array_merge($tables, - $tmpTables - ); - } - if ($dao->where_tables) { - $tmpTables = array(); - foreach (unserialize($dao->where_tables) as $tmpName => $tmpInfo) { - if ($tmpName == '`civicrm_group_contact-' . $dao->id . '`') { - $tmpName = '`civicrm_group_contact-ACL`'; - $tmpInfo = str_replace('civicrm_group_contact-' . $dao->id, 'civicrm_group_contact-ACL', $tmpInfo); - $staticGroupIDs[] = $dao->id; - } - elseif ($tmpName == '`civicrm_group_contact_cache_' . $dao->id . '`') { - $tmpName = '`civicrm_group_contact_cache-ACL`'; - $tmpInfo = str_replace('civicrm_group_contact_cache_' . $dao->id, 'civicrm_group_contact_cache-ACL', $tmpInfo); - $cachedGroupIDs[] = $dao->id; - } - $tmpTables[$tmpName] = $tmpInfo; - } - $whereTables = array_merge($whereTables, $tmpTables); - } - } + $groupIDs[] = $dao->id; - if (($dao->saved_search_id || $dao->children || $dao->parents) && - $dao->cache_date == NULL - ) { - CRM_Contact_BAO_GroupContactCache::load($dao); + if (($dao->saved_search_id || $dao->children || $dao->parents)) { + if ($dao->cache_date == NULL) { + CRM_Contact_BAO_GroupContactCache::load($dao); + } + $groupContactCacheClause = " UNION SELECT contact_id FROM civicrm_group_contact_cache WHERE group_id IN (" . implode(', ', $groupIDs) . ")"; } - } - if ($staticGroupIDs) { - $clauses[] = '( `civicrm_group_contact-ACL`.group_id IN (' . implode(', ', $staticGroupIDs) . ') AND `civicrm_group_contact-ACL`.status IN ("Added") )'; } - if ($cachedGroupIDs) { - $clauses[] = '`civicrm_group_contact_cache-ACL`.group_id IN (' . implode(', ', $cachedGroupIDs) . ')'; + if ($groupIDs) { + $clauses[] = "( + `contact_a`.id IN ( + SELECT contact_id FROM civicrm_group_contact WHERE group_id IN (" . implode(', ', $groupIDs) . ") AND status = 'Added' + $groupContactCacheClause + ) + )"; } } } @@ -864,23 +835,28 @@ public static function group( ) { $userCacheKey = "{$contactID}_{$type}_{$tableName}_" . CRM_Core_Config::domainID() . '_' . md5(implode(',', array_merge((array) $allGroups, (array) $includedGroups))); if (empty(Civi::$statics[__CLASS__]['permissioned_groups'])) { - Civi::$statics[__CLASS__]['permissioned_groups'] = array(); + Civi::$statics[__CLASS__]['permissioned_groups'] = []; } if (!empty(Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey])) { return Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey]; } + if ($allGroups == NULL) { + $allGroups = CRM_Contact_BAO_Contact::buildOptions('group_id', NULL, ['onlyActive' => FALSE]); + } + $acls = CRM_ACL_BAO_Cache::build($contactID); - $ids = array(); + $ids = []; if (!empty($acls)) { $aclKeys = array_keys($acls); $aclKeys = implode(',', $aclKeys); - $cacheKey = "$tableName-$aclKeys"; + $cacheKey = CRM_Utils_Cache::cleanKey("$tableName-$aclKeys"); $cache = CRM_Utils_Cache::singleton(); $ids = $cache->get($cacheKey); if (!$ids) { + $ids = []; $query = " SELECT a.operation, a.object_id FROM civicrm_acl_cache c, civicrm_acl a @@ -891,7 +867,7 @@ public static function group( GROUP BY a.operation,a.object_id ORDER BY a.object_id "; - $params = array(1 => array($tableName, 'String')); + $params = [1 => [$tableName, 'String']]; $dao = CRM_Core_DAO::executeQuery($query, $params); while ($dao->fetch()) { if ($dao->object_id) { diff --git a/CRM/ACL/BAO/Cache.php b/CRM/ACL/BAO/Cache.php index 392d15f48a66..c165e940c0d6 100644 --- a/CRM/ACL/BAO/Cache.php +++ b/CRM/ACL/BAO/Cache.php @@ -1,9 +1,9 @@ array($id, 'Integer')); + $params = [1 => [$id, 'Integer']]; if ($id == 0) { $query .= " OR contact_id IS NULL"; @@ -83,7 +83,7 @@ public static function retrieve($id) { $dao = CRM_Core_DAO::executeQuery($query, $params); - $cache = array(); + $cache = []; while ($dao->fetch()) { $cache[$dao->acl_id] = 1; } @@ -96,7 +96,7 @@ public static function retrieve($id) { */ public static function store($id, &$cache) { foreach ($cache as $aclID => $data) { - $dao = new CRM_ACL_DAO_Cache(); + $dao = new CRM_ACL_BAO_Cache(); if ($id) { $dao->contact_id = $id; } @@ -122,7 +122,7 @@ public static function deleteEntry($id) { DELETE FROM civicrm_acl_cache WHERE contact_id = %1 "; - $params = array(1 => array($id, 'Integer')); + $params = [1 => [$id, 'Integer']]; CRM_Core_DAO::executeQuery($query, $params); } @@ -142,6 +142,9 @@ public static function updateEntry($id) { * Deletes all the cache entries. */ public static function resetCache() { + if (!CRM_Core_Config::isPermitCacheFlushMode()) { + return; + } // reset any static caching self::$_cache = NULL; @@ -151,7 +154,12 @@ public static function resetCache() { WHERE modified_date IS NULL OR (modified_date <= %1) "; - $params = array(1 => array(CRM_Contact_BAO_GroupContactCache::getCacheInvalidDateTime(), 'String')); + $params = [ + 1 => [ + CRM_Contact_BAO_GroupContactCache::getCacheInvalidDateTime(), + 'String', + ], + ]; CRM_Core_DAO::singleValueQuery($query, $params); // CRM_Core_DAO::singleValueQuery("TRUNCATE TABLE civicrm_acl_contact_cache"); // No, force-commits transaction diff --git a/CRM/ACL/BAO/EntityRole.php b/CRM/ACL/BAO/EntityRole.php index 2146e0288897..8ed2b2e0b816 100644 --- a/CRM/ACL/BAO/EntityRole.php +++ b/CRM/ACL/BAO/EntityRole.php @@ -1,9 +1,9 @@ ts('Contact'), 'civicrm_group' => ts('Group'), - ); + ]; } return self::$_entityTable; } @@ -80,8 +80,8 @@ public static function retrieve(&$params, &$defaults) { * @param bool $is_active * Value we want to set the is_active field. * - * @return Object - * DAO object on success, null otherwise + * @return bool + * true if we found and updated the object, else false */ public static function setIsActive($id, $is_active) { return CRM_Core_DAO::setFieldValue('CRM_ACL_DAO_EntityRole', $id, 'is_active', $is_active); diff --git a/CRM/ACL/DAO/ACL.php b/CRM/ACL/DAO/ACL.php index a4e3359c6dde..d5a62e863ada 100644 --- a/CRM/ACL/DAO/ACL.php +++ b/CRM/ACL/DAO/ACL.php @@ -1,322 +1,329 @@ __table = 'civicrm_acl'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL ID') , - 'description' => 'Unique table ID', - 'required' => true, + 'title' => ts('ACL ID'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'where' => 'civicrm_acl.id', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'name' => array( + ], + 'name' => [ 'name' => 'name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('ACL Name') , - 'description' => 'ACL Name.', + 'title' => ts('ACL Name'), + 'description' => ts('ACL Name.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_acl.name', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'deny' => array( + ], + ], + 'deny' => [ 'name' => 'deny', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Deny ACL?') , - 'description' => 'Is this ACL entry Allow (0) or Deny (1) ?', - 'required' => true, + 'title' => ts('Deny ACL?'), + 'description' => ts('Is this ACL entry Allow (0) or Deny (1) ?'), + 'required' => TRUE, + 'where' => 'civicrm_acl.deny', + 'default' => '0', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Radio', - ) , - ) , - 'entity_table' => array( + ], + ], + 'entity_table' => [ 'name' => 'entity_table', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('ACL Entity') , - 'description' => 'Table of the object possessing this ACL entry (Contact, Group, or ACL Group)', - 'required' => true, + 'title' => ts('ACL Entity'), + 'description' => ts('Table of the object possessing this ACL entry (Contact, Group, or ACL Group)'), + 'required' => TRUE, 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_acl.entity_table', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'entity_id' => array( + ], + 'entity_id' => [ 'name' => 'entity_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Entity ID') , - 'description' => 'ID of the object possessing this ACL', + 'title' => ts('Entity ID'), + 'description' => ts('ID of the object possessing this ACL'), + 'where' => 'civicrm_acl.entity_id', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'operation' => array( + ], + 'operation' => [ 'name' => 'operation', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('ACL Operation') , - 'description' => 'What operation does this ACL entry control?', - 'required' => true, + 'title' => ts('ACL Operation'), + 'description' => ts('What operation does this ACL entry control?'), + 'required' => TRUE, 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, + 'where' => 'civicrm_acl.operation', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_ACL_BAO_ACL::operation', - ) - ) , - 'object_table' => array( + ], + ], + 'object_table' => [ 'name' => 'object_table', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('ACL Object') , - 'description' => 'The table of the object controlled by this ACL entry', + 'title' => ts('ACL Object'), + 'description' => ts('The table of the object controlled by this ACL entry'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_acl.object_table', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'object_id' => array( + ], + 'object_id' => [ 'name' => 'object_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL Object ID') , - 'description' => 'The ID of the object controlled by this ACL entry', + 'title' => ts('ACL Object ID'), + 'description' => ts('The ID of the object controlled by this ACL entry'), + 'where' => 'civicrm_acl.object_id', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'acl_table' => array( + ], + 'acl_table' => [ 'name' => 'acl_table', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('ACL Table') , - 'description' => 'If this is a grant/revoke entry, what table are we granting?', + 'title' => ts('ACL Table'), + 'description' => ts('If this is a grant/revoke entry, what table are we granting?'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_acl.acl_table', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'acl_id' => array( + ], + 'acl_id' => [ 'name' => 'acl_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL Group ID') , - 'description' => 'ID of the ACL or ACL group being granted/revoked', + 'title' => ts('ACL Group ID'), + 'description' => ts('ID of the ACL or ACL group being granted/revoked'), + 'where' => 'civicrm_acl.acl_id', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - ) , - 'is_active' => array( + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('ACL Is Active?') , - 'description' => 'Is this property active?', + 'title' => ts('ACL Is Active?'), + 'description' => ts('Is this property active?'), + 'where' => 'civicrm_acl.is_active', 'table_name' => 'civicrm_acl', 'entity' => 'ACL', 'bao' => 'CRM_ACL_BAO_ACL', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - ); + ], + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -324,10 +331,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -335,24 +343,30 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'index_acl_id' => array( + $indices = [ + 'index_acl_id' => [ 'name' => 'index_acl_id', - 'field' => array( + 'field' => [ 0 => 'acl_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_acl::0::acl_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/ACL/DAO/ACLCache.php b/CRM/ACL/DAO/ACLCache.php new file mode 100644 index 000000000000..cbf774e4b276 --- /dev/null +++ b/CRM/ACL/DAO/ACLCache.php @@ -0,0 +1,222 @@ +__table = 'civicrm_acl_cache'; + parent::__construct(); + } + + /** + * Returns foreign keys and entity references. + * + * @return array + * [CRM_Core_Reference_Interface] + */ + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'acl_id', 'civicrm_acl', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); + } + return Civi::$statics[__CLASS__]['links']; + } + + /** + * Returns all the column names of this table + * + * @return array + */ + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ + 'name' => 'id', + 'type' => CRM_Utils_Type::T_INT, + 'title' => ts('Cache ID'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'where' => 'civicrm_acl_cache.id', + 'table_name' => 'civicrm_acl_cache', + 'entity' => 'ACLCache', + 'bao' => 'CRM_ACL_DAO_ACLCache', + 'localizable' => 0, + ], + 'contact_id' => [ + 'name' => 'contact_id', + 'type' => CRM_Utils_Type::T_INT, + 'title' => ts('Cache Contact'), + 'description' => ts('Foreign Key to Contact'), + 'where' => 'civicrm_acl_cache.contact_id', + 'table_name' => 'civicrm_acl_cache', + 'entity' => 'ACLCache', + 'bao' => 'CRM_ACL_DAO_ACLCache', + 'localizable' => 0, + 'FKClassName' => 'CRM_Contact_DAO_Contact', + ], + 'acl_id' => [ + 'name' => 'acl_id', + 'type' => CRM_Utils_Type::T_INT, + 'title' => ts('Cache ACL'), + 'description' => ts('Foreign Key to ACL'), + 'required' => TRUE, + 'where' => 'civicrm_acl_cache.acl_id', + 'table_name' => 'civicrm_acl_cache', + 'entity' => 'ACLCache', + 'bao' => 'CRM_ACL_DAO_ACLCache', + 'localizable' => 0, + 'FKClassName' => 'CRM_ACL_DAO_ACL', + ], + 'modified_date' => [ + 'name' => 'modified_date', + 'type' => CRM_Utils_Type::T_TIMESTAMP, + 'title' => ts('Cache Modified Date'), + 'description' => ts('When was this cache entry last modified'), + 'required' => FALSE, + 'where' => 'civicrm_acl_cache.modified_date', + 'table_name' => 'civicrm_acl_cache', + 'entity' => 'ACLCache', + 'bao' => 'CRM_ACL_DAO_ACLCache', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); + } + return Civi::$statics[__CLASS__]['fields']; + } + + /** + * Return a mapping from field-name to the corresponding key (as used in fields()). + * + * @return array + * Array(string $name => string $uniqueName). + */ + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); + } + return Civi::$statics[__CLASS__]['fieldKeys']; + } + + /** + * Returns the names of this table + * + * @return string + */ + public static function getTableName() { + return self::$_tableName; + } + + /** + * Returns if this table needs to be logged + * + * @return bool + */ + public function getLog() { + return self::$_log; + } + + /** + * Returns the list of fields that can be imported + * + * @param bool $prefix + * + * @return array + */ + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_cache', $prefix, []); + return $r; + } + + /** + * Returns the list of fields that can be exported + * + * @param bool $prefix + * + * @return array + */ + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_cache', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_acl_id' => [ + 'name' => 'index_acl_id', + 'field' => [ + 0 => 'acl_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_acl_cache::0::acl_id', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; + } + +} diff --git a/CRM/ACL/DAO/Cache.php b/CRM/ACL/DAO/Cache.php deleted file mode 100644 index 16c1af6755b1..000000000000 --- a/CRM/ACL/DAO/Cache.php +++ /dev/null @@ -1,223 +0,0 @@ -__table = 'civicrm_acl_cache'; - parent::__construct(); - } - /** - * Returns foreign keys and entity references. - * - * @return array - * [CRM_Core_Reference_Interface] - */ - static function getReferenceColumns() { - if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'acl_id', 'civicrm_acl', 'id'); - CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); - } - return Civi::$statics[__CLASS__]['links']; - } - /** - * Returns all the column names of this table - * - * @return array - */ - static function &fields() { - if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( - 'name' => 'id', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Cache ID') , - 'description' => 'Unique table ID', - 'required' => true, - 'table_name' => 'civicrm_acl_cache', - 'entity' => 'Cache', - 'bao' => 'CRM_ACL_BAO_Cache', - 'localizable' => 0, - ) , - 'contact_id' => array( - 'name' => 'contact_id', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Cache Contact') , - 'description' => 'Foreign Key to Contact', - 'table_name' => 'civicrm_acl_cache', - 'entity' => 'Cache', - 'bao' => 'CRM_ACL_BAO_Cache', - 'localizable' => 0, - 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'acl_id' => array( - 'name' => 'acl_id', - 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Cache ACL') , - 'description' => 'Foreign Key to ACL', - 'required' => true, - 'table_name' => 'civicrm_acl_cache', - 'entity' => 'Cache', - 'bao' => 'CRM_ACL_BAO_Cache', - 'localizable' => 0, - 'FKClassName' => 'CRM_ACL_DAO_ACL', - ) , - 'modified_date' => array( - 'name' => 'modified_date', - 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Cache Modified Date') , - 'description' => 'When was this cache entry last modified', - 'required' => false, - 'table_name' => 'civicrm_acl_cache', - 'entity' => 'Cache', - 'bao' => 'CRM_ACL_BAO_Cache', - 'localizable' => 0, - ) , - ); - CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); - } - return Civi::$statics[__CLASS__]['fields']; - } - /** - * Return a mapping from field-name to the corresponding key (as used in fields()). - * - * @return array - * Array(string $name => string $uniqueName). - */ - static function &fieldKeys() { - if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { - Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); - } - return Civi::$statics[__CLASS__]['fieldKeys']; - } - /** - * Returns the names of this table - * - * @return string - */ - static function getTableName() { - return self::$_tableName; - } - /** - * Returns if this table needs to be logged - * - * @return boolean - */ - function getLog() { - return self::$_log; - } - /** - * Returns the list of fields that can be imported - * - * @param bool $prefix - * - * @return array - */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_cache', $prefix, array()); - return $r; - } - /** - * Returns the list of fields that can be exported - * - * @param bool $prefix - * - * @return array - */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_cache', $prefix, array()); - return $r; - } - /** - * Returns the list of indices - */ - public static function indices($localize = TRUE) { - $indices = array( - 'index_acl_id' => array( - 'name' => 'index_acl_id', - 'field' => array( - 0 => 'acl_id', - ) , - 'localizable' => false, - 'sig' => 'civicrm_acl_cache::0::acl_id', - ) , - ); - return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; - } -} diff --git a/CRM/ACL/DAO/EntityRole.php b/CRM/ACL/DAO/EntityRole.php index 5ecda4016a70..ae09968341da 100644 --- a/CRM/ACL/DAO/EntityRole.php +++ b/CRM/ACL/DAO/EntityRole.php @@ -1,203 +1,197 @@ __table = 'civicrm_acl_entity_role'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Entity Role') , - 'description' => 'Unique table ID', - 'required' => true, + 'title' => ts('Entity Role'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'where' => 'civicrm_acl_entity_role.id', 'table_name' => 'civicrm_acl_entity_role', 'entity' => 'EntityRole', 'bao' => 'CRM_ACL_BAO_EntityRole', 'localizable' => 0, - ) , - 'acl_role_id' => array( + ], + 'acl_role_id' => [ 'name' => 'acl_role_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL Role ID') , - 'description' => 'Foreign Key to ACL Role (which is an option value pair and hence an implicit FK)', - 'required' => true, + 'title' => ts('ACL Role ID'), + 'description' => ts('Foreign Key to ACL Role (which is an option value pair and hence an implicit FK)'), + 'required' => TRUE, + 'where' => 'civicrm_acl_entity_role.acl_role_id', 'table_name' => 'civicrm_acl_entity_role', 'entity' => 'EntityRole', 'bao' => 'CRM_ACL_BAO_EntityRole', 'localizable' => 0, - ) , - 'entity_table' => array( + ], + 'entity_table' => [ 'name' => 'entity_table', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Entity Table') , - 'description' => 'Table of the object joined to the ACL Role (Contact or Group)', - 'required' => true, + 'title' => ts('Entity Table'), + 'description' => ts('Table of the object joined to the ACL Role (Contact or Group)'), + 'required' => TRUE, 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_acl_entity_role.entity_table', 'table_name' => 'civicrm_acl_entity_role', 'entity' => 'EntityRole', 'bao' => 'CRM_ACL_BAO_EntityRole', 'localizable' => 0, - ) , - 'entity_id' => array( + ], + 'entity_id' => [ 'name' => 'entity_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL Entity ID') , - 'description' => 'ID of the group/contact object being joined', - 'required' => true, + 'title' => ts('ACL Entity ID'), + 'description' => ts('ID of the group/contact object being joined'), + 'required' => TRUE, + 'where' => 'civicrm_acl_entity_role.entity_id', 'table_name' => 'civicrm_acl_entity_role', 'entity' => 'EntityRole', 'bao' => 'CRM_ACL_BAO_EntityRole', 'localizable' => 0, - ) , - 'is_active' => array( + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('ACL Entity Role is Active') , - 'description' => 'Is this property active?', + 'title' => ts('ACL Entity Role is Active'), + 'description' => ts('Is this property active?'), + 'where' => 'civicrm_acl_entity_role.is_active', 'table_name' => 'civicrm_acl_entity_role', 'entity' => 'EntityRole', 'bao' => 'CRM_ACL_BAO_EntityRole', 'localizable' => 0, - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -205,10 +199,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_entity_role', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_entity_role', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -216,33 +211,39 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_entity_role', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_entity_role', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'index_role' => array( + $indices = [ + 'index_role' => [ 'name' => 'index_role', - 'field' => array( + 'field' => [ 0 => 'acl_role_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_acl_entity_role::0::acl_role_id', - ) , - 'index_entity' => array( + ], + 'index_entity' => [ 'name' => 'index_entity', - 'field' => array( + 'field' => [ 0 => 'entity_table', 1 => 'entity_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_acl_entity_role::0::entity_table::entity_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/ACL/Form/ACL.php b/CRM/ACL/Form/ACL.php index c440178d08e2..7f9419721437 100644 --- a/CRM/ACL/Form/ACL.php +++ b/CRM/ACL/Form/ACL.php @@ -1,9 +1,9 @@ add('text', 'name', ts('Description'), CRM_Core_DAO::getAttribute('CRM_ACL_DAO_ACL', 'name'), TRUE); - $operations = array('' => ts('- select -')) + CRM_ACL_BAO_ACL::operation(); + $operations = ['' => ts('- select -')] + CRM_ACL_BAO_ACL::operation(); $this->add('select', 'operation', ts('Operation'), $operations, TRUE ); - $objTypes = array( + $objTypes = [ '1' => ts('A group of contacts'), '2' => ts('A profile'), '3' => ts('A set of custom data fields'), - ); + ]; if (CRM_Core_Permission::access('CiviEvent')) { $objTypes['4'] = ts('Events'); } - $extra = array('onclick' => "showObjectSelect();"); + $extra = ['onclick' => "showObjectSelect();"]; $this->addRadio('object_type', ts('Type of Data'), $objTypes, @@ -140,31 +140,31 @@ public function buildQuickForm() { ); $label = ts('Role'); - $role = array( + $role = [ '-1' => ts('- select role -'), '0' => ts('Everyone'), - ) + CRM_Core_OptionGroup::values('acl_role'); + ] + CRM_Core_OptionGroup::values('acl_role'); $this->add('select', 'entity_id', $label, $role, TRUE); - $group = array( + $group = [ '-1' => ts('- select -'), '0' => ts('All Groups'), - ) + CRM_Core_PseudoConstant::group(); + ] + CRM_Core_PseudoConstant::group(); - $customGroup = array( + $customGroup = [ '-1' => ts('- select -'), '0' => ts('All Custom Groups'), - ) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id'); + ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id'); - $ufGroup = array( + $ufGroup = [ '-1' => ts('- select -'), '0' => ts('All Profiles'), - ) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id'); + ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id'); - $event = array( + $event = [ '-1' => ts('- select -'), '0' => ts('All Events'), - ) + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); + ] + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); $this->add('select', 'group_id', ts('Group'), $group); $this->add('select', 'custom_group_id', ts('Custom Data'), $customGroup); @@ -173,7 +173,7 @@ public function buildQuickForm() { $this->add('checkbox', 'is_active', ts('Enabled?')); - $this->addFormRule(array('CRM_ACL_Form_ACL', 'formRule')); + $this->addFormRule(['CRM_ACL_Form_ACL', 'formRule']); } /** @@ -189,7 +189,7 @@ public static function formRule($params) { $errors['entity_id'] = ts('Please assign this permission to a Role.'); } - $validOperations = array('View', 'Edit'); + $validOperations = ['View', 'Edit']; $operationMessage = ts("Only 'View' and 'Edit' operations are valid for this type of data"); // Figure out which type of object we're permissioning on and make sure user has selected a value. @@ -254,7 +254,9 @@ public static function formRule($params) { */ public function postProcess() { // note this also resets any ACL cache - CRM_Core_BAO_Cache::deleteGroup('contact fields'); + Civi::cache('fields')->flush(); + // reset ACL and system caches. + CRM_Core_BAO_Cache::resetCaches(); if ($this->_action & CRM_Core_Action::DELETE) { CRM_ACL_BAO_ACL::del($this->_id); diff --git a/CRM/ACL/Form/ACLBasic.php b/CRM/ACL/Form/ACLBasic.php index 07b6df7bdad4..263b49592765 100644 --- a/CRM/ACL/Form/ACLBasic.php +++ b/CRM/ACL/Form/ACLBasic.php @@ -1,9 +1,9 @@ _id || $this->_id === '0' @@ -49,9 +49,9 @@ public function setDefaultValues() { WHERE entity_id = %1 AND ( object_table NOT IN ( 'civicrm_saved_search', 'civicrm_uf_group', 'civicrm_custom_group' ) ) "; - $params = array(1 => array($this->_id, 'Integer')); + $params = [1 => [$this->_id, 'Integer']]; $dao = CRM_Core_DAO::executeQuery($query, $params); - $defaults['object_table'] = array(); + $defaults['object_table'] = []; while ($dao->fetch()) { $defaults['object_table'][$dao->object_table] = 1; } @@ -75,14 +75,14 @@ public function buildQuickForm() { ts('ACL Type'), $permissions, NULL, NULL, TRUE, NULL, - array('
' . ts("%count contact has been reserved.", array('plural' => '%count contacts have been reserved.', 'count' => $countVoters)) . '
'; + $status = '' . ts("%count contact has been reserved.", ['plural' => '%count contacts have been reserved.', 'count' => $countVoters]) . '
'; if ($groupAdditions) { $status .= '' . ts('They have been added to %1.', - array(1 => implode(' ' . ts('and') . ' ', $groupAdditions)) + [1 => implode(' ' . ts('and') . ' ', $groupAdditions)] ) . '
'; } CRM_Core_Session::setStatus($status, ts('Reservation Added'), 'success'); @@ -281,10 +281,10 @@ public function postProcess() { // Error message if (count($this->_contactIds) > $countVoters) { CRM_Core_Session::setStatus(ts('Reservation did not add for %count contact.', - array( + [ 'plural' => 'Reservation did not add for %count contacts.', 'count' => (count($this->_contactIds) - $countVoters), - ) + ] ), ts('Notice')); } @@ -306,24 +306,24 @@ public function postProcess() { * @return array */ private function _addRespondentToGroup($contactIds) { - $groupAdditions = array(); + $groupAdditions = []; if (empty($contactIds)) { return $groupAdditions; } $params = $this->controller->exportValues($this->_name); - $groups = CRM_Utils_Array::value('groups', $params, array()); + $groups = CRM_Utils_Array::value('groups', $params, []); $newGroupName = CRM_Utils_Array::value('newGroupName', $params); $newGroupDesc = CRM_Utils_Array::value('newGroupDesc', $params); $newGroupId = NULL; //create new group. if ($newGroupName) { - $grpParams = array( + $grpParams = [ 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE, - ); + ]; $group = CRM_Contact_BAO_Group::create($grpParams); $groups[] = $newGroupId = $group->id; } diff --git a/CRM/Campaign/Form/Task/Result.php b/CRM/Campaign/Form/Task/Result.php index 98bd9fb73124..25f81fb7fdbd 100644 --- a/CRM/Campaign/Form/Task/Result.php +++ b/CRM/Campaign/Form/Task/Result.php @@ -1,9 +1,9 @@ addButtons(array( - array( - 'type' => 'done', - 'name' => ts('Done'), - 'isDefault' => TRUE, - ), - ) - ); + $this->addButtons([ + [ + 'type' => 'done', + 'name' => ts('Done'), + 'isDefault' => TRUE, + ], + ]); } } diff --git a/CRM/Campaign/Info.php b/CRM/Campaign/Info.php index 8667ca30c38c..9543c059d5b5 100644 --- a/CRM/Campaign/Info.php +++ b/CRM/Campaign/Info.php @@ -1,9 +1,9 @@ 'CiviCampaign', 'translatedName' => ts('CiviCampaign'), 'title' => ts('CiviCRM Campaign Engine'), 'search' => 1, 'showActivitiesInCore' => 1, - ); + ]; } - /** * @inheritDoc * @param bool $getAllUnconditionally @@ -64,35 +64,35 @@ public function getInfo() { * @return array */ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) { - $permissions = array( - 'administer CiviCampaign' => array( + $permissions = [ + 'administer CiviCampaign' => [ ts('administer CiviCampaign'), ts('Create new campaign, survey and petition types and their status'), - ), - 'manage campaign' => array( + ], + 'manage campaign' => [ ts('manage campaign'), ts('Create new campaigns, surveys and petitions, reserve respondents'), - ), - 'reserve campaign contacts' => array( + ], + 'reserve campaign contacts' => [ ts('reserve campaign contacts'), ts('Reserve campaign contacts for surveys and petitions'), - ), - 'release campaign contacts' => array( + ], + 'release campaign contacts' => [ ts('release campaign contacts'), ts('Release reserved campaign contacts for surveys and petitions'), - ), - 'interview campaign contacts' => array( + ], + 'interview campaign contacts' => [ ts('interview campaign contacts'), ts('Record survey and petition responses from their reserved contacts'), - ), - 'gotv campaign contacts' => array( + ], + 'gotv campaign contacts' => [ ts('GOTV campaign contacts'), ts('Record that contacts voted'), - ), - 'sign CiviCRM Petition' => array( + ], + 'sign CiviCRM Petition' => [ ts('sign CiviCRM Petition'), - ), - ); + ], + ]; if (!$descriptions) { foreach ($permissions as $name => $attr) { @@ -103,7 +103,6 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F return $permissions; } - /** * @inheritDoc * @return null @@ -130,6 +129,14 @@ public function registerTab() { return NULL; } + /** + * @inheritDoc + * @return string + */ + public function getIcon() { + return 'crm-i fa-star-o'; + } + /** * @inheritDoc * @return null @@ -154,20 +161,20 @@ public function creatNewShortcut(&$shortCuts) { if (CRM_Core_Permission::check('manage campaign') || CRM_Core_Permission::check('administer CiviCampaign') ) { - $shortCuts = array_merge($shortCuts, array( - array( + $shortCuts = array_merge($shortCuts, [ + [ 'path' => 'civicrm/campaign/add', 'query' => "reset=1&action=add", 'ref' => 'new-campaign', 'title' => ts('Campaign'), - ), - array( + ], + [ 'path' => 'civicrm/survey/add', 'query' => "reset=1&action=add", 'ref' => 'new-survey', 'title' => ts('Survey'), - ), - )); + ], + ]); } } diff --git a/CRM/Campaign/Page/AJAX.php b/CRM/Campaign/Page/AJAX.php index caaadfad8a08..ecec01993619 100644 --- a/CRM/Campaign/Page/AJAX.php +++ b/CRM/Campaign/Page/AJAX.php @@ -1,9 +1,9 @@ 'fail', 'voter_id' => $voterId, 'activity_id' => $params['interviewer_id'], - ); + ]; //time to validate custom data. $errors = CRM_Core_BAO_CustomField::validateCustomData($params); @@ -108,7 +108,7 @@ public static function loadOptionGroupDetails() { $id = CRM_Utils_Request::retrieve('option_group_id', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $status = 'fail'; - $opValues = array(); + $opValues = []; if ($id) { $groupParams['id'] = $id; @@ -136,10 +136,10 @@ public static function loadOptionGroupDetails() { $status = 'success'; } - $result = array( + $result = [ 'status' => $status, 'result' => $opValues, - ); + ]; CRM_Utils_JSON::output($result); } @@ -149,7 +149,7 @@ public function voterList() { $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $searchParams = explode(',', $searchCriteria); - $params = $searchRows = array(); + $params = $searchRows = []; foreach ($searchParams as $param) { if (!empty($_POST[$param])) { $params[$param] = $_POST[$param]; @@ -157,10 +157,10 @@ public function voterList() { } //format multi-select group and contact types. - foreach (array( - 'group', - 'contact_type', - ) as $param) { + foreach ([ + 'group', + 'contact_type', + ] as $param) { $paramValue = CRM_Utils_Array::value($param, $params); if ($paramValue) { unset($params[$param]); @@ -171,12 +171,12 @@ public function voterList() { } } - $voterClauseParams = array(); - foreach (array( - 'campaign_survey_id', - 'survey_interviewer_id', - 'campaign_search_voter_for', - ) as $fld) { + $voterClauseParams = []; + foreach ([ + 'campaign_survey_id', + 'survey_interviewer_id', + 'campaign_search_voter_for', + ] as $fld) { $voterClauseParams[$fld] = CRM_Utils_Array::value($fld, $params); } @@ -224,42 +224,42 @@ public function voterList() { } } - $selectorCols = array( + $selectorCols = [ 'sort_name', 'street_address', 'street_name', 'street_number', 'street_unit', - ); + ]; // get the data table params. - $dataTableParams = array( - 'sEcho' => array( + $dataTableParams = [ + 'sEcho' => [ 'name' => 'sEcho', 'type' => 'Integer', 'default' => 0, - ), - 'offset' => array( + ], + 'offset' => [ 'name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0, - ), - 'rowCount' => array( + ], + 'rowCount' => [ 'name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25, - ), - 'sort' => array( + ], + 'sort' => [ 'name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'sort_name', - ), - 'sortOrder' => array( + ], + 'sortOrder' => [ 'name' => 'sSortDir_0', 'type' => 'String', 'default' => 'asc', - ), - ); + ], + ]; foreach ($dataTableParams as $pName => $pValues) { $$pName = $pValues['default']; if (!empty($_POST[$pValues['name']])) { @@ -291,14 +291,14 @@ public function voterList() { $iTotal = $searchCount; - $selectorCols = array( + $selectorCols = [ 'contact_type', 'sort_name', 'street_address', 'street_name', 'street_number', 'street_unit', - ); + ]; $extraVoterColName = 'is_interview_conducted'; if ($params['campaign_search_voter_for'] == 'reserve') { @@ -328,7 +328,7 @@ public function voterList() { $result->contact_id ); - $searchRows[$contactID] = array('id' => $contactID); + $searchRows[$contactID] = ['id' => $contactID]; foreach ($selectorCols as $col) { $val = $result->$col; if ($col == 'contact_type') { @@ -357,7 +357,7 @@ public function voterList() { } } - $selectorElements = array_merge($selectorCols, array($extraVoterColName)); + $selectorElements = array_merge($selectorCols, [$extraVoterColName]); $iFilteredTotal = $iTotal; @@ -400,13 +400,13 @@ public function processVoterData() { } } if ($createActivity) { - $ids = array( + $ids = [ 'source_record_id', 'source_contact_id', 'target_contact_id', 'assignee_contact_id', - ); - $activityParams = array(); + ]; + $activityParams = []; foreach ($ids as $id) { $val = CRM_Utils_Array::value($id, $_POST); if (!$val) { @@ -421,12 +421,12 @@ public function processVoterData() { $activityStatus = CRM_Core_PseudoConstant::activityStatus('name'); $scheduledStatusId = array_search('Scheduled', $activityStatus); if ($isReserved) { - $surveyValues = array(); - $surveyParams = array('id' => $activityParams['source_record_id']); + $surveyValues = []; + $surveyParams = ['id' => $activityParams['source_record_id']]; CRM_Core_DAO::commonRetrieve('CRM_Campaign_DAO_Survey', $surveyParams, $surveyValues, - array('title', 'activity_type_id', 'campaign_id') + ['title', 'activity_type_id', 'campaign_id'] ); $activityTypeId = $surveyValues['activity_type_id']; @@ -451,11 +451,11 @@ public function processVoterData() { } else { //delete reserved activity for given voter. - $voterIds = array($activityParams['target_contact_id']); + $voterIds = [$activityParams['target_contact_id']]; $activities = CRM_Campaign_BAO_Survey::voterActivityDetails($activityParams['source_record_id'], $voterIds, $activityParams['source_contact_id'], - array($scheduledStatusId) + [$scheduledStatusId] ); foreach ($activities as $voterId => $values) { $activityId = CRM_Utils_Array::value('activity_id', $values); @@ -491,47 +491,14 @@ public function processVoterData() { } } - CRM_Utils_JSON::output(array('status' => $status)); - } - - public function allActiveCampaigns() { - $currentCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(); - $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, TRUE, FALSE, TRUE); - $options = array( - array( - 'value' => '', - 'title' => ts('- select -'), - ), - ); - foreach ($campaigns as $value => $title) { - $class = NULL; - if (!array_key_exists($value, $currentCampaigns)) { - $class = 'status-past'; - } - $options[] = array( - 'value' => $value, - 'title' => $title, - 'class' => $class, - ); - } - $status = 'fail'; - if (count($options) > 1) { - $status = 'success'; - } - - $results = array( - 'status' => $status, - 'campaigns' => $options, - ); - - CRM_Utils_JSON::output($results); + CRM_Utils_JSON::output(['status' => $status]); } public function campaignGroups() { $surveyId = CRM_Utils_Request::retrieve('survey_id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST' ); - $campGroups = array(); + $campGroups = []; if ($surveyId) { $campaignId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'campaign_id'); if ($campaignId) { @@ -544,22 +511,22 @@ public function campaignGroups() { if (empty($campGroups)) { $campGroups = CRM_Core_PseudoConstant::group(); } - $groups = array( - array( + $groups = [ + [ 'value' => '', 'title' => ts('- select -'), - ), - ); + ], + ]; foreach ($campGroups as $grpId => $title) { - $groups[] = array( + $groups[] = [ 'value' => $grpId, 'title' => $title, - ); + ]; } - $results = array( + $results = [ 'status' => 'success', 'groups' => $groups, - ); + ]; CRM_Utils_JSON::output($results); } @@ -573,7 +540,7 @@ public static function campaignList() { $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $searchParams = explode(',', $searchCriteria); - $params = $searchRows = array(); + $params = $searchRows = []; foreach ($searchParams as $param) { if (isset($_POST[$param])) { $params[$param] = $_POST[$param]; @@ -581,7 +548,7 @@ public static function campaignList() { } //this is sequence columns on datatable. - $selectorCols = array( + $selectorCols = [ 'id', 'name', 'title', @@ -595,36 +562,36 @@ public static function campaignList() { 'is_active', 'isActive', 'action', - ); + ]; // get the data table params. - $dataTableParams = array( - 'sEcho' => array( + $dataTableParams = [ + 'sEcho' => [ 'name' => 'sEcho', 'type' => 'Integer', 'default' => 0, - ), - 'offset' => array( + ], + 'offset' => [ 'name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0, - ), - 'rowCount' => array( + ], + 'rowCount' => [ 'name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25, - ), - 'sort' => array( + ], + 'sort' => [ 'name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'start_date', - ), - 'sortOrder' => array( + ], + 'sortOrder' => [ 'name' => 'sSortDir_0', 'type' => 'String', 'default' => 'desc', - ), - ); + ], + ]; foreach ($dataTableParams as $pName => $pValues) { $$pName = $pValues['default']; if (!empty($_POST[$pValues['name']])) { @@ -634,12 +601,12 @@ public static function campaignList() { } } } - foreach (array( - 'sort', - 'offset', - 'rowCount', - 'sortOrder', - ) as $sortParam) { + foreach ([ + 'sort', + 'offset', + 'rowCount', + 'sortOrder', + ] as $sortParam) { $params[$sortParam] = $$sortParam; } @@ -676,7 +643,7 @@ public function surveyList() { $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $searchParams = explode(',', $searchCriteria); - $params = $searchRows = array(); + $params = $searchRows = []; foreach ($searchParams as $param) { if (!empty($_POST[$param])) { $params[$param] = $_POST[$param]; @@ -684,7 +651,7 @@ public function surveyList() { } //this is sequence columns on datatable. - $selectorCols = array( + $selectorCols = [ 'id', 'title', 'campaign_id', @@ -700,36 +667,36 @@ public function surveyList() { 'result_id', 'action', 'voterLinks', - ); + ]; // get the data table params. - $dataTableParams = array( - 'sEcho' => array( + $dataTableParams = [ + 'sEcho' => [ 'name' => 'sEcho', 'type' => 'Integer', 'default' => 0, - ), - 'offset' => array( + ], + 'offset' => [ 'name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0, - ), - 'rowCount' => array( + ], + 'rowCount' => [ 'name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25, - ), - 'sort' => array( + ], + 'sort' => [ 'name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'created_date', - ), - 'sortOrder' => array( + ], + 'sortOrder' => [ 'name' => 'sSortDir_0', 'type' => 'String', 'default' => 'desc', - ), - ); + ], + ]; foreach ($dataTableParams as $pName => $pValues) { $$pName = $pValues['default']; if (!empty($_POST[$pValues['name']])) { @@ -739,12 +706,12 @@ public function surveyList() { } } } - foreach (array( - 'sort', - 'offset', - 'rowCount', - 'sortOrder', - ) as $sortParam) { + foreach ([ + 'sort', + 'offset', + 'rowCount', + 'sortOrder', + ] as $sortParam) { $params[$sortParam] = $$sortParam; } @@ -781,7 +748,7 @@ public function petitionList() { $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST'); $searchParams = explode(',', $searchCriteria); - $params = $searchRows = array(); + $params = $searchRows = []; foreach ($searchParams as $param) { if (!empty($_POST[$param])) { $params[$param] = $_POST[$param]; @@ -789,7 +756,7 @@ public function petitionList() { } //this is sequence columns on datatable. - $selectorCols = array( + $selectorCols = [ 'id', 'title', 'campaign_id', @@ -800,36 +767,36 @@ public function petitionList() { 'is_active', 'isActive', 'action', - ); + ]; // get the data table params. - $dataTableParams = array( - 'sEcho' => array( + $dataTableParams = [ + 'sEcho' => [ 'name' => 'sEcho', 'type' => 'Integer', 'default' => 0, - ), - 'offset' => array( + ], + 'offset' => [ 'name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0, - ), - 'rowCount' => array( + ], + 'rowCount' => [ 'name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25, - ), - 'sort' => array( + ], + 'sort' => [ 'name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'created_date', - ), - 'sortOrder' => array( + ], + 'sortOrder' => [ 'name' => 'sSortDir_0', 'type' => 'String', 'default' => 'desc', - ), - ); + ], + ]; foreach ($dataTableParams as $pName => $pValues) { $$pName = $pValues['default']; if (!empty($_POST[$pValues['name']])) { @@ -839,12 +806,12 @@ public function petitionList() { } } } - foreach (array( - 'sort', - 'offset', - 'rowCount', - 'sortOrder', - ) as $sortParam) { + foreach ([ + 'sort', + 'offset', + 'rowCount', + 'sortOrder', + ] as $sortParam) { $params[$sortParam] = $$sortParam; } diff --git a/CRM/Campaign/Page/DashBoard.php b/CRM/Campaign/Page/DashBoard.php index 0ba913f40835..08ac5a08e228 100644 --- a/CRM/Campaign/Page/DashBoard.php +++ b/CRM/Campaign/Page/DashBoard.php @@ -1,9 +1,9 @@ array( + self::$_campaignActionLinks = [ + CRM_Core_Action::UPDATE => [ 'name' => ts('Edit'), 'url' => 'civicrm/campaign/add', 'qs' => 'reset=1&action=update&id=%%id%%', 'title' => ts('Update Campaign'), - ), - CRM_Core_Action::DISABLE => array( + ], + CRM_Core_Action::DISABLE => [ 'name' => ts('Disable'), 'title' => ts('Disable Campaign'), 'ref' => 'crm-enable-disable', - ), - CRM_Core_Action::ENABLE => array( + ], + CRM_Core_Action::ENABLE => [ 'name' => ts('Enable'), 'title' => ts('Enable Campaign'), 'ref' => 'crm-enable-disable', - ), - CRM_Core_Action::DELETE => array( + ], + CRM_Core_Action::DELETE => [ 'name' => ts('Delete'), 'url' => 'civicrm/campaign/add', 'qs' => 'action=delete&reset=1&id=%%id%%', 'title' => ts('Delete Campaign'), - ), - ); + ], + ]; } return self::$_campaignActionLinks; @@ -88,30 +88,30 @@ public static function campaignActionLinks() { public static function surveyActionLinks() { // check if variable _actionsLinks is populated if (!isset(self::$_surveyActionLinks)) { - self::$_surveyActionLinks = array( - CRM_Core_Action::UPDATE => array( + self::$_surveyActionLinks = [ + CRM_Core_Action::UPDATE => [ 'name' => ts('Edit'), 'url' => 'civicrm/survey/configure/main', 'qs' => 'action=update&id=%%id%%&reset=1', 'title' => ts('Update Survey'), - ), - CRM_Core_Action::DISABLE => array( + ], + CRM_Core_Action::DISABLE => [ 'name' => ts('Disable'), 'ref' => 'crm-enable-disable', 'title' => ts('Disable Survey'), - ), - CRM_Core_Action::ENABLE => array( + ], + CRM_Core_Action::ENABLE => [ 'name' => ts('Enable'), 'ref' => 'crm-enable-disable', 'title' => ts('Enable Survey'), - ), - CRM_Core_Action::DELETE => array( + ], + CRM_Core_Action::DELETE => [ 'name' => ts('Delete'), 'url' => 'civicrm/survey/delete', 'qs' => 'id=%%id%%&reset=1', 'title' => ts('Delete Survey'), - ), - ); + ], + ]; } return self::$_surveyActionLinks; @@ -123,43 +123,43 @@ public static function surveyActionLinks() { public static function petitionActionLinks() { if (!isset(self::$_petitionActionLinks)) { self::$_petitionActionLinks = self::surveyActionLinks(); - self::$_petitionActionLinks[CRM_Core_Action::UPDATE] = array( + self::$_petitionActionLinks[CRM_Core_Action::UPDATE] = [ 'name' => ts('Edit'), 'url' => 'civicrm/petition/add', 'qs' => 'action=update&id=%%id%%&reset=1', 'title' => ts('Update Petition'), - ); - self::$_petitionActionLinks[CRM_Core_Action::DISABLE] = array( + ]; + self::$_petitionActionLinks[CRM_Core_Action::DISABLE] = [ 'name' => ts('Disable'), 'ref' => 'crm-enable-disable', 'title' => ts('Disable Petition'), - ); - self::$_petitionActionLinks[CRM_Core_Action::ENABLE] = array( + ]; + self::$_petitionActionLinks[CRM_Core_Action::ENABLE] = [ 'name' => ts('Enable'), 'ref' => 'crm-enable-disable', 'title' => ts('Enable Petition'), - ); - self::$_petitionActionLinks[CRM_Core_Action::DELETE] = array( + ]; + self::$_petitionActionLinks[CRM_Core_Action::DELETE] = [ 'name' => ts('Delete'), 'url' => 'civicrm/petition/add', 'qs' => 'action=delete&id=%%id%%&reset=1', 'title' => ts('Delete Petition'), - ); - self::$_petitionActionLinks[CRM_Core_Action::PROFILE] = array( + ]; + self::$_petitionActionLinks[CRM_Core_Action::PROFILE] = [ 'name' => ts('Sign'), 'url' => 'civicrm/petition/sign', 'qs' => 'sid=%%id%%&reset=1', 'title' => ts('Sign Petition'), 'fe' => TRUE, //CRM_Core_Action::PROFILE is used because there isn't a specific action for sign - ); - self::$_petitionActionLinks[CRM_Core_Action::BROWSE] = array( + ]; + self::$_petitionActionLinks[CRM_Core_Action::BROWSE] = [ 'name' => ts('Signatures'), 'url' => 'civicrm/activity/search', 'qs' => 'survey=%%id%%&force=1', 'title' => ts('List the signatures'), //CRM_Core_Action::PROFILE is used because there isn't a specific action for sign - ); + ]; } return self::$_petitionActionLinks; @@ -196,8 +196,8 @@ public function browseCampaign() { * * @return array */ - public static function getCampaignSummary($params = array()) { - $campaignsData = array(); + public static function getCampaignSummary($params = []) { + $campaignsData = []; //get the campaigns. $campaigns = CRM_Campaign_BAO_Campaign::getCampaignSummary($params); @@ -205,7 +205,7 @@ public static function getCampaignSummary($params = array()) { $config = CRM_Core_Config::singleton(); $campaignType = CRM_Campaign_PseudoConstant::campaignType(); $campaignStatus = CRM_Campaign_PseudoConstant::campaignStatus(); - $properties = array( + $properties = [ 'id', 'name', 'title', @@ -215,7 +215,7 @@ public static function getCampaignSummary($params = array()) { 'is_active', 'start_date', 'end_date', - ); + ]; foreach ($campaigns as $cmpid => $campaign) { foreach ($properties as $prop) { $campaignsData[$cmpid][$prop] = CRM_Utils_Array::value($prop, $campaign); @@ -251,7 +251,7 @@ public static function getCampaignSummary($params = array()) { } $campaignsData[$cmpid]['action'] = CRM_Core_Action::formLink(self::campaignActionLinks(), $action, - array('id' => $campaign['id']), + ['id' => $campaign['id']], ts('more'), FALSE, 'campaign.dashboard.row', @@ -296,8 +296,8 @@ public function browseSurvey() { * * @return array */ - public static function getSurveySummary($params = array()) { - $surveysData = array(); + public static function getSurveySummary($params = []) { + $surveysData = []; //get the survey. $config = CRM_Core_Config::singleton(); @@ -311,7 +311,7 @@ public static function getSurveySummary($params = array()) { $surveysData[$sid]['campaign'] = CRM_Utils_Array::value($campaignId, $campaigns); $surveysData[$sid]['activity_type'] = $surveyType[$survey['activity_type_id']]; if (!empty($survey['release_frequency'])) { - $surveysData[$sid]['release_frequency'] = ts('1 Day', array('plural' => '%count Days', 'count' => $survey['release_frequency'])); + $surveysData[$sid]['release_frequency'] = ts('1 Day', ['plural' => '%count Days', 'count' => $survey['release_frequency']]); } $action = array_sum(array_keys(self::surveyActionLinks($surveysData[$sid]['activity_type']))); @@ -344,7 +344,7 @@ public static function getSurveySummary($params = array()) { } $surveysData[$sid]['action'] = CRM_Core_Action::formLink(self::surveyActionLinks($surveysData[$sid]['activity_type']), $action, - array('id' => $sid), + ['id' => $sid], ts('more'), FALSE, 'survey.dashboard.row', @@ -402,9 +402,9 @@ public function browsePetition() { * * @return array */ - public static function getPetitionSummary($params = array()) { + public static function getPetitionSummary($params = []) { $config = CRM_Core_Config::singleton(); - $petitionsData = array(); + $petitionsData = []; //get the petitions. $petitions = CRM_Campaign_BAO_Petition::getPetitionSummary($params); @@ -439,7 +439,7 @@ public static function getPetitionSummary($params = array()) { $petitionsData[$pid]['action'] = CRM_Core_Action::formLink(self::petitionActionLinks(), $action, - array('id' => $pid), + ['id' => $pid], ts('more'), FALSE, 'petition.dashboard.row', @@ -453,11 +453,11 @@ public static function getPetitionSummary($params = array()) { } public function browse() { - $this->_tabs = array( + $this->_tabs = [ 'campaign' => ts('Campaigns'), 'survey' => ts('Surveys'), 'petition' => ts('Petitions'), - ); + ]; $subPageType = CRM_Utils_Request::retrieve('type', 'String', $this); if ($subPageType) { @@ -474,11 +474,11 @@ public function browse() { } CRM_Core_Resources::singleton() ->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header') - ->addSetting(array( - 'tabSettings' => array( + ->addSetting([ + 'tabSettings' => [ 'active' => strtolower(CRM_Utils_Array::value('subPage', $_GET, 'campaign')), - ), - )); + ], + ]); } /** @@ -495,14 +495,14 @@ public function run() { } public function buildTabs() { - $allTabs = array(); + $allTabs = []; foreach ($this->_tabs as $name => $title) { - $allTabs[$name] = array( + $allTabs[$name] = [ 'title' => $title, 'valid' => TRUE, 'active' => TRUE, 'link' => CRM_Utils_System::url('civicrm/campaign', "reset=1&type=$name"), - ); + ]; } $allTabs['campaign']['class'] = 'livePage'; $this->assign('tabHeader', $allTabs); diff --git a/CRM/Campaign/Page/Petition.php b/CRM/Campaign/Page/Petition.php index 9a10f16752e9..c526df7f0eee 100644 --- a/CRM/Campaign/Page/Petition.php +++ b/CRM/Campaign/Page/Petition.php @@ -1,9 +1,9 @@ assign('survey_id', $petition_id); $pparams['id'] = $petition_id; - $this->petition = array(); + $this->petition = []; CRM_Campaign_BAO_Survey::retrieve($pparams, $this->petition); $this->assign('is_share', CRM_Utils_Array::value('is_share', $this->petition)); $this->assign('thankyou_title', CRM_Utils_Array::value('thankyou_title', $this->petition)); @@ -119,7 +120,7 @@ public static function confirm($contact_id, $subscribe_id, $hash, $activity_id, $ce->save(); CRM_Contact_BAO_GroupContact::addContactsToGroup( - array($contact_id), + [$contact_id], $se->group_id, 'Email', 'Added', diff --git a/CRM/Campaign/Page/Petition/ThankYou.php b/CRM/Campaign/Page/Petition/ThankYou.php index f0fc9fffb21e..ac4d8d4b8342 100644 --- a/CRM/Campaign/Page/Petition/ThankYou.php +++ b/CRM/Campaign/Page/Petition/ThankYou.php @@ -1,9 +1,9 @@ petition = array(); + $this->petition = []; CRM_Campaign_BAO_Survey::retrieve($params, $this->petition); $this->assign('petitionTitle', $this->petition['title']); $this->assign('thankyou_title', CRM_Utils_Array::value('thankyou_title', $this->petition)); diff --git a/CRM/Campaign/Page/SurveyType.php b/CRM/Campaign/Page/SurveyType.php index 74da1d9f3186..bfe7e4cd906c 100644 --- a/CRM/Campaign/Page/SurveyType.php +++ b/CRM/Campaign/Page/SurveyType.php @@ -1,9 +1,9 @@ assign('gName', $this->_gName); $this->assign('GName', $this->_GName); - CRM_Utils_System::setTitle(ts('%1 Options', array(1 => $this->_GName))); + CRM_Utils_System::setTitle(ts('%1 Options', [1 => $this->_GName])); - $this->assign('addSurveyType', array("civicrm/admin/campaign/surveyType", "reset=1&action=add")); + $this->assign('addSurveyType', ["civicrm/admin/campaign/surveyType", "reset=1&action=add"]); } /** @@ -102,30 +102,30 @@ public function getBAOName() { */ public function &links() { if (!(self::$_links)) { - self::$_links = array( - CRM_Core_Action::UPDATE => array( + self::$_links = [ + CRM_Core_Action::UPDATE => [ 'name' => ts('Edit'), 'url' => 'civicrm/admin/campaign/surveyType', 'qs' => 'action=update&id=%%id%%&reset=1', - 'title' => ts('Edit %1', array(1 => $this->_gName)), - ), - CRM_Core_Action::DISABLE => array( + 'title' => ts('Edit %1', [1 => $this->_gName]), + ], + CRM_Core_Action::DISABLE => [ 'name' => ts('Disable'), 'ref' => 'crm-enable-disable', - 'title' => ts('Disable %1', array(1 => $this->_gName)), - ), - CRM_Core_Action::ENABLE => array( + 'title' => ts('Disable %1', [1 => $this->_gName]), + ], + CRM_Core_Action::ENABLE => [ 'name' => ts('Enable'), 'ref' => 'crm-enable-disable', - 'title' => ts('Enable %1', array(1 => $this->_gName)), - ), - CRM_Core_Action::DELETE => array( + 'title' => ts('Enable %1', [1 => $this->_gName]), + ], + CRM_Core_Action::DELETE => [ 'name' => ts('Delete'), 'url' => 'civicrm/admin/campaign/surveyType', 'qs' => 'action=delete&id=%%id%%', - 'title' => ts('Delete %1 Type', array(1 => $this->_gName)), - ), - ); + 'title' => ts('Delete %1 Type', [1 => $this->_gName]), + ], + ]; } return self::$_links; } @@ -143,7 +143,7 @@ public function run() { */ public function browse() { $campaingCompId = CRM_Core_Component::getComponentID('CiviCampaign'); - $groupParams = array('name' => $this->_gName); + $groupParams = ['name' => $this->_gName]; $optionValues = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'component_id,weight'); foreach ($optionValues as $key => $optionValue) { diff --git a/CRM/Campaign/Page/Vote.php b/CRM/Campaign/Page/Vote.php index 76586b3699ad..ad131746ff45 100644 --- a/CRM/Campaign/Page/Vote.php +++ b/CRM/Campaign/Page/Vote.php @@ -1,9 +1,9 @@ _tabs = array( + $this->_tabs = [ 'reserve' => ts('Reserve Respondents'), 'interview' => ts('Interview Respondents'), - ); + ]; $this->_surveyId = CRM_Utils_Request::retrieve('sid', 'Positive', $this); $this->_interviewerId = CRM_Utils_Request::retrieve('cid', 'Positive', $this); @@ -93,11 +93,11 @@ public function browse() { CRM_Core_Resources::singleton() ->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header') - ->addSetting(array( - 'tabSettings' => array( + ->addSetting([ + 'tabSettings' => [ 'active' => strtolower(CRM_Utils_Array::value('subPage', $_GET, 'reserve')), - ), - )); + ], + ]); } /** @@ -110,17 +110,16 @@ public function run() { } public function buildTabs() { - $allTabs = array(); + $allTabs = []; foreach ($this->_tabs as $name => $title) { // check for required permissions. - if (!CRM_Core_Permission::check(array( - array( + if (!CRM_Core_Permission::check([ + [ 'manage campaign', 'administer CiviCampaign', "{$name} campaign contacts", - ), - )) - ) { + ], + ])) { continue; } @@ -131,12 +130,12 @@ public function buildTabs() { if ($this->_interviewerId) { $urlParams .= "&cid={$this->_interviewerId}"; } - $allTabs[$name] = array( + $allTabs[$name] = [ 'title' => $title, 'valid' => TRUE, 'active' => TRUE, 'link' => CRM_Utils_System::url('civicrm/campaign/vote', $urlParams), - ); + ]; } $this->assign('tabHeader', empty($allTabs) ? FALSE : $allTabs); diff --git a/CRM/Campaign/PseudoConstant.php b/CRM/Campaign/PseudoConstant.php index 15030a7a283c..e121a86d5b6f 100644 --- a/CRM/Campaign/PseudoConstant.php +++ b/CRM/Campaign/PseudoConstant.php @@ -1,9 +1,9 @@ fetch()) { $this->_query->convertToPseudoNames($result); - $row = array(); + $row = []; // the columns we are interested in foreach (self::$_properties as $property) { if (property_exists($result, $property)) { @@ -271,30 +271,34 @@ public function buildPrevNextCache($sort) { if (!$crmPID) { $cacheKey = "civicrm search {$this->_key}"; - CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact'); + Civi::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact'); - $sql = $this->_query->searchQuery(0, 0, $sort, + $sql = $this->_query->getSearchSQLParts(0, 0, $sort, FALSE, FALSE, FALSE, FALSE, - TRUE, $this->_campaignWhereClause, + $this->_campaignWhereClause, NULL, $this->_campaignFromClause ); - list($select, $from) = explode(' FROM ', $sql); - $insertSQL = " -INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) -SELECT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name -FROM {$from} + + $selectSQL = " + SELECT %1, contact_a.id, contact_a.display_name +FROM {$sql['from']} "; - $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); - $result = CRM_Core_DAO::executeQuery($insertSQL); - unset($errorScope); - if (is_a($result, 'DB_Error')) { + try { + Civi::service('prevnext')->fillWithSql($cacheKey, $selectSQL, [1 => [$cacheKey, 'String']]); + } + catch (CRM_Core_Exception $e) { + // Heavy handed, no? Seems like this merits an explanation. return; } - // also record an entry in the cache key table, so we can delete it periodically - CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey); + + if (Civi::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql) { + // SQL-backed prevnext cache uses an extra record for pruning the cache. + // Also ensure that caches stay alive for 2 days a per previous code. + Civi::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql::cacheDays); + } } } @@ -319,40 +323,40 @@ public function getQILL() { * the column headers that need to be displayed */ public function &getColumnHeaders($action = NULL, $output = NULL) { - self::$_columnHeaders = array(); + self::$_columnHeaders = []; if (!$this->_single) { - $contactDetails = array( - array( + $contactDetails = [ + [ 'name' => ts('Contact Name'), 'sort' => 'sort_name', 'direction' => CRM_Utils_Sort::ASCENDING, - ), - array( + ], + [ 'name' => ts('Street Number'), 'sort' => 'street_number', - ), - array( + ], + [ 'name' => ts('Street Name'), 'sort' => 'street_name', - ), - array('name' => ts('Street Address')), - array( + ], + ['name' => ts('Street Address')], + [ 'name' => ts('City'), 'sort' => 'city', - ), - array( + ], + [ 'name' => ts('Postal Code'), 'sort' => 'postal_code', - ), - array( + ], + [ 'name' => ts('State'), 'sort' => 'state_province_name', - ), - array('name' => ts('Country')), - array('name' => ts('Email')), - array('name' => ts('Phone')), - ); + ], + ['name' => ts('Country')], + ['name' => ts('Email')], + ['name' => ts('Phone')], + ]; self::$_columnHeaders = array_merge($contactDetails, self::$_columnHeaders); } diff --git a/CRM/Campaign/StateMachine/Search.php b/CRM/Campaign/StateMachine/Search.php index 4c04c01a7f65..6d38b3aa5f61 100644 --- a/CRM/Campaign/StateMachine/Search.php +++ b/CRM/Campaign/StateMachine/Search.php @@ -1,9 +1,9 @@ _pages = array(); + $this->_pages = []; $this->_pages['CRM_Campaign_Form_Search'] = NULL; list($task, $result) = $this->taskName($controller, 'Search'); @@ -78,7 +78,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) { * * @param string $formName * - * @return string + * @return array * the name of the form that will handle the task */ public function taskName($controller, $formName = 'Search') { diff --git a/CRM/Campaign/Task.php b/CRM/Campaign/Task.php index 2b12d19e0047..6e4367b0a6f8 100644 --- a/CRM/Campaign/Task.php +++ b/CRM/Campaign/Task.php @@ -1,9 +1,9 @@ array( + self::$_tasks = [ + self::INTERVIEW => [ 'title' => ts('Record Respondents Interview'), - 'class' => array( + 'class' => [ 'CRM_Campaign_Form_Task_Interview', 'CRM_Campaign_Form_Task_Release', - ), + ], 'result' => FALSE, - ), - 2 => array( + ], + self::RESERVE => [ 'title' => ts('Reserve Respondents'), - 'class' => array( + 'class' => [ 'CRM_Campaign_Form_Task_Reserve', 'CRM_Campaign_Form_Task_Interview', 'CRM_Campaign_Form_Task_Release', - ), + ], 'result' => FALSE, - ), - 3 => array( + ], + self::RELEASE => [ 'title' => ts('Release Respondents'), 'class' => 'CRM_Campaign_Form_Task_Release', 'result' => FALSE, - ), - 4 => array( + ], + self::TASK_PRINT => [ 'title' => ts('Print Respondents'), 'class' => 'CRM_Campaign_Form_Task_Print', 'result' => FALSE, - ), - ); + ], + ]; - CRM_Utils_Hook::searchTasks('campaign', self::$_tasks); - asort(self::$_tasks); + parent::tasks(); } return self::$_tasks; } - /** - * These tasks are the core set of task titles - * on voters. - * - * @return array - * the set of task titles - */ - public static function &taskTitles() { - self::tasks(); - $titles = array(); - foreach (self::$_tasks as $id => $value) { - $titles[$id] = $value['title']; - } - - return $titles; - } - /** * Show tasks selectively based on the permission level * of the user * * @param int $permission + * @param array $params * * @return array * set of tasks that are valid for the user */ - public static function &permissionedTaskTitles($permission) { + public static function permissionedTaskTitles($permission, $params = []) { $tasks = self::taskTitles(); + $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params); return $tasks; } @@ -143,14 +125,14 @@ public static function &permissionedTaskTitles($permission) { public static function getTask($value) { self::tasks(); if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) { - // make the interview task by default - $value = 1; + // Set the interview task as default + $value = self::INTERVIEW; } - return array( + return [ self::$_tasks[$value]['class'], self::$_tasks[$value]['result'], - ); + ]; } } diff --git a/CRM/Campaign/xml/Menu/Campaign.xml b/CRM/Campaign/xml/Menu/Campaign.xml index a5c673f24eb8..555eb1f2843b 100644 --- a/CRM/Campaign/xml/Menu/Campaign.xml +++ b/CRM/Campaign/xml/Menu/Campaign.xml @@ -72,7 +72,7 @@{$values['description']}
"; } + if ($params['context'] == 'current') { + $smarty = CRM_Core_Smarty::singleton(); + + $contactCombos = [ + [ + 'permContact' => $params['contact_id'], + 'permDisplayName' => $displayName, + 'otherContact' => $values['cid'], + 'otherDisplayName' => $values['display_name'], + 'columnKey' => 'sort_name', + ], + [ + 'permContact' => $values['cid'], + 'permDisplayName' => $values['display_name'], + 'otherContact' => $params['contact_id'], + 'otherDisplayName' => $displayName, + 'columnKey' => 'relation', + ], + ]; + + foreach ($contactCombos as $combo) { + foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) { + $smarty->assign('permType', $permType); + if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType) + || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType) + ) { + $smarty->assign('permDisplayName', $combo['permDisplayName']); + $smarty->assign('otherDisplayName', $combo['otherDisplayName']); + $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl'); + } + } + } + } + $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']); $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']); $relationship['city'] = $values['city']; @@ -2138,7 +2206,11 @@ public static function getContactRelationshipSelector(&$params) { } } - $relationshipsDT = array(); + $columnHeaders = self::getColumnHeaders(); + $selector = NULL; + CRM_Utils_Hook::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector); + + $relationshipsDT = []; $relationshipsDT['data'] = $contactRelationships; $relationshipsDT['recordsTotal'] = $params['total']; $relationshipsDT['recordsFiltered'] = $params['total']; @@ -2146,4 +2218,230 @@ public static function getContactRelationshipSelector(&$params) { return $relationshipsDT; } + /** + * @return array + */ + public static function getColumnHeaders() { + return [ + 'relation' => [ + 'name' => ts('Relationship'), + 'sort' => 'relation', + 'direction' => CRM_Utils_Sort::ASCENDING, + ], + 'sort_name' => [ + 'name' => '', + 'sort' => 'sort_name', + 'direction' => CRM_Utils_Sort::ASCENDING, + ], + 'start_date' => [ + 'name' => ts('Start'), + 'sort' => 'start_date', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'end_date' => [ + 'name' => ts('End'), + 'sort' => 'end_date', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'city' => [ + 'name' => ts('City'), + 'sort' => 'city', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'state' => [ + 'name' => ts('State/Prov'), + 'sort' => 'state', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'email' => [ + 'name' => ts('Email'), + 'sort' => 'email', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'phone' => [ + 'name' => ts('Phone'), + 'sort' => 'phone', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + 'links' => [ + 'name' => '', + 'sort' => 'links', + 'direction' => CRM_Utils_Sort::DONTCARE, + ], + ]; + } + + /** + * @inheritdoc + */ + public static function buildOptions($fieldName, $context = NULL, $props = []) { + if ($fieldName === 'relationship_type_id') { + return self::buildRelationshipTypeOptions($props); + } + + return parent::buildOptions($fieldName, $context, $props); + } + + /** + * Builds a list of options available for relationship types + * + * @param array $params + * - contact_type: Limits by contact type on the "A" side + * - relationship_id: Used to find the value for contact type for "B" side. + * If contact_a matches provided contact_id then type of contact_b will + * be used. Otherwise uses type of contact_a. Must be used with contact_id + * - contact_id: Limits by contact types of this contact on the "A" side + * - is_form: Returns array with keys indexed for use in a quickform + * - relationship_direction: For relationship types with duplicate names + * on both sides, defines which option should be returned, a_b or b_a + * + * @return array + */ + public static function buildRelationshipTypeOptions($params = []) { + $contactId = CRM_Utils_Array::value('contact_id', $params); + $direction = CRM_Utils_Array::value('relationship_direction', $params, 'a_b'); + $relationshipId = CRM_Utils_Array::value('relationship_id', $params); + $contactType = CRM_Utils_Array::value('contact_type', $params); + $isForm = CRM_Utils_Array::value('is_form', $params); + $showAll = FALSE; + + // getContactRelationshipType will return an empty set if these are not set + if (!$contactId && !$relationshipId && !$contactType) { + $showAll = TRUE; + } + + $labels = self::getContactRelationshipType( + $contactId, + $direction, + $relationshipId, + $contactType, + $showAll, + 'label' + ); + + if ($isForm) { + return $labels; + } + + $names = self::getContactRelationshipType( + $contactId, + $direction, + $relationshipId, + $contactType, + $showAll, + 'name' + ); + + // ensure $names contains only entries in $labels + $names = array_intersect_key($names, $labels); + + $nameToLabels = array_combine($names, $labels); + + return $nameToLabels; + } + + /** + * Process the params from api, form and check if current + * employer should be set or unset. + * + * @param array $params + * @param int $relationshipId + * @param int|null $updatedRelTypeID + * + * @return bool + * TRUE if current employer needs to be cleared. + * @throws \CiviCRM_API3_Exception + */ + public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) { + $existingTypeID = (int) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id'); + $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID; + $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]); + + if ($currentEmployerID !== (int) $params['contact_id_b'] || !self::isRelationshipTypeCurrentEmployer($existingTypeID)) { + return FALSE; + } + //Clear employer if relationship is expired. + if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) { + return TRUE; + } + //current employer checkbox is disabled on the form. + //inactive or relationship type(employer of) is updated. + if ((isset($params['is_current_employer']) && empty($params['is_current_employer'])) + || ((isset($params['is_active']) && empty($params['is_active']))) + || $existingTypeID != $updatedRelTypeID) { + // If there are no other active employer relationships between the same 2 contacts... + if (!civicrm_api3('Relationship', 'getcount', [ + 'is_active' => 1, + 'relationship_type_id' => $existingTypeID, + 'id' => ['<>' => $params['id']], + 'contact_id_a' => $params['contact_id_a'], + 'contact_id_b' => $params['contact_id_b'], + ])) { + return TRUE; + } + } + + return FALSE; + } + + /** + * Is this a current employer relationship type. + * + * @todo - this could use cached pseudoconstant lookups. + * + * @param int $existingTypeID + * + * @return bool + */ + private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool { + $isCurrentEmployerRelationshipType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of'; + return $isCurrentEmployerRelationshipType; + } + + /** + * Is the inherited relationship invalidated by this relationship change. + * + * @param $membershipValues + * @param array $values + * @param int $cid + * @param int $mainRelatedContactId + * + * @return array + * @throws \CiviCRM_API3_Exception + */ + private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid, $mainRelatedContactId): array { + $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']); + $relTypeIds = $membershipType['relationship_type_id']; + $membshipInheritedFrom = $membershipValues['owner_membership_id'] ?? NULL; + if (!$membshipInheritedFrom || !in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) { + return [implode(',', $relTypeIds), FALSE]; + } + //CRM-16300 check if owner membership exist for related membership + $isDeletable = !empty($values[$mainRelatedContactId]['memberships'][$membshipInheritedFrom]); + return [implode(',', $relTypeIds), $isDeletable]; + } + + /** + * Add an inherited membership, provided max related not exceeded. + * + * @param array $membershipValues + * + * @return array + * @throws \CRM_Core_Exception + */ + protected static function addInheritedMembership($membershipValues) { + $query = " +SELECT count(*) + FROM civicrm_membership + LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id) + WHERE membership_type_id = {$membershipValues['membership_type_id']} + AND owner_membership_id = {$membershipValues['owner_membership_id']} + AND is_current_member = 1"; + $result = CRM_Core_DAO::singleValueQuery($query); + if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) { + CRM_Member_BAO_Membership::create($membershipValues); + } + return $membershipValues; + } + } diff --git a/CRM/Contact/BAO/RelationshipType.php b/CRM/Contact/BAO/RelationshipType.php index 656f7bae6ef5..bc11bf2f0248 100644 --- a/CRM/Contact/BAO/RelationshipType.php +++ b/CRM/Contact/BAO/RelationshipType.php @@ -1,9 +1,9 @@ copyValues($params); if ($relationshipType->find(TRUE)) { CRM_Core_DAO::storeValues($relationshipType, $defaults); - $relationshipType->free(); return $relationshipType; } return NULL; @@ -68,8 +67,8 @@ public static function retrieve(&$params, &$defaults) { * @param bool $is_active * Value we want to set the is_active field. * - * @return Object - * DAO object on success, null otherwise + * @return bool + * true if we found and updated the object, else false */ public static function setIsActive($id, $is_active) { return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_RelationshipType', $id, 'is_active', $is_active); @@ -79,25 +78,20 @@ public static function setIsActive($id, $is_active) { * Add the relationship type in the db. * * @param array $params - * (reference ) an assoc array of name/value pairs. - * @param array $ids - * The array that holds all the db ids. * * @return CRM_Contact_DAO_RelationshipType */ - public static function add(&$params, &$ids) { - //to change name, CRM-3336 - if (empty($params['label_a_b']) && !empty($params['name_a_b'])) { - $params['label_a_b'] = $params['name_a_b']; - } - - if (empty($params['label_b_a']) && !empty($params['name_b_a'])) { - $params['label_b_a'] = $params['name_b_a']; - } + public static function add($params) { + if (empty($params['id'])) { + // Set name to label if not set + if (empty($params['label_a_b']) && !empty($params['name_a_b'])) { + $params['label_a_b'] = $params['name_a_b']; + } + if (empty($params['label_b_a']) && !empty($params['name_b_a'])) { + $params['label_b_a'] = $params['name_b_a']; + } - // set label to name if it's not set - but *only* for - // ADD action. CRM-3336 as part from (CRM-3522) - if (empty($ids['relationshipType'])) { + // set label to name if it's not set if (empty($params['name_a_b']) && !empty($params['label_a_b'])) { $params['name_a_b'] = $params['label_a_b']; } @@ -109,24 +103,18 @@ public static function add(&$params, &$ids) { // action is taken depending upon the mode $relationshipType = new CRM_Contact_DAO_RelationshipType(); - $relationshipType->copyValues($params); + $hook = empty($params['id']) ? 'create' : 'edit'; + CRM_Utils_Hook::pre($hook, 'RelationshipType', CRM_Utils_Array::value('id', $params), $params); - // if label B to A is blank, insert the value label A to B for it - if (!strlen(trim($strName = CRM_Utils_Array::value('name_b_a', $params)))) { - $relationshipType->name_b_a = CRM_Utils_Array::value('name_a_b', $params); - } - if (!strlen(trim($strName = CRM_Utils_Array::value('label_b_a', $params)))) { - $relationshipType->label_b_a = CRM_Utils_Array::value('label_a_b', $params); - } - - $relationshipType->id = CRM_Utils_Array::value('relationshipType', $ids); + $relationshipType->copyValues($params); + $relationshipType->save(); - $result = $relationshipType->save(); + CRM_Utils_Hook::post($hook, 'RelationshipType', $relationshipType->id, $relationshipType); CRM_Core_PseudoConstant::relationshipType('label', TRUE); CRM_Core_PseudoConstant::relationshipType('name', TRUE); CRM_Case_XMLProcessor::flushStaticCaches(); - return $result; + return $relationshipType; } /** @@ -153,10 +141,10 @@ public static function del($relationshipTypeId) { $relationship->delete(); // remove this relationship type from membership types - $mems = civicrm_api3('MembershipType', 'get', array( - 'relationship_type_id' => array('LIKE' => "%{$relationshipTypeId}%"), - 'return' => array('id', 'relationship_type_id', 'relationship_direction'), - )); + $mems = civicrm_api3('MembershipType', 'get', [ + 'relationship_type_id' => ['LIKE' => "%{$relationshipTypeId}%"], + 'return' => ['id', 'relationship_type_id', 'relationship_direction'], + ]); foreach ($mems['values'] as $membershipTypeId => $membershipType) { $pos = array_search($relationshipTypeId, $membershipType['relationship_type_id']); // Api call may have returned false positives but currently the relationship_type_id uses diff --git a/CRM/Contact/BAO/SavedSearch.php b/CRM/Contact/BAO/SavedSearch.php index 694f849847db..396cb3826ae5 100644 --- a/CRM/Contact/BAO/SavedSearch.php +++ b/CRM/Contact/BAO/SavedSearch.php @@ -1,9 +1,9 @@ 'event_date_low', + 'event_end_date_high' => 'event_date_high', + 'case_from_start_date_low' => 'case_from_date_low', + 'case_from_start_date_high' => 'case_from_date_high', + 'case_to_end_date_low' => 'case_to_date_low', + 'case_to_end_date_high' => 'case_to_date_high', + ]; + $fv = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values'); $result = NULL; if ($fv) { @@ -99,7 +108,7 @@ public static function getFormValues($id) { $result = unserialize($fv); } - $specialFields = array('contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'); + $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id']; foreach ($result as $element => $value) { if (CRM_Contact_BAO_Query::isAlreadyProcessedForQueryFormat($value)) { $id = CRM_Utils_Array::value(0, $value); @@ -107,21 +116,36 @@ public static function getFormValues($id) { if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { $op = key($value); $value = CRM_Utils_Array::value($op, $value); - if (in_array($op, array('BETWEEN', '>=', '<='))) { + if (in_array($op, ['BETWEEN', '>=', '<='])) { self::decodeRelativeFields($result, $id, $op, $value); unset($result[$element]); continue; } } + // Check for a date range field, which might be a standard date + // range or a relative date. if (strpos($id, '_date_low') !== FALSE || strpos($id, '_date_high') !== FALSE) { $entityName = strstr($id, '_date', TRUE); - if (!empty($result['relative_dates']) && array_key_exists($entityName, $result['relative_dates'])) { - $result[$id] = NULL; - $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName]; - } - else { - $result[$id] = $value; - $result["{$entityName}_date_relative"] = 0; + + // This is the default, for non relative dates. We will overwrite + // it if we determine this is a relative date. + $result[$id] = $value; + $result["{$entityName}_date_relative"] = 0; + + if (!empty($result['relative_dates'])) { + if (array_key_exists($entityName, $result['relative_dates'])) { + // We have a match from a regular field. + $result[$id] = NULL; + $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName]; + } + elseif (!empty($specialDateFields[$id])) { + // We may have a match on a special date field. + $entityName = strstr($specialDateFields[$id], '_date', TRUE); + if (array_key_exists($entityName, $result['relative_dates'])) { + $result[$id] = NULL; + $result["{$entityName}_relative"] = $result['relative_dates'][$entityName]; + } + } } } else { @@ -172,7 +196,7 @@ public static function getFormValues($id) { unset($result['privacy']['do_not_toggle']); } - $result['privacy_options'] = array(); + $result['privacy_options'] = []; foreach ($result['privacy'] as $name => $val) { if ($val) { $result['privacy_options'][] = $name; @@ -183,6 +207,13 @@ public static function getFormValues($id) { } } + if ($customSearchClass = CRM_Utils_Array::value('customSearchClass', $result)) { + // check if there is a special function - formatSavedSearchFields defined in the custom search form + if (method_exists($customSearchClass, 'formatSavedSearchFields')) { + $customSearchClass::formatSavedSearchFields($result); + } + } + return $result; } @@ -246,7 +277,7 @@ public static function contactIDsSQL($id) { return CRM_Contact_BAO_SearchCustom::contactIDSQL(NULL, $id); } else { - $tables = $whereTables = array('civicrm_contact' => 1); + $tables = $whereTables = ['civicrm_contact' => 1]; $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables); if (!$where) { $where = '( 1 )'; @@ -274,10 +305,10 @@ public static function fromWhereEmail($id) { return CRM_Contact_BAO_SearchCustom::fromWhereEmail(NULL, $id); } else { - $tables = $whereTables = array('civicrm_contact' => 1, 'civicrm_email' => 1); + $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1]; $where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables); $from = CRM_Contact_BAO_Query::fromClause($whereTables); - return array($from, $where); + return [$from, $where]; } } else { @@ -289,45 +320,8 @@ public static function fromWhereEmail($id) { $where = " ( 1 ) "; $tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1; $tables['civicrm_email'] = $whereTables['civicrm_email'] = 1; - return array($from, $where); - } - } - - /** - * Given a saved search compute the clause and the tables and store it for future use. - */ - public function buildClause() { - $fv = unserialize($this->form_values); - - if ($this->mapping_id) { - $params = CRM_Core_BAO_Mapping::formattedFields($fv); + return [$from, $where]; } - else { - $params = CRM_Contact_BAO_Query::convertFormValues($fv); - } - - if (!empty($params)) { - $tables = $whereTables = array(); - $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables); - if (!empty($tables)) { - $this->select_tables = serialize($tables); - } - if (!empty($whereTables)) { - $this->where_tables = serialize($whereTables); - } - } - } - - /** - * Save the search. - * - * @param bool $hook - */ - public function save($hook = TRUE) { - // first build the computed fields - $this->buildClause(); - - parent::save($hook); } /** @@ -389,7 +383,7 @@ protected function assignTestValue($fieldName, &$fieldDef, $counter) { if ($fieldName == 'form_values') { // A dummy value for form_values. $this->{$fieldName} = serialize( - array('sort_name' => "SortName{$counter}")); + ['sort_name' => "SortName{$counter}"]); } else { parent::assignTestValues($fieldName, $fieldDef, $counter); @@ -403,10 +397,29 @@ protected function assignTestValue($fieldName, &$fieldDef, $counter) { * @param array $formValues */ public static function saveRelativeDates(&$queryParams, $formValues) { - $relativeDates = array('relative_dates' => array()); + // This is required only until all fields are converted to datepicker fields as the new format is truer to the + // form format and simply saves (e.g) custom_3_relative => "this.year" + $relativeDates = ['relative_dates' => []]; + $specialDateFields = [ + 'event_relative', + 'case_from_relative', + 'case_to_relative', + 'participant_relative', + 'log_date_relative', + 'birth_date_relative', + 'deceased_date_relative', + 'mailing_date_relative', + 'relation_date_relative', + 'relation_start_date_relative', + 'relation_end_date_relative', + 'relation_action_date_relative', + ]; foreach ($formValues as $id => $value) { - if (preg_match('/_date_relative$/', $id) && !empty($value)) { + if (in_array($id, $specialDateFields) && !empty($value)) { $entityName = strstr($id, '_date', TRUE); + if (empty($entityName)) { + $entityName = strstr($id, '_relative', TRUE); + } $relativeDates['relative_dates'][$entityName] = $value; } } @@ -426,14 +439,15 @@ public static function saveRelativeDates(&$queryParams, $formValues) { */ public static function saveSkippedElement(&$queryParams, $formValues) { // these are elements which are skipped in a smart group criteria - $specialElements = array( + $specialElements = [ 'operator', 'component_mode', 'display_relationship_type', - ); + 'uf_group_id', + ]; foreach ($specialElements as $element) { if (!empty($formValues[$element])) { - $queryParams[] = array($element, '=', $formValues[$element], 0, 0); + $queryParams[] = [$element, '=', $formValues[$element], 0, 0]; } } } @@ -453,7 +467,12 @@ public static function decodeRelativeFields(&$formValues, $fieldName, $op, $valu // select date range as default if ($isCustomDateField) { - $formValues[$fieldName . '_relative'] = 0; + if (array_key_exists('relative_dates', $formValues) && array_key_exists($fieldName, $formValues['relative_dates'])) { + $formValues[$fieldName . '_relative'] = $formValues['relative_dates'][$fieldName]; + } + else { + $formValues[$fieldName . '_relative'] = 0; + } } switch ($op) { case 'BETWEEN': diff --git a/CRM/Contact/BAO/SearchCustom.php b/CRM/Contact/BAO/SearchCustom.php index e13bc52c4f14..cadd086e4c40 100644 --- a/CRM/Contact/BAO/SearchCustom.php +++ b/CRM/Contact/BAO/SearchCustom.php @@ -1,9 +1,9 @@ 'custom_search', 'return' => 'name', 'value' => $customSearchID, - )); + ]); $ext = CRM_Extension_System::singleton()->getMapper(); @@ -95,7 +95,7 @@ public static function details($csID, $ssID = NULL, $gID = NULL) { CRM_Core_Error::fatal('Custom search file: ' . $customSearchFile . ' does not exist. Please verify your custom search settings in CiviCRM administrative panel.'); } - return array($customSearchID, $customSearchClass, $formValues); + return [$customSearchID, $customSearchClass, $formValues]; } /** @@ -138,7 +138,7 @@ public static function &buildFormValues($args) { $args = trim($args); $values = explode("\n", $args); - $formValues = array(); + $formValues = []; foreach ($values as $value) { list($n, $v) = CRM_Utils_System::explode('=', $value, 2); if (!empty($v)) { @@ -160,7 +160,7 @@ public static function fromWhereEmail($csID, $ssID) { $from = $customClass->from(); $where = $customClass->where(); - return array($from, $where); + return [$from, $where]; } } diff --git a/CRM/Contact/BAO/SubscriptionHistory.php b/CRM/Contact/BAO/SubscriptionHistory.php index 331e2add53fb..ec1a44d18991 100644 --- a/CRM/Contact/BAO/SubscriptionHistory.php +++ b/CRM/Contact/BAO/SubscriptionHistory.php @@ -1,9 +1,9 @@ __table = 'civicrm_acl_contact_cache'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'user_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('ACL Contact Cache ID') , - 'description' => 'primary key', - 'required' => true, + 'title' => ts('ACL Contact Cache ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'where' => 'civicrm_acl_contact_cache.id', 'table_name' => 'civicrm_acl_contact_cache', 'entity' => 'ACLContactCache', 'bao' => 'CRM_Contact_DAO_ACLContactCache', 'localizable' => 0, - ) , - 'user_id' => array( + ], + 'user_id' => [ 'name' => 'user_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'FK to civicrm_contact (could be null for anon user)', + 'title' => ts('Contact ID'), + 'description' => ts('FK to civicrm_contact (could be null for anon user)'), + 'where' => 'civicrm_acl_contact_cache.user_id', 'table_name' => 'civicrm_acl_contact_cache', 'entity' => 'ACLContactCache', 'bao' => 'CRM_Contact_DAO_ACLContactCache', 'localizable' => 0, - 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'contact_id' => array( + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'FK to civicrm_contact', - 'required' => true, + 'title' => ts('Contact ID'), + 'description' => ts('FK to civicrm_contact'), + 'required' => TRUE, + 'where' => 'civicrm_acl_contact_cache.contact_id', 'table_name' => 'civicrm_acl_contact_cache', 'entity' => 'ACLContactCache', 'bao' => 'CRM_Contact_DAO_ACLContactCache', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'operation' => array( + ], + 'operation' => [ 'name' => 'operation', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Operation') , - 'description' => 'What operation does this user have permission on?', - 'required' => true, + 'title' => ts('Operation'), + 'description' => ts('What operation does this user have permission on?'), + 'required' => TRUE, 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, + 'where' => 'civicrm_acl_contact_cache.operation', 'table_name' => 'civicrm_acl_contact_cache', 'entity' => 'ACLContactCache', 'bao' => 'CRM_Contact_DAO_ACLContactCache', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_ACL_BAO_ACL::operation', - ) - ) , - ); + ], + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -197,10 +187,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_contact_cache', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_contact_cache', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -208,27 +199,33 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_contact_cache', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_contact_cache', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'UI_user_contact_operation' => array( + $indices = [ + 'UI_user_contact_operation' => [ 'name' => 'UI_user_contact_operation', - 'field' => array( + 'field' => [ 0 => 'user_id', 1 => 'contact_id', 2 => 'operation', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_acl_contact_cache::1::user_id::contact_id::operation', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/Contact.php b/CRM/Contact/DAO/Contact.php index ab724755b13d..a7da4e718e99 100644 --- a/CRM/Contact/DAO/Contact.php +++ b/CRM/Contact/DAO/Contact.php @@ -1,1394 +1,1424 @@ __table = 'civicrm_contact'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'primary_contact_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'employer_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'primary_contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'employer_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'Unique Contact ID', - 'required' => true, - 'import' => true, + 'title' => ts('Contact ID'), + 'description' => ts('Unique Contact ID'), + 'required' => TRUE, + 'import' => TRUE, 'where' => 'civicrm_contact.id', 'headerPattern' => '/internal|contact?|id$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'contact_type' => array( + ], + 'contact_type' => [ 'name' => 'contact_type', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Type') , - 'description' => 'Type of Contact.', + 'title' => ts('Contact Type'), + 'description' => ts('Type of Contact.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, - 'export' => true, 'where' => 'civicrm_contact.contact_type', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NULL', - ) - ) , - 'contact_sub_type' => array( + ], + ], + 'contact_sub_type' => [ 'name' => 'contact_sub_type', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Subtype') , - 'description' => 'May be used to over-ride contact view and edit templates.', + 'title' => ts('Contact Subtype'), + 'description' => ts('May be used to over-ride contact view and edit templates.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.contact_sub_type', 'headerPattern' => '/C(ontact )?(subtype|sub-type|sub type)/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND, + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NOT NULL', - ) - ) , - 'do_not_email' => array( + ], + ], + 'do_not_email' => [ 'name' => 'do_not_email', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Do Not Email') , - 'import' => true, + 'title' => ts('Do Not Email'), + 'import' => TRUE, 'where' => 'civicrm_contact.do_not_email', 'headerPattern' => '/d(o )?(not )?(email)/i', 'dataPattern' => '/^\d{1,}$/', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'do_not_phone' => array( + ], + ], + 'do_not_phone' => [ 'name' => 'do_not_phone', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Do Not Phone') , - 'import' => true, + 'title' => ts('Do Not Phone'), + 'import' => TRUE, 'where' => 'civicrm_contact.do_not_phone', 'headerPattern' => '/d(o )?(not )?(call|phone)/i', 'dataPattern' => '/^\d{1,}$/', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'do_not_mail' => array( + ], + ], + 'do_not_mail' => [ 'name' => 'do_not_mail', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Do Not Mail') , - 'import' => true, + 'title' => ts('Do Not Mail'), + 'import' => TRUE, 'where' => 'civicrm_contact.do_not_mail', 'headerPattern' => '/^(d(o\s)?n(ot\s)?mail)|(\w*)?bulk\s?(\w*)$/i', 'dataPattern' => '/^\d{1,}$/', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'do_not_sms' => array( + ], + ], + 'do_not_sms' => [ 'name' => 'do_not_sms', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Do Not Sms') , - 'import' => true, + 'title' => ts('Do Not Sms'), + 'import' => TRUE, 'where' => 'civicrm_contact.do_not_sms', 'headerPattern' => '/d(o )?(not )?(sms)/i', 'dataPattern' => '/^\d{1,}$/', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'do_not_trade' => array( + ], + ], + 'do_not_trade' => [ 'name' => 'do_not_trade', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Do Not Trade') , - 'import' => true, + 'title' => ts('Do Not Trade'), + 'import' => TRUE, 'where' => 'civicrm_contact.do_not_trade', 'headerPattern' => '/d(o )?(not )?(trade)/i', 'dataPattern' => '/^\d{1,}$/', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'is_opt_out' => array( + ], + ], + 'is_opt_out' => [ 'name' => 'is_opt_out', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('No Bulk Emails (User Opt Out)') , - 'description' => 'Has the contact opted out from receiving all bulk email from the organization or site domain?', - 'required' => true, - 'import' => true, + 'title' => ts('No Bulk Emails (User Opt Out)'), + 'description' => ts('Has the contact opted out from receiving all bulk email from the organization or site domain?'), + 'required' => TRUE, + 'import' => TRUE, 'where' => 'civicrm_contact.is_opt_out', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'legal_identifier' => array( + ], + ], + 'legal_identifier' => [ 'name' => 'legal_identifier', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Legal Identifier') , - 'description' => 'May be used for SSN, EIN/TIN, Household ID (census) or other applicable unique legal/government ID. - ', + 'title' => ts('Legal Identifier'), + 'description' => ts('May be used for SSN, EIN/TIN, Household ID (census) or other applicable unique legal/government ID.'), 'maxlength' => 32, 'size' => CRM_Utils_Type::MEDIUM, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.legal_identifier', 'headerPattern' => '/legal\s?id/i', 'dataPattern' => '/\w+?\d{5,}/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'external_identifier' => array( + ], + ], + 'external_identifier' => [ 'name' => 'external_identifier', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('External Identifier') , - 'description' => 'Unique trusted external ID (generally from a legacy app/datasource). Particularly useful for deduping operations.', + 'title' => ts('External Identifier'), + 'description' => ts('Unique trusted external ID (generally from a legacy app/datasource). Particularly useful for deduping operations.'), 'maxlength' => 64, 'size' => 8, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.external_identifier', 'headerPattern' => '/external\s?id/i', 'dataPattern' => '/^\d{11,}$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'sort_name' => array( + ], + ], + 'sort_name' => [ 'name' => 'sort_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Sort Name') , - 'description' => 'Name used for sorting different contact types', + 'title' => ts('Sort Name'), + 'description' => ts('Name used for sorting different contact types'), 'maxlength' => 128, 'size' => 30, - 'export' => true, 'where' => 'civicrm_contact.sort_name', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'display_name' => array( + ], + ], + 'display_name' => [ 'name' => 'display_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Display Name') , - 'description' => 'Formatted name representing preferred format for display/print/other output.', + 'title' => ts('Display Name'), + 'description' => ts('Formatted name representing preferred format for display/print/other output.'), 'maxlength' => 128, 'size' => 30, - 'export' => true, 'where' => 'civicrm_contact.display_name', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'nick_name' => array( + ], + ], + 'nick_name' => [ 'name' => 'nick_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Nickname') , - 'description' => 'Nickname.', + 'title' => ts('Nickname'), + 'description' => ts('Nickname.'), 'maxlength' => 128, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.nick_name', 'headerPattern' => '/n(ick\s)name|nick$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'legal_name' => array( + ], + ], + 'legal_name' => [ 'name' => 'legal_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Legal Name') , - 'description' => 'Legal Name.', + 'title' => ts('Legal Name'), + 'description' => ts('Legal Name.'), 'maxlength' => 128, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.legal_name', 'headerPattern' => '/^legal|(l(egal\s)?name)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'image_URL' => array( + ], + ], + 'image_URL' => [ 'name' => 'image_URL', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Image Url') , - 'description' => 'optional URL for preferred image (photo, logo, etc.) to display for this contact.', - 'import' => true, + 'title' => ts('Image Url'), + 'description' => ts('optional URL for preferred image (photo, logo, etc.) to display for this contact.'), + 'import' => TRUE, 'where' => 'civicrm_contact.image_URL', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'File', - ) , - ) , - 'preferred_communication_method' => array( + ], + ], + 'preferred_communication_method' => [ 'name' => 'preferred_communication_method', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Preferred Communication Method') , - 'description' => 'What is the preferred mode of communication.', + 'title' => ts('Preferred Communication Method'), + 'description' => ts('What is the preferred mode of communication.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.preferred_communication_method', 'headerPattern' => '/^p(ref\w*\s)?c(omm\w*)|( meth\w*)$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND, + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'preferred_communication_method', 'optionEditPath' => 'civicrm/admin/options/preferred_communication_method', - ) - ) , - 'preferred_language' => array( + ], + ], + 'preferred_language' => [ 'name' => 'preferred_language', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Preferred Language') , - 'description' => 'Which language is preferred for communication. FK to languages in civicrm_option_value.', + 'title' => ts('Preferred Language'), + 'description' => ts('Which language is preferred for communication. FK to languages in civicrm_option_value.'), 'maxlength' => 5, 'size' => CRM_Utils_Type::SIX, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.preferred_language', 'headerPattern' => '/^lang/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'languages', 'keyColumn' => 'name', 'optionEditPath' => 'civicrm/admin/options/languages', - ) - ) , - 'preferred_mail_format' => array( + ], + ], + 'preferred_mail_format' => [ 'name' => 'preferred_mail_format', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Preferred Mail Format') , - 'description' => 'What is the preferred mode of sending an email.', + 'title' => ts('Preferred Mail Format'), + 'description' => ts('What is the preferred mode of sending an email.'), 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.preferred_mail_format', 'headerPattern' => '/^p(ref\w*\s)?m(ail\s)?f(orm\w*)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'default' => 'Both', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_Core_SelectValues::pmf', - ) - ) , - 'hash' => array( + ], + ], + 'hash' => [ 'name' => 'hash', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Hash') , - 'description' => 'Key for validating requests related to this contact.', + 'title' => ts('Contact Hash'), + 'description' => ts('Key for validating requests related to this contact.'), 'maxlength' => 32, 'size' => CRM_Utils_Type::MEDIUM, - 'export' => true, 'where' => 'civicrm_contact.hash', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'api_key' => array( + ], + 'api_key' => [ 'name' => 'api_key', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Api Key') , - 'description' => 'API Key for validating requests related to this contact.', + 'title' => ts('Api Key'), + 'description' => ts('API Key for validating requests related to this contact.'), 'maxlength' => 32, 'size' => CRM_Utils_Type::MEDIUM, + 'where' => 'civicrm_contact.api_key', + 'permission' => [ + [ + 'administer CiviCRM', + 'edit api keys', + ], + ], 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'contact_source' => array( + ], + 'contact_source' => [ 'name' => 'source', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Source') , - 'description' => 'where contact come from, e.g. import, donate module insert...', + 'title' => ts('Contact Source'), + 'description' => ts('where contact come from, e.g. import, donate module insert...'), 'maxlength' => 255, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.source', 'headerPattern' => '/(C(ontact\s)?Source)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'first_name' => array( + ], + ], + 'first_name' => [ 'name' => 'first_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('First Name') , - 'description' => 'First Name.', + 'title' => ts('First Name'), + 'description' => ts('First Name.'), 'maxlength' => 64, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.first_name', 'headerPattern' => '/^first|(f(irst\s)?name)$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'middle_name' => array( + ], + ], + 'middle_name' => [ 'name' => 'middle_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Middle Name') , - 'description' => 'Middle Name.', + 'title' => ts('Middle Name'), + 'description' => ts('Middle Name.'), 'maxlength' => 64, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.middle_name', 'headerPattern' => '/^middle|(m(iddle\s)?name)$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'last_name' => array( + ], + ], + 'last_name' => [ 'name' => 'last_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Last Name') , - 'description' => 'Last Name.', + 'title' => ts('Last Name'), + 'description' => ts('Last Name.'), 'maxlength' => 64, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.last_name', 'headerPattern' => '/^last|(l(ast\s)?name)$/i', 'dataPattern' => '/^\w+(\s\w+)?+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'prefix_id' => array( + ], + ], + 'prefix_id' => [ 'name' => 'prefix_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Individual Prefix') , - 'description' => 'Prefix or Title for name (Ms, Mr...). FK to prefix ID', - 'import' => true, + 'title' => ts('Individual Prefix'), + 'description' => ts('Prefix or Title for name (Ms, Mr...). FK to prefix ID'), + 'import' => TRUE, 'where' => 'civicrm_contact.prefix_id', 'headerPattern' => '/^(prefix|title)/i', 'dataPattern' => '/^(mr|ms|mrs|sir|dr)\.?$/i', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'individual_prefix', 'optionEditPath' => 'civicrm/admin/options/individual_prefix', - ) - ) , - 'suffix_id' => array( + ], + ], + 'suffix_id' => [ 'name' => 'suffix_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Individual Suffix') , - 'description' => 'Suffix for name (Jr, Sr...). FK to suffix ID', - 'import' => true, + 'title' => ts('Individual Suffix'), + 'description' => ts('Suffix for name (Jr, Sr...). FK to suffix ID'), + 'import' => TRUE, 'where' => 'civicrm_contact.suffix_id', 'headerPattern' => '/^suffix$/i', 'dataPattern' => '/^(sr|jr)\.?|i{2,}$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'individual_suffix', 'optionEditPath' => 'civicrm/admin/options/individual_suffix', - ) - ) , - 'formal_title' => array( + ], + ], + 'formal_title' => [ 'name' => 'formal_title', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Formal Title') , - 'description' => 'Formal (academic or similar) title in front of name. (Prof., Dr. etc.)', + 'title' => ts('Formal Title'), + 'description' => ts('Formal (academic or similar) title in front of name. (Prof., Dr. etc.)'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.formal_title', 'headerPattern' => '/^title/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'communication_style_id' => array( + ], + ], + 'communication_style_id' => [ 'name' => 'communication_style_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Communication Style') , - 'description' => 'Communication style (e.g. formal vs. familiar) to use with this contact. FK to communication styles in civicrm_option_value.', - 'export' => true, + 'title' => ts('Communication Style'), + 'description' => ts('Communication style (e.g. formal vs. familiar) to use with this contact. FK to communication styles in civicrm_option_value.'), + 'import' => TRUE, 'where' => 'civicrm_contact.communication_style_id', - 'headerPattern' => '', - 'dataPattern' => '', + 'headerPattern' => '/style/i', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'communication_style', 'optionEditPath' => 'civicrm/admin/options/communication_style', - ) - ) , - 'email_greeting_id' => array( + ], + ], + 'email_greeting_id' => [ 'name' => 'email_greeting_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Email Greeting ID') , - 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Email Greeting.', + 'title' => ts('Email Greeting ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Email Greeting.'), + 'where' => 'civicrm_contact.email_greeting_id', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'email_greeting_custom' => array( + 'pseudoconstant' => [ + 'optionGroupName' => 'email_greeting', + 'optionEditPath' => 'civicrm/admin/options/email_greeting', + ], + ], + 'email_greeting_custom' => [ 'name' => 'email_greeting_custom', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Email Greeting Custom') , - 'description' => 'Custom Email Greeting.', + 'title' => ts('Email Greeting Custom'), + 'description' => ts('Custom Email Greeting.'), 'maxlength' => 128, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.email_greeting_custom', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => false, + 'export' => FALSE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'email_greeting_display' => array( + ], + ], + 'email_greeting_display' => [ 'name' => 'email_greeting_display', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Email Greeting') , - 'description' => 'Cache Email Greeting.', + 'title' => ts('Email Greeting'), + 'description' => ts('Cache Email Greeting.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_contact.email_greeting_display', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'postal_greeting_id' => array( + ], + ], + 'postal_greeting_id' => [ 'name' => 'postal_greeting_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Postal Greeting ID') , - 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Postal Greeting.', + 'title' => ts('Postal Greeting ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Postal Greeting.'), + 'where' => 'civicrm_contact.postal_greeting_id', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'postal_greeting_custom' => array( + ], + 'pseudoconstant' => [ + 'optionGroupName' => 'postal_greeting', + 'optionEditPath' => 'civicrm/admin/options/postal_greeting', + ], + ], + 'postal_greeting_custom' => [ 'name' => 'postal_greeting_custom', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Postal Greeting Custom') , - 'description' => 'Custom Postal greeting.', + 'title' => ts('Postal Greeting Custom'), + 'description' => ts('Custom Postal greeting.'), 'maxlength' => 128, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.postal_greeting_custom', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => false, + 'export' => FALSE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'postal_greeting_display' => array( + ], + ], + 'postal_greeting_display' => [ 'name' => 'postal_greeting_display', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Postal Greeting') , - 'description' => 'Cache Postal greeting.', + 'title' => ts('Postal Greeting'), + 'description' => ts('Cache Postal greeting.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_contact.postal_greeting_display', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'addressee_id' => array( + ], + ], + 'addressee_id' => [ 'name' => 'addressee_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Addressee ID') , - 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Addressee.', + 'title' => ts('Addressee ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Addressee.'), + 'where' => 'civicrm_contact.addressee_id', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'addressee_custom' => array( + 'pseudoconstant' => [ + 'optionGroupName' => 'addressee', + 'optionEditPath' => 'civicrm/admin/options/addressee', + ], + ], + 'addressee_custom' => [ 'name' => 'addressee_custom', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Addressee Custom') , - 'description' => 'Custom Addressee.', + 'title' => ts('Addressee Custom'), + 'description' => ts('Custom Addressee.'), 'maxlength' => 128, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.addressee_custom', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => false, + 'export' => FALSE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'addressee_display' => array( + ], + ], + 'addressee_display' => [ 'name' => 'addressee_display', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Addressee') , - 'description' => 'Cache Addressee.', + 'title' => ts('Addressee'), + 'description' => ts('Cache Addressee.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_contact.addressee_display', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'job_title' => array( + ], + ], + 'job_title' => [ 'name' => 'job_title', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Job Title') , - 'description' => 'Job Title', + 'title' => ts('Job Title'), + 'description' => ts('Job Title'), 'maxlength' => 255, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.job_title', 'headerPattern' => '/^job|(j(ob\s)?title)$/i', 'dataPattern' => '//', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'gender_id' => array( + ], + ], + 'gender_id' => [ 'name' => 'gender_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Gender') , - 'description' => 'FK to gender ID', - 'import' => true, + 'title' => ts('Gender'), + 'description' => ts('FK to gender ID'), + 'import' => TRUE, 'where' => 'civicrm_contact.gender_id', 'headerPattern' => '/^gender$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'optionGroupName' => 'gender', 'optionEditPath' => 'civicrm/admin/options/gender', - ) - ) , - 'birth_date' => array( + ], + ], + 'birth_date' => [ 'name' => 'birth_date', 'type' => CRM_Utils_Type::T_DATE, - 'title' => ts('Birth Date') , - 'description' => 'Date of birth', - 'import' => true, + 'title' => ts('Birth Date'), + 'description' => ts('Date of birth'), + 'import' => TRUE, 'where' => 'civicrm_contact.birth_date', 'headerPattern' => '/^birth|(b(irth\s)?date)|D(\W*)O(\W*)B(\W*)$/i', 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select Date', 'formatType' => 'birth', - ) , - ) , - 'is_deceased' => array( + ], + ], + 'is_deceased' => [ 'name' => 'is_deceased', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Deceased') , - 'import' => true, + 'title' => ts('Deceased'), + 'import' => TRUE, 'where' => 'civicrm_contact.is_deceased', 'headerPattern' => '/i(s\s)?d(eceased)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'deceased_date' => array( + ], + ], + 'deceased_date' => [ 'name' => 'deceased_date', 'type' => CRM_Utils_Type::T_DATE, - 'title' => ts('Deceased Date') , - 'description' => 'Date of deceased', - 'import' => true, + 'title' => ts('Deceased Date'), + 'description' => ts('Date of deceased'), + 'import' => TRUE, 'where' => 'civicrm_contact.deceased_date', 'headerPattern' => '/^deceased|(d(eceased\s)?date)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select Date', 'formatType' => 'birth', - ) , - ) , - 'household_name' => array( + ], + ], + 'household_name' => [ 'name' => 'household_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Household Name') , - 'description' => 'Household Name.', + 'title' => ts('Household Name'), + 'description' => ts('Household Name.'), 'maxlength' => 128, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.household_name', 'headerPattern' => '/^household|(h(ousehold\s)?name)$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'primary_contact_id' => array( + ], + ], + 'primary_contact_id' => [ 'name' => 'primary_contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Household Primary Contact ID') , - 'description' => 'Optional FK to Primary Contact for this household.', + 'title' => ts('Household Primary Contact ID'), + 'description' => ts('Optional FK to Primary Contact for this household.'), + 'where' => 'civicrm_contact.primary_contact_id', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - ) , - 'organization_name' => array( + ], + ], + 'organization_name' => [ 'name' => 'organization_name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Organization Name') , - 'description' => 'Organization Name.', + 'title' => ts('Organization Name'), + 'description' => ts('Organization Name.'), 'maxlength' => 128, 'size' => 30, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.organization_name', 'headerPattern' => '/^organization|(o(rganization\s)?name)$/i', 'dataPattern' => '/^\w+$/', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'sic_code' => array( + ], + ], + 'sic_code' => [ 'name' => 'sic_code', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Sic Code') , - 'description' => 'Standard Industry Classification Code.', + 'title' => ts('Sic Code'), + 'description' => ts('Standard Industry Classification Code.'), 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.sic_code', 'headerPattern' => '/^sic|(s(ic\s)?code)$/i', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'user_unique_id' => array( + ], + ], + 'user_unique_id' => [ 'name' => 'user_unique_id', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Unique ID (OpenID)') , - 'description' => 'the OpenID (or OpenID-style http://username.domain/) unique identifier for this contact mainly used for logging in to CiviCRM', + 'title' => ts('Unique ID (OpenID)'), + 'description' => ts('the OpenID (or OpenID-style http://username.domain/) unique identifier for this contact mainly used for logging in to CiviCRM'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - 'import' => true, + 'import' => TRUE, 'where' => 'civicrm_contact.user_unique_id', 'headerPattern' => '/^Open\s?ID|u(niq\w*)?\s?ID/i', 'dataPattern' => '/^[\w\/\:\.]+$/', - 'export' => true, + 'export' => TRUE, 'rule' => 'url', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'current_employer_id' => array( + ], + ], + 'current_employer_id' => [ 'name' => 'employer_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Current Employer') , - 'description' => 'OPTIONAL FK to civicrm_contact record.', - 'export' => true, + 'title' => ts('Current Employer'), + 'description' => ts('OPTIONAL FK to civicrm_contact record.'), 'where' => 'civicrm_contact.employer_id', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - 'html' => array( + 'html' => [ 'type' => 'EntityRef', - ) , - ) , - 'contact_is_deleted' => array( + ], + ], + 'contact_is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Contact is in Trash') , - 'required' => true, - 'export' => true, + 'title' => ts('Contact is in Trash'), + 'required' => TRUE, 'where' => 'civicrm_contact.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, + 'default' => '0', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'created_date' => array( + ], + ], + 'created_date' => [ 'name' => 'created_date', 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Created Date') , - 'description' => 'When was the contact was created.', - 'required' => false, - 'export' => true, + 'title' => ts('Created Date'), + 'description' => ts('When was the contact was created.'), + 'required' => FALSE, 'where' => 'civicrm_contact.created_date', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'default' => 'NULL', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - 'modified_date' => array( + ], + 'modified_date' => [ 'name' => 'modified_date', 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Modified Date') , - 'description' => 'When was the contact (or closely related entity) was created or modified or deleted.', - 'required' => false, - 'export' => true, + 'title' => ts('Modified Date'), + 'description' => ts('When was the contact (or closely related entity) was created or modified or deleted.'), + 'required' => FALSE, 'where' => 'civicrm_contact.modified_date', - 'headerPattern' => '', - 'dataPattern' => '', + 'export' => TRUE, 'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', 'table_name' => 'civicrm_contact', 'entity' => 'Contact', 'bao' => 'CRM_Contact_BAO_Contact', 'localizable' => 0, - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -1396,10 +1426,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -1407,147 +1438,177 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'index_contact_type' => array( + $indices = [ + 'index_contact_type' => [ 'name' => 'index_contact_type', - 'field' => array( + 'field' => [ 0 => 'contact_type', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::contact_type', - ) , - 'index_contact_sub_type' => array( + ], + 'index_contact_sub_type' => [ 'name' => 'index_contact_sub_type', - 'field' => array( + 'field' => [ 0 => 'contact_sub_type', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::contact_sub_type', - ) , - 'UI_external_identifier' => array( + ], + 'UI_external_identifier' => [ 'name' => 'UI_external_identifier', - 'field' => array( + 'field' => [ 0 => 'external_identifier', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_contact::1::external_identifier', - ) , - 'index_sort_name' => array( + ], + 'index_sort_name' => [ 'name' => 'index_sort_name', - 'field' => array( + 'field' => [ 0 => 'sort_name', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::sort_name', - ) , - 'index_preferred_communication_method' => array( + ], + 'index_preferred_communication_method' => [ 'name' => 'index_preferred_communication_method', - 'field' => array( + 'field' => [ 0 => 'preferred_communication_method', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::preferred_communication_method', - ) , - 'index_hash' => array( + ], + 'index_hash' => [ 'name' => 'index_hash', - 'field' => array( + 'field' => [ 0 => 'hash', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::hash', - ) , - 'index_api_key' => array( + ], + 'index_api_key' => [ 'name' => 'index_api_key', - 'field' => array( + 'field' => [ 0 => 'api_key', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::api_key', - ) , - 'index_first_name' => array( + ], + 'index_first_name' => [ 'name' => 'index_first_name', - 'field' => array( + 'field' => [ 0 => 'first_name', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::first_name', - ) , - 'index_last_name' => array( + ], + 'index_last_name' => [ 'name' => 'index_last_name', - 'field' => array( + 'field' => [ 0 => 'last_name', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::last_name', - ) , - 'UI_prefix' => array( + ], + 'UI_prefix' => [ 'name' => 'UI_prefix', - 'field' => array( + 'field' => [ 0 => 'prefix_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::prefix_id', - ) , - 'UI_suffix' => array( + ], + 'UI_suffix' => [ 'name' => 'UI_suffix', - 'field' => array( + 'field' => [ 0 => 'suffix_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::suffix_id', - ) , - 'index_communication_style_id' => array( + ], + 'index_communication_style_id' => [ 'name' => 'index_communication_style_id', - 'field' => array( + 'field' => [ 0 => 'communication_style_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::communication_style_id', - ) , - 'UI_gender' => array( + ], + 'UI_gender' => [ 'name' => 'UI_gender', - 'field' => array( + 'field' => [ 0 => 'gender_id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::gender_id', - ) , - 'index_household_name' => array( + ], + 'index_is_deceased' => [ + 'name' => 'index_is_deceased', + 'field' => [ + 0 => 'is_deceased', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::is_deceased', + ], + 'index_household_name' => [ 'name' => 'index_household_name', - 'field' => array( + 'field' => [ 0 => 'household_name', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::household_name', - ) , - 'index_organization_name' => array( + ], + 'index_organization_name' => [ 'name' => 'index_organization_name', - 'field' => array( + 'field' => [ 0 => 'organization_name', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::organization_name', - ) , - 'index_is_deleted_sort_name' => array( + ], + 'index_is_deleted_sort_name' => [ 'name' => 'index_is_deleted_sort_name', - 'field' => array( + 'field' => [ 0 => 'is_deleted', 1 => 'sort_name', 2 => 'id', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_contact::0::is_deleted::sort_name::id', - ) , - ); + ], + 'index_created_date' => [ + 'name' => 'index_created_date', + 'field' => [ + 0 => 'created_date', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::created_date', + ], + 'index_modified_date' => [ + 'name' => 'index_modified_date', + 'field' => [ + 0 => 'modified_date', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::modified_date', + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/ContactType.php b/CRM/Contact/DAO/ContactType.php index efc21bcb8e6e..b6db4bf85612 100644 --- a/CRM/Contact/DAO/ContactType.php +++ b/CRM/Contact/DAO/ContactType.php @@ -1,264 +1,264 @@ __table = 'civicrm_contact_type'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_contact_type', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_contact_type', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact Type ID') , - 'description' => 'Contact Type ID', - 'required' => true, + 'title' => ts('Contact Type ID'), + 'description' => ts('Contact Type ID'), + 'required' => TRUE, + 'where' => 'civicrm_contact_type.id', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, - ) , - 'name' => array( + ], + 'name' => [ 'name' => 'name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Name') , - 'description' => 'Internal name of Contact Type (or Subtype).', + 'title' => ts('Name'), + 'description' => ts('Internal name of Contact Type (or Subtype).'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_contact_type.name', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, - ) , - 'label' => array( + ], + 'label' => [ 'name' => 'label', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Type Label') , - 'description' => 'localized Name of Contact Type.', + 'title' => ts('Contact Type Label'), + 'description' => ts('localized Name of Contact Type.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_contact_type.label', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 1, - ) , - 'description' => array( + ], + 'description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Contact Type Description') , - 'description' => 'localized Optional verbose description of the type.', + 'title' => ts('Contact Type Description'), + 'description' => ts('localized Optional verbose description of the type.'), 'rows' => 2, 'cols' => 60, + 'where' => 'civicrm_contact_type.description', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 1, - 'html' => array( + 'html' => [ 'type' => 'TextArea', - ) , - ) , - 'image_URL' => array( + ], + ], + 'image_URL' => [ 'name' => 'image_URL', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Type Image URL') , - 'description' => 'URL of image if any.', + 'title' => ts('Contact Type Image URL'), + 'description' => ts('URL of image if any.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_contact_type.image_URL', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, - ) , - 'parent_id' => array( + ], + 'parent_id' => [ 'name' => 'parent_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact Type Parent') , - 'description' => 'Optional FK to parent contact type.', + 'title' => ts('Contact Type Parent'), + 'description' => ts('Optional FK to parent contact type.'), + 'where' => 'civicrm_contact_type.parent_id', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_ContactType', - 'pseudoconstant' => array( + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'id', 'labelColumn' => 'label', 'condition' => 'parent_id IS NULL', - ) - ) , - 'is_active' => array( + ], + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Contact Type Is Active?') , - 'description' => 'Is this entry active?', + 'title' => ts('Contact Type Is Active?'), + 'description' => ts('Is this entry active?'), + 'where' => 'civicrm_contact_type.is_active', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, - ) , - 'is_reserved' => array( + ], + 'is_reserved' => [ 'name' => 'is_reserved', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Contact Type is Reserved?') , - 'description' => 'Is this contact type a predefined system type', + 'title' => ts('Contact Type is Reserved?'), + 'description' => ts('Is this contact type a predefined system type'), + 'where' => 'civicrm_contact_type.is_reserved', 'table_name' => 'civicrm_contact_type', 'entity' => 'ContactType', 'bao' => 'CRM_Contact_BAO_ContactType', 'localizable' => 0, - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return CRM_Core_DAO::getLocaleTableName(self::$_tableName); } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -266,10 +266,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact_type', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact_type', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -277,25 +278,31 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact_type', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact_type', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'contact_type' => array( + $indices = [ + 'contact_type' => [ 'name' => 'contact_type', - 'field' => array( + 'field' => [ 0 => 'name', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_contact_type::1::name', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/DashboardContact.php b/CRM/Contact/DAO/DashboardContact.php index 951be6206121..e9456cec9e11 100644 --- a/CRM/Contact/DAO/DashboardContact.php +++ b/CRM/Contact/DAO/DashboardContact.php @@ -1,217 +1,215 @@ __table = 'civicrm_dashboard_contact'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'dashboard_id', 'civicrm_dashboard', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'dashboard_id', 'civicrm_dashboard', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Dashboard Contact ID') , - 'required' => true, + 'title' => ts('Dashboard Contact ID'), + 'required' => TRUE, + 'where' => 'civicrm_dashboard_contact.id', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, - ) , - 'dashboard_id' => array( + ], + 'dashboard_id' => [ 'name' => 'dashboard_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Dashboard') , - 'description' => 'Dashboard ID', - 'required' => true, + 'title' => ts('Dashboard'), + 'description' => ts('Dashboard ID'), + 'required' => TRUE, + 'where' => 'civicrm_dashboard_contact.dashboard_id', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, 'FKClassName' => 'CRM_Core_DAO_Dashboard', - ) , - 'contact_id' => array( + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Dashboard Contact') , - 'description' => 'Contact ID', - 'required' => true, + 'title' => ts('Dashboard Contact'), + 'description' => ts('Contact ID'), + 'required' => TRUE, + 'where' => 'civicrm_dashboard_contact.contact_id', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'column_no' => array( + ], + 'column_no' => [ 'name' => 'column_no', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Column No') , - 'description' => 'column no for this widget', + 'title' => ts('Column No'), + 'description' => ts('column no for this widget'), + 'where' => 'civicrm_dashboard_contact.column_no', + 'default' => '0', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, - ) , - 'is_active' => array( + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Dashlet is Active?') , - 'description' => 'Is this widget active?', + 'title' => ts('Dashlet is Active?'), + 'description' => ts('Is this widget active?'), + 'where' => 'civicrm_dashboard_contact.is_active', + 'default' => '0', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, - ) , - 'weight' => array( + ], + 'weight' => [ 'name' => 'weight', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Order') , - 'description' => 'Ordering of the widgets.', + 'title' => ts('Order'), + 'description' => ts('Ordering of the widgets.'), + 'where' => 'civicrm_dashboard_contact.weight', + 'default' => '0', 'table_name' => 'civicrm_dashboard_contact', 'entity' => 'DashboardContact', 'bao' => 'CRM_Contact_BAO_DashboardContact', 'localizable' => 0, - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -219,10 +217,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dashboard_contact', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dashboard_contact', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -230,26 +229,32 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dashboard_contact', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dashboard_contact', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'index_dashboard_id_contact_id' => array( + $indices = [ + 'index_dashboard_id_contact_id' => [ 'name' => 'index_dashboard_id_contact_id', - 'field' => array( + 'field' => [ 0 => 'dashboard_id', 1 => 'contact_id', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_dashboard_contact::1::dashboard_id::contact_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/Factory.php b/CRM/Contact/DAO/Factory.php index 5f4432c2b50f..8af2fc1ac416 100644 --- a/CRM/Contact/DAO/Factory.php +++ b/CRM/Contact/DAO/Factory.php @@ -5,7 +5,7 @@ */ class CRM_Contact_DAO_Factory { - static $_classes = array( + public static $_classes = [ 'Address' => 'data', 'Contact' => 'data', 'Email' => 'data', @@ -17,39 +17,35 @@ class CRM_Contact_DAO_Factory { 'Organization' => 'data', 'Phone' => 'data', 'Relationship' => 'data', - ); + ]; - static $_prefix = array( - 'business' => 'CRM/Contact/BAO/', - 'data' => 'CRM/Contact/DAO/', - ); - - static $_suffix = '.php'; + public static $_prefix = [ + 'business' => 'CRM_Contact_BAO_', + 'data' => 'CRM_Contact_DAO_', + ]; /** * @param string $className * * @return mixed */ - static function &create($className) { + public static function create($className) { $type = CRM_Utils_Array::value($className, self::$_classes); if (!$type) { return CRM_Core_DAO_Factory::create($className); } - $file = self::$_prefix[$type] . $className; - $class = str_replace('/', '_', $file); - - require_once($file . self::$_suffix); + $class = self::$_prefix[$type] . $className; if ($type == 'singleton') { $newObj = $class::singleton(); } else { // this is either 'business' or 'data' - $newObj = new $class; + $newObj = new $class(); } return $newObj; } + } diff --git a/CRM/Contact/DAO/Group.php b/CRM/Contact/DAO/Group.php index f3a4ad3091aa..8e7ce46ae841 100644 --- a/CRM/Contact/DAO/Group.php +++ b/CRM/Contact/DAO/Group.php @@ -1,469 +1,504 @@ __table = 'civicrm_group'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'saved_search_id', 'civicrm_saved_search', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'modified_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'saved_search_id', 'civicrm_saved_search', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'modified_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group ID') , - 'description' => 'Group ID', - 'required' => true, + 'title' => ts('Group ID'), + 'description' => ts('Group ID'), + 'required' => TRUE, + 'where' => 'civicrm_group.id', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'name' => array( + ], + 'name' => [ 'name' => 'name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Name') , - 'description' => 'Internal name of Group.', + 'title' => ts('Group Name'), + 'description' => ts('Internal name of Group.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_group.name', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'title' => array( + ], + 'title' => [ 'name' => 'title', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Title') , - 'description' => 'Name of Group.', + 'title' => ts('Group Title'), + 'description' => ts('Name of Group.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_group.title', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 1, - ) , - 'description' => array( + 'html' => [ + 'type' => 'Text', + ], + ], + 'description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Group Description') , - 'description' => 'Optional verbose description of the group.', + 'title' => ts('Group Description'), + 'description' => ts('Optional verbose description of the group.'), 'rows' => 2, 'cols' => 60, + 'where' => 'civicrm_group.description', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'TextArea', - ) , - ) , - 'source' => array( + ], + ], + 'source' => [ 'name' => 'source', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Source') , - 'description' => 'Module or process which created this group.', + 'title' => ts('Group Source'), + 'description' => ts('Module or process which created this group.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_group.source', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'saved_search_id' => array( + ], + 'saved_search_id' => [ 'name' => 'saved_search_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Saved Search ID') , - 'description' => 'FK to saved search table.', + 'title' => ts('Saved Search ID'), + 'description' => ts('FK to saved search table.'), + 'where' => 'civicrm_group.saved_search_id', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_SavedSearch', - ) , - 'is_active' => array( + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Group Enabled') , - 'description' => 'Is this entry active?', + 'title' => ts('Group Enabled'), + 'description' => ts('Is this entry active?'), + 'where' => 'civicrm_group.is_active', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'visibility' => array( + ], + 'visibility' => [ 'name' => 'visibility', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Visibility Setting') , - 'description' => 'In what context(s) is this field visible.', + 'title' => ts('Group Visibility Setting'), + 'description' => ts('In what context(s) is this field visible.'), 'maxlength' => 24, 'size' => CRM_Utils_Type::MEDIUM, + 'where' => 'civicrm_group.visibility', 'default' => 'User and User Admin Only', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_Core_SelectValues::groupVisibility', - ) - ) , - 'where_clause' => array( + ], + ], + 'where_clause' => [ 'name' => 'where_clause', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Group Where Clause') , - 'description' => 'the sql where clause if a saved search acl', + 'title' => ts('Group Where Clause'), + 'description' => ts('the sql where clause if a saved search acl'), + 'where' => 'civicrm_group.where_clause', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'select_tables' => array( + ], + 'select_tables' => [ 'name' => 'select_tables', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Tables For Select Clause') , - 'description' => 'the tables to be included in a select data', + 'title' => ts('Tables For Select Clause'), + 'description' => ts('the tables to be included in a select data'), + 'where' => 'civicrm_group.select_tables', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'where_tables' => array( + 'serialize' => self::SERIALIZE_PHP, + ], + 'where_tables' => [ 'name' => 'where_tables', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Tables For Where Clause') , - 'description' => 'the tables to be included in the count statement', + 'title' => ts('Tables For Where Clause'), + 'description' => ts('the tables to be included in the count statement'), + 'where' => 'civicrm_group.where_tables', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'group_type' => array( + 'serialize' => self::SERIALIZE_PHP, + ], + 'group_type' => [ 'name' => 'group_type', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Type') , - 'description' => 'FK to group type', + 'title' => ts('Group Type'), + 'description' => ts('FK to group type'), 'maxlength' => 128, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_group.group_type', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - 'pseudoconstant' => array( + 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND, + 'pseudoconstant' => [ 'optionGroupName' => 'group_type', 'optionEditPath' => 'civicrm/admin/options/group_type', - ) - ) , - 'cache_date' => array( + ], + ], + 'cache_date' => [ 'name' => 'cache_date', 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Group Cache Date') , - 'description' => 'Date when we created the cache for a smart group', - 'required' => false, + 'title' => ts('Group Cache Date'), + 'description' => ts('Date when we created the cache for a smart group'), + 'required' => FALSE, + 'where' => 'civicrm_group.cache_date', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'refresh_date' => array( + ], + 'refresh_date' => [ 'name' => 'refresh_date', 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Next Group Refresh Time') , - 'description' => 'Date and time when we need to refresh the cache next.', - 'required' => false, + 'title' => ts('Next Group Refresh Time'), + 'description' => ts('Date and time when we need to refresh the cache next.'), + 'required' => FALSE, + 'where' => 'civicrm_group.refresh_date', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'parents' => array( + ], + 'parents' => [ 'name' => 'parents', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Group Parents') , - 'description' => 'IDs of the parent(s)', + 'title' => ts('Group Parents'), + 'description' => ts('IDs of the parent(s)'), + 'where' => 'civicrm_group.parents', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'children' => array( + 'serialize' => self::SERIALIZE_COMMA, + 'pseudoconstant' => [ + 'callback' => 'CRM_Core_PseudoConstant::allGroup', + ], + ], + 'children' => [ 'name' => 'children', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Group Children') , - 'description' => 'IDs of the child(ren)', + 'title' => ts('Group Children'), + 'description' => ts('IDs of the child(ren)'), + 'where' => 'civicrm_group.children', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'is_hidden' => array( + ], + 'is_hidden' => [ 'name' => 'is_hidden', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Group is Hidden') , - 'description' => 'Is this group hidden?', + 'title' => ts('Group is Hidden'), + 'description' => ts('Is this group hidden?'), + 'where' => 'civicrm_group.is_hidden', + 'default' => '0', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'is_reserved' => array( + ], + 'is_reserved' => [ 'name' => 'is_reserved', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Group is Reserved') , + 'title' => ts('Group is Reserved'), + 'where' => 'civicrm_group.is_reserved', + 'default' => '0', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, - ) , - 'created_id' => array( + ], + 'created_id' => [ 'name' => 'created_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Created By') , - 'description' => 'FK to contact table.', + 'title' => ts('Group Created By'), + 'description' => ts('FK to contact table.'), + 'where' => 'civicrm_group.created_id', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'modified_id' => array( + ], + 'modified_id' => [ 'name' => 'modified_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Modified By') , - 'description' => 'FK to contact table.', + 'title' => ts('Group Modified By'), + 'description' => ts('FK to contact table.'), + 'where' => 'civicrm_group.modified_id', 'table_name' => 'civicrm_group', 'entity' => 'Group', 'bao' => 'CRM_Contact_BAO_Group', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return CRM_Core_DAO::getLocaleTableName(self::$_tableName); } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -471,10 +506,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -482,42 +518,48 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'index_group_type' => array( + $indices = [ + 'index_group_type' => [ 'name' => 'index_group_type', - 'field' => array( + 'field' => [ 0 => 'group_type', - ) , - 'localizable' => false, + ], + 'localizable' => FALSE, 'sig' => 'civicrm_group::0::group_type', - ) , - 'UI_title' => array( + ], + 'UI_title' => [ 'name' => 'UI_title', - 'field' => array( + 'field' => [ 0 => 'title', - ) , - 'localizable' => true, - 'unique' => true, + ], + 'localizable' => TRUE, + 'unique' => TRUE, 'sig' => 'civicrm_group::1::title', - ) , - 'UI_name' => array( + ], + 'UI_name' => [ 'name' => 'UI_name', - 'field' => array( + 'field' => [ 0 => 'name', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_group::1::name', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/GroupContact.php b/CRM/Contact/DAO/GroupContact.php index 380588a7d343..aa20c459b680 100644 --- a/CRM/Contact/DAO/GroupContact.php +++ b/CRM/Contact/DAO/GroupContact.php @@ -1,239 +1,235 @@ __table = 'civicrm_group_contact'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'location_id', 'civicrm_loc_block', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'email_id', 'civicrm_email', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'location_id', 'civicrm_loc_block', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'email_id', 'civicrm_email', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Contact ID') , - 'description' => 'primary key', - 'required' => true, + 'title' => ts('Group Contact ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact.id', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, - ) , - 'group_id' => array( + ], + 'group_id' => [ 'name' => 'group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group ID') , - 'description' => 'FK to civicrm_group', - 'required' => true, + 'title' => ts('Group ID'), + 'description' => ts('FK to civicrm_group'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact.group_id', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_group', 'keyColumn' => 'id', 'labelColumn' => 'title', - ) - ) , - 'contact_id' => array( + ], + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'FK to civicrm_contact', - 'required' => true, + 'title' => ts('Contact ID'), + 'description' => ts('FK to civicrm_contact'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact.contact_id', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'status' => array( + ], + 'status' => [ 'name' => 'status', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Contact Status') , - 'description' => 'status of contact relative to membership in group', + 'title' => ts('Group Contact Status'), + 'description' => ts('status of contact relative to membership in group'), 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, + 'where' => 'civicrm_group_contact.status', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_Core_SelectValues::groupContactStatus', - ) - ) , - 'location_id' => array( + ], + ], + 'location_id' => [ 'name' => 'location_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Contact Location') , - 'description' => 'Optional location to associate with this membership', + 'title' => ts('Group Contact Location'), + 'description' => ts('Optional location to associate with this membership'), + 'where' => 'civicrm_group_contact.location_id', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, 'FKClassName' => 'CRM_Core_DAO_LocBlock', - ) , - 'email_id' => array( + ], + 'email_id' => [ 'name' => 'email_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Contact Email') , - 'description' => 'Optional email to associate with this membership', + 'title' => ts('Group Contact Email'), + 'description' => ts('Optional email to associate with this membership'), + 'where' => 'civicrm_group_contact.email_id', 'table_name' => 'civicrm_group_contact', 'entity' => 'GroupContact', 'bao' => 'CRM_Contact_BAO_GroupContact', 'localizable' => 0, 'FKClassName' => 'CRM_Core_DAO_Email', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -241,10 +237,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -252,26 +249,32 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'UI_contact_group' => array( + $indices = [ + 'UI_contact_group' => [ 'name' => 'UI_contact_group', - 'field' => array( + 'field' => [ 0 => 'contact_id', 1 => 'group_id', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_group_contact::1::contact_id::group_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/GroupContactCache.php b/CRM/Contact/DAO/GroupContactCache.php index d85be450bd62..8c8c09f29ede 100644 --- a/CRM/Contact/DAO/GroupContactCache.php +++ b/CRM/Contact/DAO/GroupContactCache.php @@ -1,179 +1,169 @@ __table = 'civicrm_group_contact_cache'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Contact Cache ID') , - 'description' => 'primary key', - 'required' => true, + 'title' => ts('Group Contact Cache ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact_cache.id', 'table_name' => 'civicrm_group_contact_cache', 'entity' => 'GroupContactCache', 'bao' => 'CRM_Contact_BAO_GroupContactCache', 'localizable' => 0, - ) , - 'group_id' => array( + ], + 'group_id' => [ 'name' => 'group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group') , - 'description' => 'FK to civicrm_group', - 'required' => true, + 'title' => ts('Group'), + 'description' => ts('FK to civicrm_group'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact_cache.group_id', 'table_name' => 'civicrm_group_contact_cache', 'entity' => 'GroupContactCache', 'bao' => 'CRM_Contact_BAO_GroupContactCache', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_group', 'keyColumn' => 'id', 'labelColumn' => 'title', - ) - ) , - 'contact_id' => array( + ], + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'FK to civicrm_contact', - 'required' => true, + 'title' => ts('Contact ID'), + 'description' => ts('FK to civicrm_contact'), + 'required' => TRUE, + 'where' => 'civicrm_group_contact_cache.contact_id', 'table_name' => 'civicrm_group_contact_cache', 'entity' => 'GroupContactCache', 'bao' => 'CRM_Contact_BAO_GroupContactCache', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -181,10 +171,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact_cache', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact_cache', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -192,26 +183,32 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact_cache', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact_cache', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'UI_contact_group' => array( + $indices = [ + 'UI_contact_group' => [ 'name' => 'UI_contact_group', - 'field' => array( + 'field' => [ 0 => 'contact_id', 1 => 'group_id', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_group_contact_cache::1::contact_id::group_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/GroupNesting.php b/CRM/Contact/DAO/GroupNesting.php index 255e80ac9963..71cae5d79f0b 100644 --- a/CRM/Contact/DAO/GroupNesting.php +++ b/CRM/Contact/DAO/GroupNesting.php @@ -1,171 +1,161 @@ __table = 'civicrm_group_nesting'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'child_group_id', 'civicrm_group', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'child_group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_group_id', 'civicrm_group', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Nesting ID') , - 'description' => 'Relationship ID', - 'required' => true, + 'title' => ts('Group Nesting ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'where' => 'civicrm_group_nesting.id', 'table_name' => 'civicrm_group_nesting', 'entity' => 'GroupNesting', 'bao' => 'CRM_Contact_BAO_GroupNesting', 'localizable' => 0, - ) , - 'child_group_id' => array( + ], + 'child_group_id' => [ 'name' => 'child_group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Child Group') , - 'description' => 'ID of the child group', - 'required' => true, + 'title' => ts('Child Group'), + 'description' => ts('ID of the child group'), + 'required' => TRUE, + 'where' => 'civicrm_group_nesting.child_group_id', 'table_name' => 'civicrm_group_nesting', 'entity' => 'GroupNesting', 'bao' => 'CRM_Contact_BAO_GroupNesting', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - ) , - 'parent_group_id' => array( + ], + 'parent_group_id' => [ 'name' => 'parent_group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Parent Group') , - 'description' => 'ID of the parent group', - 'required' => true, + 'title' => ts('Parent Group'), + 'description' => ts('ID of the parent group'), + 'required' => TRUE, + 'where' => 'civicrm_group_nesting.parent_group_id', 'table_name' => 'civicrm_group_nesting', 'entity' => 'GroupNesting', 'bao' => 'CRM_Contact_BAO_GroupNesting', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -173,10 +163,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_nesting', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_nesting', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -184,15 +175,21 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_nesting', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_nesting', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array(); + $indices = []; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/GroupOrganization.php b/CRM/Contact/DAO/GroupOrganization.php index 718a2bfda29c..a6491b4f9f34 100644 --- a/CRM/Contact/DAO/GroupOrganization.php +++ b/CRM/Contact/DAO/GroupOrganization.php @@ -1,179 +1,169 @@ __table = 'civicrm_group_organization'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'organization_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'organization_id', 'civicrm_contact', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Organization ID') , - 'description' => 'Relationship ID', - 'required' => true, + 'title' => ts('Group Organization ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'where' => 'civicrm_group_organization.id', 'table_name' => 'civicrm_group_organization', 'entity' => 'GroupOrganization', 'bao' => 'CRM_Contact_BAO_GroupOrganization', 'localizable' => 0, - ) , - 'group_id' => array( + ], + 'group_id' => [ 'name' => 'group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group') , - 'description' => 'ID of the group', - 'required' => true, + 'title' => ts('Group'), + 'description' => ts('ID of the group'), + 'required' => TRUE, + 'where' => 'civicrm_group_organization.group_id', 'table_name' => 'civicrm_group_organization', 'entity' => 'GroupOrganization', 'bao' => 'CRM_Contact_BAO_GroupOrganization', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_group', 'keyColumn' => 'id', 'labelColumn' => 'title', - ) - ) , - 'organization_id' => array( + ], + ], + 'organization_id' => [ 'name' => 'organization_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Organization') , - 'description' => 'ID of the Organization Contact', - 'required' => true, + 'title' => ts('Organization'), + 'description' => ts('ID of the Organization Contact'), + 'required' => TRUE, + 'where' => 'civicrm_group_organization.organization_id', 'table_name' => 'civicrm_group_organization', 'entity' => 'GroupOrganization', 'bao' => 'CRM_Contact_BAO_GroupOrganization', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -181,10 +171,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_organization', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_organization', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -192,26 +183,32 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_organization', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_organization', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'UI_group_organization' => array( + $indices = [ + 'UI_group_organization' => [ 'name' => 'UI_group_organization', - 'field' => array( + 'field' => [ 0 => 'group_id', 1 => 'organization_id', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_group_organization::1::group_id::organization_id', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/Relationship.php b/CRM/Contact/DAO/Relationship.php index 5953567a02b1..2849aead67fa 100644 --- a/CRM/Contact/DAO/Relationship.php +++ b/CRM/Contact/DAO/Relationship.php @@ -1,338 +1,350 @@ __table = 'civicrm_relationship'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id_a', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id_b', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'relationship_type_id', 'civicrm_relationship_type', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'case_id', 'civicrm_case', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id_a', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id_b', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'relationship_type_id', 'civicrm_relationship_type', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'case_id', 'civicrm_case', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Relationship ID') , - 'description' => 'Relationship ID', - 'required' => true, + 'title' => ts('Relationship ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.id', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - ) , - 'contact_id_a' => array( + ], + 'contact_id_a' => [ 'name' => 'contact_id_a', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact A') , - 'description' => 'id of the first contact', - 'required' => true, + 'title' => ts('Contact A'), + 'description' => ts('id of the first contact'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.contact_id_a', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'contact_id_b' => array( + ], + 'contact_id_b' => [ 'name' => 'contact_id_b', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact B') , - 'description' => 'id of the second contact', - 'required' => true, + 'title' => ts('Contact B'), + 'description' => ts('id of the second contact'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.contact_id_b', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - 'html' => array( + 'html' => [ 'type' => 'EntityRef', - ) , - ) , - 'relationship_type_id' => array( + ], + ], + 'relationship_type_id' => [ 'name' => 'relationship_type_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Relationship Type') , - 'description' => 'id of the relationship', - 'required' => true, + 'title' => ts('Relationship Type'), + 'description' => ts('id of the relationship'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.relationship_type_id', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_RelationshipType', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - ) , - 'start_date' => array( + ], + ], + 'start_date' => [ 'name' => 'start_date', 'type' => CRM_Utils_Type::T_DATE, - 'title' => ts('Relationship Start Date') , - 'description' => 'date when the relationship started', + 'title' => ts('Relationship Start Date'), + 'description' => ts('date when the relationship started'), + 'where' => 'civicrm_relationship.start_date', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select Date', - ) , - ) , - 'end_date' => array( + 'formatType' => 'activityDate', + ], + ], + 'end_date' => [ 'name' => 'end_date', 'type' => CRM_Utils_Type::T_DATE, - 'title' => ts('Relationship End Date') , - 'description' => 'date when the relationship ended', + 'title' => ts('Relationship End Date'), + 'description' => ts('date when the relationship ended'), + 'where' => 'civicrm_relationship.end_date', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select Date', - ) , - ) , - 'is_active' => array( + 'formatType' => 'activityDate', + ], + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Relationship Is Active') , - 'description' => 'is the relationship active ?', + 'title' => ts('Relationship Is Active'), + 'description' => ts('is the relationship active ?'), + 'where' => 'civicrm_relationship.is_active', 'default' => '1', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'CheckBox', - ) , - ) , - 'description' => array( + ], + ], + 'description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Description') , - 'description' => 'Optional verbose description for the relationship.', + 'title' => ts('Relationship Description'), + 'description' => ts('Optional verbose description for the relationship.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_relationship.description', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Text', - ) , - ) , - 'is_permission_a_b' => array( + ], + ], + 'is_permission_a_b' => [ 'name' => 'is_permission_a_b', - 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Contact A has Permission Over Contact B') , - 'description' => 'is contact a has permission to view / edit contact and - related data for contact b ? - ', + 'type' => CRM_Utils_Type::T_INT, + 'title' => ts('Contact A has Permission Over Contact B'), + 'description' => ts('Permission that Contact A has to view/update Contact B'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.is_permission_a_b', + 'default' => '0', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( - 'type' => 'CheckBox', - ) , - ) , - 'is_permission_b_a' => array( + 'html' => [ + 'type' => 'Radio', + ], + 'pseudoconstant' => [ + 'callback' => 'CRM_Core_SelectValues::getPermissionedRelationshipOptions', + ], + ], + 'is_permission_b_a' => [ 'name' => 'is_permission_b_a', - 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Contact B has Permission Over Contact A') , - 'description' => 'is contact b has permission to view / edit contact and - related data for contact a ? - ', + 'type' => CRM_Utils_Type::T_INT, + 'title' => ts('Contact B has Permission Over Contact A'), + 'description' => ts('Permission that Contact B has to view/update Contact A'), + 'required' => TRUE, + 'where' => 'civicrm_relationship.is_permission_b_a', + 'default' => '0', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, - 'html' => array( - 'type' => 'CheckBox', - ) , - ) , - 'case_id' => array( + 'html' => [ + 'type' => 'Radio', + ], + 'pseudoconstant' => [ + 'callback' => 'CRM_Core_SelectValues::getPermissionedRelationshipOptions', + ], + ], + 'case_id' => [ 'name' => 'case_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Relationship Case') , - 'description' => 'FK to civicrm_case', + 'title' => ts('Relationship Case'), + 'description' => ts('FK to civicrm_case'), + 'where' => 'civicrm_relationship.case_id', 'default' => 'NULL', 'table_name' => 'civicrm_relationship', 'entity' => 'Relationship', 'bao' => 'CRM_Contact_BAO_Relationship', 'localizable' => 0, 'FKClassName' => 'CRM_Case_DAO_Case', - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -340,10 +352,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -351,15 +364,21 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array(); + $indices = []; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/RelationshipType.php b/CRM/Contact/DAO/RelationshipType.php index 16e0125fe122..a4509a7b8bbb 100644 --- a/CRM/Contact/DAO/RelationshipType.php +++ b/CRM/Contact/DAO/RelationshipType.php @@ -1,354 +1,373 @@ __table = 'civicrm_relationship_type'; parent::__construct(); } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Relationship Type ID') , - 'description' => 'Primary key', - 'required' => true, + 'title' => ts('Relationship Type ID'), + 'description' => ts('Primary key'), + 'required' => TRUE, + 'where' => 'civicrm_relationship_type.id', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - ) , - 'name_a_b' => array( + ], + 'name_a_b' => [ 'name' => 'name_a_b', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Type Name A to B') , - 'description' => 'name for relationship of contact_a to contact_b.', + 'title' => ts('Relationship Type Name A to B'), + 'description' => ts('name for relationship of contact_a to contact_b.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.name_a_b', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - ) , - 'label_a_b' => array( + ], + 'label_a_b' => [ 'name' => 'label_a_b', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Type Label A to B') , - 'description' => 'label for relationship of contact_a to contact_b.', + 'title' => ts('Relationship Type Label A to B'), + 'description' => ts('label for relationship of contact_a to contact_b.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.label_a_b', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 1, - ) , - 'name_b_a' => array( + 'html' => [ + 'type' => 'Text', + ], + ], + 'name_b_a' => [ 'name' => 'name_b_a', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Type Name B to A') , - 'description' => 'Optional name for relationship of contact_b to contact_a.', + 'title' => ts('Relationship Type Name B to A'), + 'description' => ts('Optional name for relationship of contact_b to contact_a.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.name_b_a', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - ) , - 'label_b_a' => array( + ], + 'label_b_a' => [ 'name' => 'label_b_a', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Type Label B to A') , - 'description' => 'Optional label for relationship of contact_b to contact_a.', + 'title' => ts('Relationship Type Label B to A'), + 'description' => ts('Optional label for relationship of contact_b to contact_a.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.label_b_a', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 1, - ) , - 'description' => array( + 'html' => [ + 'type' => 'Text', + ], + ], + 'description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Relationship Description') , - 'description' => 'Optional verbose description of the relationship type.', + 'title' => ts('Relationship Description'), + 'description' => ts('Optional verbose description of the relationship type.'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_relationship_type.description', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 1, - ) , - 'contact_type_a' => array( + 'html' => [ + 'type' => 'Text', + ], + ], + 'contact_type_a' => [ 'name' => 'contact_type_a', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Type for Contact A') , - 'description' => 'If defined, contact_a in a relationship of this type must be a specific contact_type.', + 'title' => ts('Contact Type for Contact A'), + 'description' => ts('If defined, contact_a in a relationship of this type must be a specific contact_type.'), 'maxlength' => 12, 'size' => CRM_Utils_Type::TWELVE, + 'where' => 'civicrm_relationship_type.contact_type_a', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NULL', - ) - ) , - 'contact_type_b' => array( + ], + ], + 'contact_type_b' => [ 'name' => 'contact_type_b', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Type for Contact B') , - 'description' => 'If defined, contact_b in a relationship of this type must be a specific contact_type.', + 'title' => ts('Contact Type for Contact B'), + 'description' => ts('If defined, contact_b in a relationship of this type must be a specific contact_type.'), 'maxlength' => 12, 'size' => CRM_Utils_Type::TWELVE, + 'where' => 'civicrm_relationship_type.contact_type_b', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NULL', - ) - ) , - 'contact_sub_type_a' => array( + ], + ], + 'contact_sub_type_a' => [ 'name' => 'contact_sub_type_a', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Subtype A') , - 'description' => 'If defined, contact_sub_type_a in a relationship of this type must be a specific contact_sub_type. - ', + 'title' => ts('Contact Subtype A'), + 'description' => ts('If defined, contact_sub_type_a in a relationship of this type must be a specific contact_sub_type.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.contact_sub_type_a', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NOT NULL', - ) - ) , - 'contact_sub_type_b' => array( + ], + ], + 'contact_sub_type_b' => [ 'name' => 'contact_sub_type_b', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Contact Subtype B') , - 'description' => 'If defined, contact_sub_type_b in a relationship of this type must be a specific contact_sub_type. - ', + 'title' => ts('Contact Subtype B'), + 'description' => ts('If defined, contact_sub_type_b in a relationship of this type must be a specific contact_sub_type.'), 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, + 'where' => 'civicrm_relationship_type.contact_sub_type_b', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_contact_type', 'keyColumn' => 'name', 'labelColumn' => 'label', 'condition' => 'parent_id IS NOT NULL', - ) - ) , - 'is_reserved' => array( + ], + ], + 'is_reserved' => [ 'name' => 'is_reserved', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Relationship Type is Reserved') , - 'description' => 'Is this relationship type a predefined system type (can not be changed or de-activated)?', + 'title' => ts('Relationship Type is Reserved'), + 'description' => ts('Is this relationship type a predefined system type (can not be changed or de-activated)?'), + 'where' => 'civicrm_relationship_type.is_reserved', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - ) , - 'is_active' => array( + 'html' => [ + 'type' => 'CheckBox', + ], + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Relationship Type is Active') , - 'description' => 'Is this relationship type currently active (i.e. can be used when creating or editing relationships)? - ', + 'title' => ts('Relationship Type is Active'), + 'description' => ts('Is this relationship type currently active (i.e. can be used when creating or editing relationships)?'), + 'where' => 'civicrm_relationship_type.is_active', 'default' => '1', 'table_name' => 'civicrm_relationship_type', 'entity' => 'RelationshipType', 'bao' => 'CRM_Contact_BAO_RelationshipType', 'localizable' => 0, - ) , - ); + 'html' => [ + 'type' => 'CheckBox', + ], + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return CRM_Core_DAO::getLocaleTableName(self::$_tableName); } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -356,10 +375,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship_type', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship_type', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -367,34 +387,40 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship_type', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship_type', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array( - 'UI_name_a_b' => array( + $indices = [ + 'UI_name_a_b' => [ 'name' => 'UI_name_a_b', - 'field' => array( + 'field' => [ 0 => 'name_a_b', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_relationship_type::1::name_a_b', - ) , - 'UI_name_b_a' => array( + ], + 'UI_name_b_a' => [ 'name' => 'UI_name_b_a', - 'field' => array( + 'field' => [ 0 => 'name_b_a', - ) , - 'localizable' => false, - 'unique' => true, + ], + 'localizable' => FALSE, + 'unique' => TRUE, 'sig' => 'civicrm_relationship_type::1::name_b_a', - ) , - ); + ], + ]; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/SavedSearch.php b/CRM/Contact/DAO/SavedSearch.php index f6d87c8da145..cd29f674953b 100644 --- a/CRM/Contact/DAO/SavedSearch.php +++ b/CRM/Contact/DAO/SavedSearch.php @@ -1,236 +1,234 @@ __table = 'civicrm_saved_search'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mapping_id', 'civicrm_mapping', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mapping_id', 'civicrm_mapping', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Saved Search ID') , - 'description' => 'Saved Search ID', - 'required' => true, + 'title' => ts('Saved Search ID'), + 'description' => ts('Saved Search ID'), + 'required' => TRUE, + 'where' => 'civicrm_saved_search.id', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - 'form_values' => array( + ], + 'form_values' => [ 'name' => 'form_values', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Submitted Form Values') , - 'description' => 'Submitted form values for this search', - 'import' => true, + 'title' => ts('Submitted Form Values'), + 'description' => ts('Submitted form values for this search'), + 'import' => TRUE, 'where' => 'civicrm_saved_search.form_values', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - 'mapping_id' => array( + 'serialize' => self::SERIALIZE_PHP, + ], + 'mapping_id' => [ 'name' => 'mapping_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Mapping ID') , - 'description' => 'Foreign key to civicrm_mapping used for saved search-builder searches.', + 'title' => ts('Mapping ID'), + 'description' => ts('Foreign key to civicrm_mapping used for saved search-builder searches.'), + 'where' => 'civicrm_saved_search.mapping_id', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, 'FKClassName' => 'CRM_Core_DAO_Mapping', - ) , - 'search_custom_id' => array( + ], + 'search_custom_id' => [ 'name' => 'search_custom_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Option Value ID') , - 'description' => 'Foreign key to civicrm_option value table used for saved custom searches.', + 'title' => ts('Option Value ID'), + 'description' => ts('Foreign key to civicrm_option value table used for saved custom searches.'), + 'where' => 'civicrm_saved_search.search_custom_id', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - 'where_clause' => array( + ], + 'where_clause' => [ 'name' => 'where_clause', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Where Clause') , - 'description' => 'the sql where clause if a saved search acl', + 'title' => ts('Where Clause'), + 'description' => ts('the sql where clause if a saved search acl'), + 'where' => 'civicrm_saved_search.where_clause', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - 'select_tables' => array( + ], + 'select_tables' => [ 'name' => 'select_tables', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Select Tables') , - 'description' => 'the tables to be included in a select data', + 'title' => ts('Select Tables'), + 'description' => ts('the tables to be included in a select data'), + 'where' => 'civicrm_saved_search.select_tables', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - 'where_tables' => array( + 'serialize' => self::SERIALIZE_PHP, + ], + 'where_tables' => [ 'name' => 'where_tables', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Where Tables') , - 'description' => 'the tables to be included in the count statement', + 'title' => ts('Where Tables'), + 'description' => ts('the tables to be included in the count statement'), + 'where' => 'civicrm_saved_search.where_tables', 'table_name' => 'civicrm_saved_search', 'entity' => 'SavedSearch', 'bao' => 'CRM_Contact_BAO_SavedSearch', 'localizable' => 0, - ) , - ); + 'serialize' => self::SERIALIZE_PHP, + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -238,10 +236,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'saved_search', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'saved_search', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -249,15 +248,21 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'saved_search', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'saved_search', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array(); + $indices = []; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/DAO/SubscriptionHistory.php b/CRM/Contact/DAO/SubscriptionHistory.php index a29c982fb9c2..805e02ca3a38 100644 --- a/CRM/Contact/DAO/SubscriptionHistory.php +++ b/CRM/Contact/DAO/SubscriptionHistory.php @@ -1,258 +1,257 @@ __table = 'civicrm_subscription_history'; parent::__construct(); } + /** * Returns foreign keys and entity references. * * @return array * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() { + public static function getReferenceColumns() { if (!isset(Civi::$statics[__CLASS__]['links'])) { - Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id'); - Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id'); + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id'); CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } return Civi::$statics[__CLASS__]['links']; } + /** * Returns all the column names of this table * * @return array */ - static function &fields() { + public static function &fields() { if (!isset(Civi::$statics[__CLASS__]['fields'])) { - Civi::$statics[__CLASS__]['fields'] = array( - 'id' => array( + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group Membership History ID') , - 'description' => 'Internal Id', - 'required' => true, + 'title' => ts('Group Membership History ID'), + 'description' => ts('Internal Id'), + 'required' => TRUE, + 'where' => 'civicrm_subscription_history.id', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, - ) , - 'contact_id' => array( + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Contact ID') , - 'description' => 'Contact Id', - 'required' => true, + 'title' => ts('Contact ID'), + 'description' => ts('Contact Id'), + 'required' => TRUE, + 'where' => 'civicrm_subscription_history.contact_id', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'group_id' => array( + ], + 'group_id' => [ 'name' => 'group_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Group') , - 'description' => 'Group Id', + 'title' => ts('Group'), + 'description' => ts('Group Id'), + 'where' => 'civicrm_subscription_history.group_id', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, 'FKClassName' => 'CRM_Contact_DAO_Group', - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'table' => 'civicrm_group', 'keyColumn' => 'id', 'labelColumn' => 'title', - ) - ) , - 'date' => array( + ], + ], + 'date' => [ 'name' => 'date', - 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => ts('Group Membership Action Date') , - 'description' => 'Date of the (un)subscription', - 'required' => true, + 'type' => CRM_Utils_Type::T_TIMESTAMP, + 'title' => ts('Group Membership Action Date'), + 'description' => ts('Date of the (un)subscription'), + 'required' => TRUE, + 'where' => 'civicrm_subscription_history.date', + 'default' => 'CURRENT_TIMESTAMP', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, - ) , - 'method' => array( + ], + 'method' => [ 'name' => 'method', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Membership Action') , - 'description' => 'How the (un)subscription was triggered', + 'title' => ts('Group Membership Action'), + 'description' => ts('How the (un)subscription was triggered'), 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, + 'where' => 'civicrm_subscription_history.method', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, - 'html' => array( + 'html' => [ 'type' => 'Select', - ) , - 'pseudoconstant' => array( + ], + 'pseudoconstant' => [ 'callback' => 'CRM_Core_SelectValues::getSubscriptionHistoryMethods', - ) - ) , - 'status' => array( + ], + ], + 'status' => [ 'name' => 'status', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Membership Status') , - 'description' => 'The state of the contact within the group', + 'title' => ts('Group Membership Status'), + 'description' => ts('The state of the contact within the group'), 'maxlength' => 8, 'size' => CRM_Utils_Type::EIGHT, + 'where' => 'civicrm_subscription_history.status', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, - 'pseudoconstant' => array( + 'pseudoconstant' => [ 'callback' => 'CRM_Core_SelectValues::groupContactStatus', - ) - ) , - 'tracking' => array( + ], + ], + 'tracking' => [ 'name' => 'tracking', 'type' => CRM_Utils_Type::T_STRING, - 'title' => ts('Group Membership Tracking') , - 'description' => 'IP address or other tracking info', + 'title' => ts('Group Membership Tracking'), + 'description' => ts('IP address or other tracking info'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, + 'where' => 'civicrm_subscription_history.tracking', 'table_name' => 'civicrm_subscription_history', 'entity' => 'SubscriptionHistory', 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', 'localizable' => 0, - ) , - ); + ], + ]; CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } return Civi::$statics[__CLASS__]['fields']; } + /** * Return a mapping from field-name to the corresponding key (as used in fields()). * * @return array * Array(string $name => string $uniqueName). */ - static function &fieldKeys() { + public static function &fieldKeys() { if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } return Civi::$statics[__CLASS__]['fieldKeys']; } + /** * Returns the names of this table * * @return string */ - static function getTableName() { + public static function getTableName() { return self::$_tableName; } + /** * Returns if this table needs to be logged * - * @return boolean + * @return bool */ - function getLog() { + public function getLog() { return self::$_log; } + /** * Returns the list of fields that can be imported * @@ -260,10 +259,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'subscription_history', $prefix, array()); + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'subscription_history', $prefix, []); return $r; } + /** * Returns the list of fields that can be exported * @@ -271,15 +271,21 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'subscription_history', $prefix, array()); + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'subscription_history', $prefix, []); return $r; } + /** * Returns the list of indices + * + * @param bool $localize + * + * @return array */ public static function indices($localize = TRUE) { - $indices = array(); + $indices = []; return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Contact/Form/Contact.php b/CRM/Contact/Form/Contact.php index 0a1c077b62c1..11bef4a62927 100644 --- a/CRM/Contact/Form/Contact.php +++ b/CRM/Contact/Form/Contact.php @@ -1,9 +1,9 @@ _contactType, - array('Individual', 'Household', 'Organization') + ['Individual', 'Household', 'Organization'] ) ) { CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type')); @@ -177,7 +180,7 @@ public function preProcess() { $this->_contactSubType && !(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE)) ) { - CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType))); + CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType])); } $this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer', @@ -193,7 +196,7 @@ public function preProcess() { ); $typeLabel = implode(' / ', $typeLabel); - CRM_Utils_System::setTitle(ts('New %1', array(1 => $typeLabel))); + CRM_Utils_System::setTitle(ts('New %1', [1 => $typeLabel])); $session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1')); $this->_contactId = NULL; } @@ -204,13 +207,13 @@ public function preProcess() { } if ($this->_contactId) { - $defaults = array(); - $params = array('id' => $this->_contactId); - $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'); + $defaults = []; + $params = ['id' => $this->_contactId]; + $returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased']; CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities); if (empty($defaults['id'])) { - CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId))); + CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId])); } $this->_contactType = CRM_Utils_Array::value('contact_type', $defaults); @@ -224,9 +227,9 @@ public function preProcess() { $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId); if ($defaults['is_deceased']) { - $displayName .= ' (deceased)'; + $displayName .= ' (' . ts('deceased') . ')'; } - $displayName = ts('Edit %1', array(1 => $displayName)); + $displayName = ts('Edit %1', [1 => $displayName]); // Check if this is default domain contact CRM-10482 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) { @@ -235,7 +238,7 @@ public function preProcess() { // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container CRM_Utils_System::setTitle($displayName); - $context = CRM_Utils_Request::retrieve('context', 'String', $this); + $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this); $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this); $urlParams = 'reset=1&cid=' . $this->_contactId; @@ -256,13 +259,13 @@ public function preProcess() { $this->_values = $values; } else { - $params = array( + $params = [ 'id' => $this->_contactId, 'contact_id' => $this->_contactId, 'noRelationships' => TRUE, 'noNotes' => TRUE, 'noGroups' => TRUE, - ); + ]; $contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE); $this->set('values', $this->_values); @@ -430,7 +433,7 @@ public function setDefaultValues() { } // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups ) foreach ($this->_editOptions as $name => $label) { - if (!in_array($name, array('Address', 'Notes'))) { + if (!in_array($name, ['Address', 'Notes'])) { $className = 'CRM_Contact_Form_Edit_' . $name; $className::setDefaultValues($this, $defaults); } @@ -561,19 +564,19 @@ public function addRules() { return; } - $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'), $this->_contactId); + $this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'], $this->_contactId); // Call Locking check if editing existing contact if ($this->_contactId) { - $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId); + $this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId); } if (array_key_exists('Address', $this->_editOptions)) { - $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this); + $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this); } if (array_key_exists('CommunicationPreferences', $this->_editOptions)) { - $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this); + $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this); } } @@ -586,11 +589,12 @@ public function addRules() { * List of errors to be posted back to the form. * @param int $contactId * Contact id if doing update. + * @param string $contactType * * @return bool * email/openId */ - public static function formRule($fields, &$errors, $contactId = NULL) { + public static function formRule($fields, &$errors, $contactId, $contactType) { $config = CRM_Core_Config::singleton(); // validations. @@ -615,10 +619,11 @@ public static function formRule($fields, &$errors, $contactId = NULL) { $blocks['Address'] = $otherEditOptions['Address']; } - $openIds = array(); + $website_types = []; + $openIds = []; $primaryID = FALSE; foreach ($blocks as $name => $label) { - $hasData = $hasPrimary = array(); + $hasData = $hasPrimary = []; $name = strtolower($name); if (!empty($fields[$name]) && is_array($fields[$name])) { foreach ($fields[$name] as $instance => $blockValues) { @@ -629,8 +634,17 @@ public static function formRule($fields, &$errors, $contactId = NULL) { } if ($dataExists) { - // skip remaining checks for website if ($name == 'website') { + if (!empty($blockValues['website_type_id'])) { + if (empty($website_types[$blockValues['website_type_id']])) { + $website_types[$blockValues['website_type_id']] = $blockValues['website_type_id']; + } + else { + $errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.'); + } + } + + // skip remaining checks for website continue; } @@ -638,17 +652,17 @@ public static function formRule($fields, &$errors, $contactId = NULL) { if (!empty($blockValues['is_primary'])) { $hasPrimary[] = $instance; if (!$primaryID && - in_array($name, array( + in_array($name, [ 'email', 'openid', - )) && !empty($blockValues[$name]) + ]) && !empty($blockValues[$name]) ) { $primaryID = $blockValues[$name]; } } if (empty($blockValues['location_type_id'])) { - $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label)); + $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]); } } @@ -657,18 +671,18 @@ public static function formRule($fields, &$errors, $contactId = NULL) { $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues); $cid = isset($contactId) ? $contactId : 0; if ($oid->find(TRUE) && ($oid->contact_id != $cid)) { - $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID'])); + $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]); } } } if (empty($hasPrimary) && !empty($hasData)) { - $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label)); + $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]); } if (count($hasPrimary) > 1) { $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.', - array(1 => $label) + [1 => $label] ); } } @@ -678,7 +692,7 @@ public static function formRule($fields, &$errors, $contactId = NULL) { if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) { foreach ($openIds as $instance => $value) { if (!array_key_exists($instance, array_unique($openIds))) { - $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID'])); + $errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]); } } } @@ -693,7 +707,7 @@ public static function formRule($fields, &$errors, $contactId = NULL) { if (isset($fields['address']) && is_array($fields['address']) ) { - $invalidStreetNumbers = array(); + $invalidStreetNumbers = []; foreach ($fields['address'] as $cnt => $address) { if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) { $parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']); @@ -708,11 +722,16 @@ public static function formRule($fields, &$errors, $contactId = NULL) { foreach ($invalidStreetNumbers as & $num) { $num = CRM_Contact_Form_Contact::ordinalNumber($num); } - $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', array(1 => implode(', ', $invalidStreetNumbers))); + $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', [1 => implode(', ', $invalidStreetNumbers)]); } } } + // Check for duplicate contact if it wasn't already handled by ajax or disabled + if (!Civi::settings()->get('contact_ajax_check_similar') || !empty($fields['_qf_Contact_refresh_dedupe'])) { + self::checkDuplicateContacts($fields, $errors, $contactId, $contactType); + } + return $primaryID; } @@ -728,19 +747,19 @@ public function buildQuickForm() { if ($this->_action == CRM_Core_Action::UPDATE) { $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.')); - $deleteURL = array( - CRM_Core_Action::DELETE => array( + $deleteURL = [ + CRM_Core_Action::DELETE => [ 'name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&cid=%%id%%&action=delete', 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"', - ), - ); + ], + ]; $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, - array( + [ 'id' => $this->_contactId, - ), + ], ts('more'), FALSE, 'contact.image.delete', @@ -754,6 +773,14 @@ public function buildQuickForm() { $className = 'CRM_Contact_Form_Edit_' . $this->_contactType; $className::buildQuickForm($this); + // Ajax duplicate checking + $checkSimilar = Civi::settings()->get('contact_ajax_check_similar'); + $this->assign('checkSimilar', $checkSimilar); + if ($checkSimilar == 1) { + $ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType]; + $this->assign('ruleFields', CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams)); + } + // build Custom data if Custom data present in edit option $buildCustomData = 'noCustomDataPresent'; if (array_key_exists('CustomData', $this->_editOptions)) { @@ -761,15 +788,15 @@ public function buildQuickForm() { } // subtype is a common field. lets keep it here - $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType)); + $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType]); if (!empty($subtypes)) { - $this->addField('contact_sub_type', array( + $this->addField('contact_sub_type', [ 'label' => ts('Contact Type'), 'options' => $subtypes, 'class' => $buildCustomData, 'multiple' => 'multiple', 'option_url' => NULL, - )); + ]); } // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups ) @@ -794,7 +821,7 @@ public function buildQuickForm() { CRM_Contact_Form_Location::buildQuickForm($this); // add attachment - $this->addField('image_URL', array('maxlength' => '255', 'label' => ts('Browse/Upload Image'))); + $this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]); // add the dedupe button $this->addElement('submit', @@ -810,26 +837,26 @@ public function buildQuickForm() { ts('Save With Duplicate Household') ); - $buttons = array( - array( + $buttons = [ + [ 'type' => 'upload', 'name' => ts('Save'), 'subName' => 'view', 'isDefault' => TRUE, - ), - ); + ], + ]; if (CRM_Core_Permission::check('add contacts')) { - $buttons[] = array( + $buttons[] = [ 'type' => 'upload', 'name' => ts('Save and New'), 'spacing' => ' ', 'subName' => 'new', - ); + ]; } - $buttons[] = array( + $buttons[] = [ 'type' => 'cancel', 'name' => ts('Cancel'), - ); + ]; if (!empty($this->_values['contact_sub_type'])) { $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, @@ -853,6 +880,10 @@ public function postProcess() { //get the submitted values in an array $params = $this->controller->exportValues($this->_name); + if (!isset($params['preferred_communication_method'])) { + // If this field is empty QF will trim it so we have to add it in. + $params['preferred_communication_method'] = 'null'; + } $group = CRM_Utils_Array::value('group', $params); if (!empty($group) && is_array($group)) { @@ -862,8 +893,6 @@ public function postProcess() { } } - CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues); - if (!empty($params['image_URL'])) { CRM_Contact_BAO_Contact::processImageParams($params); } @@ -881,7 +910,7 @@ public function postProcess() { $params['contact_type'] = $this->_contactType; if (empty($params['contact_sub_type']) && $this->_isContactSubType) { - $params['contact_sub_type'] = array($this->_contactSubType); + $params['contact_sub_type'] = [$this->_contactSubType]; } if ($this->_contactId) { @@ -896,11 +925,11 @@ public function postProcess() { if (isset($params['contact_id'])) { // process membership status for deceased contact - $deceasedParams = array( + $deceasedParams = [ 'contact_id' => CRM_Utils_Array::value('contact_id', $params), 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE), 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL), - ); + ]; $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams); } @@ -912,8 +941,6 @@ public function postProcess() { CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params); } - $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE); - //CRM-5143 //if subtype is set, send subtype as extend to validate subtype customfield $customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type']; @@ -939,11 +966,10 @@ public function postProcess() { // process shared contact address. CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']); - if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) { + if (!array_key_exists('TagsAndGroups', $this->_editOptions)) { unset($params['group']); } - - if (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE) && !empty($params['group'])) { + elseif (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE)) { // figure out which all groups are intended to be removed $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added'); if (is_array($contactGroupList)) { @@ -962,7 +988,7 @@ public function postProcess() { $parseStatusMsg = self::parseAddressStatusMsg($parseResult); } - $blocks = array('email', 'phone', 'im', 'openid', 'address', 'website'); + $blocks = ['email', 'phone', 'im', 'openid', 'address', 'website']; foreach ($blocks as $block) { if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) { foreach ($this->_preEditValues[$block] as $count => $value) { @@ -981,10 +1007,10 @@ public function postProcess() { // status message if ($this->_contactId) { - $message = ts('%1 has been updated.', array(1 => $contact->display_name)); + $message = ts('%1 has been updated.', [1 => $contact->display_name]); } else { - $message = ts('%1 has been created.', array(1 => $contact->display_name)); + $message = ts('%1 has been created.', [1 => $contact->display_name]); } // set the contact ID @@ -992,8 +1018,10 @@ public function postProcess() { if (array_key_exists('TagsAndGroups', $this->_editOptions)) { //add contact to tags - CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']); - + if (isset($params['tag'])) { + $params['tag'] = array_flip(explode(',', $params['tag'])); + CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']); + } //save free tags if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) { CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this); @@ -1011,7 +1039,7 @@ public function postProcess() { $session->setStatus($message, ts('Contact Saved'), 'success'); // add the recently viewed contact - $recentOther = array(); + $recentOther = []; if (($session->get('userID') == $contact->id) || CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT) ) { @@ -1040,7 +1068,7 @@ public function postProcess() { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr)); } else { - $context = CRM_Utils_Request::retrieve('context', 'String', $this); + $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this); $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this); //validate the qfKey $urlParams = 'reset=1&cid=' . $contact->id; @@ -1077,7 +1105,7 @@ public static function blockDataExists(&$fields) { return FALSE; } - static $skipFields = array( + static $skipFields = [ 'location_type_id', 'is_primary', 'phone_type_id', @@ -1085,7 +1113,7 @@ public static function blockDataExists(&$fields) { 'country_id', 'website_type_id', 'master_id', - ); + ]; foreach ($fields as $name => $value) { $skipField = FALSE; foreach ($skipFields as $skip) { @@ -1130,27 +1158,27 @@ public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $c // if this is a forced save, ignore find duplicate rule if (empty($fields['_qf_Contact_upload_duplicate'])) { - $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', array($contactID)); + $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', [$contactID]); if ($ids) { $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID); $duplicateContactsLinks = '"; - print "$sql;"; - print ""; - } - CRM_Core_DAO::executeQuery($sql); + $datesTable->createWithColumns('id int primary key, date_added date'); - $startDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['start_date'])); + $startDate = !empty($this->_formValues['start_date']) ? $this->_formValues['start_date'] : date('Y-m-d'); $endDateFix = NULL; if (!empty($this->_formValues['end_date'])) { - $endDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['end_date'])); - # tack 11:59pm on to make search inclusive of the end date - $endDateFix = "AND date_added <= '" . substr($endDate, 0, 10) . " 23:59:00'"; + // tack 11:59pm on to make search inclusive of the end date + $endDateFix = "AND date_added <= '{$this->_formValues['end_date']} 23:59:00'"; } - $dateRange = "INSERT INTO dates_{$this->_tableName} ( id, date_added ) + $dateRange = "INSERT INTO {$this->_datesTable} ( id, date_added ) SELECT civicrm_contact.id, min(civicrm_log.modified_date) AS date_added @@ -208,22 +208,16 @@ public function from() { GROUP BY civicrm_contact.id HAVING - date_added >= '$startDate' + date_added >= '$startDate 00:00:00' $endDateFix"; - if ($this->_debug > 0) { - print "-- Date range query:
"; - print "$dateRange;"; - print ""; - } - - CRM_Core_DAO::executeQuery($dateRange, CRM_Core_DAO::$_nullArray); + CRM_Core_DAO::executeQuery($dateRange); // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { //block for Group search - $smartGroup = array(); + $smartGroup = []; $group = new CRM_Contact_DAO_Group(); $group->is_active = 1; $group->find(); @@ -249,22 +243,20 @@ public function from() { $xGroups = 0; } - $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); - $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP"; - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); + $xgTable->drop(); + $xgTable->createWithColumns('contact_id int primary key'); //used only when exclude group is selected if ($xGroups != 0) { - $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id ) + $excludeGroup = "INSERT INTO {$this->_xgTable} ( contact_id ) SELECT DISTINCT civicrm_group_contact.contact_id - FROM civicrm_group_contact, dates_{$this->_tableName} AS d + FROM civicrm_group_contact, {$this->_datesTable} AS d WHERE d.id = civicrm_group_contact.contact_id AND civicrm_group_contact.status = 'Added' AND civicrm_group_contact.group_id IN( {$xGroups})"; - CRM_Core_DAO::executeQuery($excludeGroup, CRM_Core_DAO::$_nullArray); + CRM_Core_DAO::executeQuery($excludeGroup); //search for smart group contacts foreach ($this->_excludeGroups as $keys => $values) { @@ -277,31 +269,21 @@ public function from() { SELECT contact_id FROM civicrm_group_contact WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')"; - $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) $smartSql"; + $smartGroupQuery = " INSERT IGNORE INTO {$this->_xgTable}(contact_id) $smartSql"; - CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); + CRM_Core_DAO::executeQuery($smartGroupQuery); } } } - $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); - $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName} - ( id int PRIMARY KEY AUTO_INCREMENT, + $igTable->drop(); + $igTable->createWithColumns('id int PRIMARY KEY AUTO_INCREMENT, contact_id int, - group_names varchar(64)) ENGINE=HEAP"; + group_names varchar(64)'); - if ($this->_debug > 0) { - print "-- Include groups query:
"; - print "$sql;"; - print ""; - } - - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); - - $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names) + $includeGroup = "INSERT INTO {$this->_igTable} (contact_id, group_names) SELECT d.id as contact_id, civicrm_group.name as group_name - FROM dates_{$this->_tableName} AS d + FROM {$this->_datesTable} AS d INNER JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = d.id LEFT JOIN civicrm_group @@ -309,8 +291,8 @@ public function from() { //used only when exclude group is selected if ($xGroups != 0) { - $includeGroup .= " LEFT JOIN Xg_{$this->_tableName} - ON d.id = Xg_{$this->_tableName}.contact_id"; + $includeGroup .= " LEFT JOIN {$this->_xgTable} + ON d.id = {$this->_xgTable}.contact_id"; } $includeGroup .= " WHERE civicrm_group_contact.status = 'Added' AND @@ -318,16 +300,10 @@ public function from() { //used only when exclude group is selected if ($xGroups != 0) { - $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; + $includeGroup .= " AND {$this->_xgTable}.contact_id IS null"; } - if ($this->_debug > 0) { - print "-- Include groups query:
"; - print "$includeGroup;"; - print ""; - } - - CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray); + CRM_Core_DAO::executeQuery($includeGroup); //search for smart group contacts foreach ($this->_includeGroups as $keys => $values) { @@ -339,7 +315,7 @@ public function from() { $smartSql .= " AND contact_a.id IN ( SELECT id AS contact_id - FROM dates_{$this->_tableName} )"; + FROM {$this->_datesTable} )"; $smartSql .= " AND contact_a.id NOT IN ( SELECT contact_id FROM civicrm_group_contact @@ -347,30 +323,20 @@ public function from() { //used only when exclude group is selected if ($xGroups != 0) { - $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})"; + $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM {$this->_xgTable})"; } $smartGroupQuery = " INSERT IGNORE INTO - Ig_{$this->_tableName}(contact_id) + {$this->_igTable}(contact_id) $smartSql"; - CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray); - if ($this->_debug > 0) { - print "-- Smart group query:
"; - print "$smartGroupQuery;"; - print ""; - } - $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName} + CRM_Core_DAO::executeQuery($smartGroupQuery); + $insertGroupNameQuery = "UPDATE IGNORE {$this->_igTable} SET group_names = (SELECT title FROM civicrm_group WHERE civicrm_group.id = $values) - WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL - AND Ig_{$this->_tableName}.group_names IS NULL"; - CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray); - if ($this->_debug > 0) { - print "-- Smart group query:
"; - print "$insertGroupNameQuery;"; - print ""; - } + WHERE {$this->_igTable}.contact_id IS NOT NULL + AND {$this->_igTable}.group_names IS NULL"; + CRM_Core_DAO::executeQuery($insertGroupNameQuery); } } } @@ -380,12 +346,12 @@ public function from() { /* We need to join to this again to get the date_added value */ - $from .= " INNER JOIN dates_{$this->_tableName} d ON (contact_a.id = d.id) {$this->_aclFrom}"; + $from .= " INNER JOIN {$this->_datesTable} d ON (contact_a.id = d.id) {$this->_aclFrom}"; // Only include groups in the search query of one or more Include OR Exclude groups has been selected. // CRM-6356 if ($this->_groups) { - $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)"; + $from .= " INNER JOIN {$this->_igTable} temptable1 ON (contact_a.id = temptable1.contact_id)"; } return $from; @@ -429,22 +395,20 @@ public function setTitle($title) { public function count() { $sql = $this->all(); - $dao = CRM_Core_DAO::executeQuery($sql, - CRM_Core_DAO::$_nullArray - ); + $dao = CRM_Core_DAO::executeQuery($sql); return $dao->N; } public function __destruct() { //drop the temp. tables if they exist - if (!empty($this->_includeGroups)) { - $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); + if ($this->_igTable && !empty($this->_includeGroups)) { + $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_igTable}"; + CRM_Core_DAO::executeQuery($sql); } - if (!empty($this->_excludeGroups)) { - $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; - CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); + if ($this->_xgTable && !empty($this->_excludeGroups)) { + $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_xgTable}"; + CRM_Core_DAO::executeQuery($sql); } } @@ -455,4 +419,27 @@ public function buildACLClause($tableAlias = 'contact') { list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias); } + /** + * Format saved search fields for this custom group. + * + * Note this is a function to facilitate the transition to jcalendar for + * saved search groups. In time it can be stripped out again. + * + * @param array $formValues + * + * @return array + */ + public static function formatSavedSearchFields($formValues) { + $dateFields = [ + 'start_date', + 'end_date', + ]; + foreach ($formValues as $element => $value) { + if (in_array($element, $dateFields) && !empty($value)) { + $formValues[$element] = date('Y-m-d', strtotime($value)); + } + } + return $formValues; + } + } diff --git a/CRM/Contact/Form/Search/Custom/EventAggregate.php b/CRM/Contact/Form/Search/Custom/EventAggregate.php index 2947696c3aa6..e3b36fc95dc7 100644 --- a/CRM/Contact/Form/Search/Custom/EventAggregate.php +++ b/CRM/Contact/Form/Search/Custom/EventAggregate.php @@ -1,9 +1,9 @@ _formValues = $formValues; - $this->_permissionedComponent = array('CiviContribute', 'CiviEvent'); + $this->_formValues = self::formatSavedSearchFields($formValues); + $this->_permissionedComponent = ['CiviContribute', 'CiviEvent']; /** * Define the columns for search result rows */ - $this->_columns = array( + $this->_columns = [ ts('Event') => 'event_name', ts('Type') => 'event_type', ts('Number of
',
- 'pattern' => '/<(\s+)?p(\s+)?>/m',
- ),
- 'br' => array(
- 'oper' => '
',
- 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
- ),
- );
-
- $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
- foreach ($htmlMsg as $k => & $m) {
- $messages = preg_split($newLineOperators['br']['pattern'], $m);
- foreach ($messages as $key => & $msg) {
- $msg = trim($msg);
- $matches = array();
- if (preg_match('/^( )+/', $msg, $matches)) {
- $spaceLen = strlen($matches[0]) / 6;
- $trimMsg = ltrim($msg, ' ');
- $charLen = strlen($trimMsg);
- $totalLen = $charLen + $spaceLen;
- if ($totalLen > 100) {
- $spacesCount = 10;
- if ($spaceLen > 50) {
- $spacesCount = 20;
- }
- if ($charLen > 100) {
- $spacesCount = 1;
- }
- $msg = str_repeat(' ', $spacesCount) . $trimMsg;
- }
- }
- }
- $m = implode($newLineOperators['br']['oper'], $messages);
- }
- $message = implode($newLineOperators['p']['oper'], $htmlMsg);
- }
-
/**
* Convert from a vague-type/file-extension to mime-type.
*
@@ -590,12 +315,12 @@ public static function formatMessage(&$message) {
* @throws \CRM_Core_Exception
*/
private static function getMimeType($type) {
- $mimeTypes = array(
+ $mimeTypes = [
'pdf' => 'application/pdf',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'odt' => 'application/vnd.oasis.opendocument.text',
'html' => 'text/html',
- );
+ ];
if (isset($mimeTypes[$type])) {
return $mimeTypes[$type];
}
@@ -604,4 +329,39 @@ private static function getMimeType($type) {
}
}
+ /**
+ * Get the categories required for rendering tokens.
+ *
+ * @return array
+ */
+ protected static function getTokenCategories() {
+ if (!isset(Civi::$statics[__CLASS__]['token_categories'])) {
+ $tokens = [];
+ CRM_Utils_Hook::tokens($tokens);
+ Civi::$statics[__CLASS__]['token_categories'] = array_keys($tokens);
+ }
+ return Civi::$statics[__CLASS__]['token_categories'];
+ }
+
+ /**
+ * Is the form in live mode (as opposed to being run as a preview).
+ *
+ * Returns true if the user has clicked the Download Document button on a
+ * Print/Merge Document (PDF Letter) search task form, or false if the Preview
+ * button was clicked.
+ *
+ * @param CRM_Core_Form $form
+ *
+ * @return bool
+ * TRUE if the Download Document button was clicked (also defaults to TRUE
+ * if the form controller does not exist), else FALSE
+ */
+ protected static function isLiveMode($form) {
+ // CRM-21255 - Hrm, CiviCase 4+5 seem to report buttons differently...
+ $buttonName = $form->controller->getButtonName();
+ $c = $form->controller->container();
+ $isLiveMode = ($buttonName == '_qf_PDF_upload') || isset($c['values']['PDF']['buttons']['_qf_PDF_upload']);
+ return $isLiveMode;
+ }
+
}
diff --git a/CRM/Contact/Form/Task/PickProfile.php b/CRM/Contact/Form/Task/PickProfile.php
index 46a5d67a6c99..a3a061b8dde3 100644
--- a/CRM/Contact/Form/Task/PickProfile.php
+++ b/CRM/Contact/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_contactIds) > $this->_maxContacts) {
- CRM_Core_Session::setStatus(ts("The maximum number of contacts you can select for Update multiple contacts is %1. You have selected %2. Please select fewer contacts from your search results and try again.", array(
- 1 => $this->_maxContacts,
- 2 => count($this->_contactIds),
- )), ts('Maximum Exceeded'), 'error');
+ CRM_Core_Session::setStatus(ts("The maximum number of contacts you can select for Update multiple contacts is %1. You have selected %2. Please select fewer contacts from your search results and try again.", [
+ 1 => $this->_maxContacts,
+ 2 => count($this->_contactIds),
+ ]), ts('Maximum Exceeded'), 'error');
$validate = TRUE;
}
@@ -106,10 +109,10 @@ public function buildQuickForm() {
if (empty($profiles)) {
$types = implode(' ' . ts('or') . ' ', $this->_contactTypes);
- CRM_Core_Session::setStatus(ts("The contact type selected for Update multiple contacts does not have a corresponding profile. Please set up a profile for %1s and try again.", array(1 => $types)), ts('No Profile Available'), 'error');
+ CRM_Core_Session::setStatus(ts("The contact type selected for Update multiple contacts does not have a corresponding profile. Please set up a profile for %1s and try again.", [1 => $types]), ts('No Profile Available'), 'error');
CRM_Utils_System::redirect($this->_userContext);
}
- $ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'), array('' => ts('- select profile -')) + $profiles, TRUE, array('class' => 'crm-select2 huge'));
+ $ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'), ['' => ts('- select profile -')] + $profiles, TRUE, ['class' => 'crm-select2 huge']);
$this->addDefaultButtons(ts('Continue'));
}
@@ -118,7 +121,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Contact/Form/Task/Print.php b/CRM/Contact/Form/Task/Print.php
index 4087d2bcb10a..911af3dd8257 100644
--- a/CRM/Contact/Form/Task/Print.php
+++ b/CRM/Contact/Form/Task/Print.php
@@ -1,9 +1,9 @@
_contactIds as $contactId) {
- $params[] = array(
+ $params[] = [
CRM_Core_Form::CB_PREFIX . $contactId,
'=',
1,
0,
0,
- );
+ ];
}
}
@@ -82,8 +82,9 @@ public function preProcess() {
$selectorName = $this->controller->selectorName();
require_once str_replace('_', DIRECTORY_SEPARATOR, $selectorName) . '.php';
- $returnP = isset($returnPropeties) ? $returnPropeties : "";
+ $returnP = isset($returnProperties) ? $returnProperties : "";
$customSearchClass = $this->get('customSearchClass');
+ $this->assign('customSearchID', $this->get('customSearchID'));
$selector = new $selectorName($customSearchClass,
$fv,
$params,
@@ -111,19 +112,18 @@ public function buildQuickForm() {
//
// just need to add a javacript to popup the window for printing
//
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Contact List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Contact List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Contact/Form/Task/ProximityCommon.php b/CRM/Contact/Form/Task/ProximityCommon.php
index f1ab27e3d041..b4a0bb0ab3bf 100644
--- a/CRM/Contact/Form/Task/ProximityCommon.php
+++ b/CRM/Contact/Form/Task/ProximityCommon.php
@@ -1,9 +1,9 @@
assign('proximity_search', TRUE);
@@ -74,18 +74,18 @@ static public function buildQuickForm($form, $proxSearch) {
$form->add('text', 'prox_postal_code', ts('Postal Code'), NULL, FALSE);
- $form->addChainSelect('prox_state_province_id', array('required' => $proxRequired));
+ $form->addChainSelect('prox_state_province_id', ['required' => $proxRequired]);
- $country = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
+ $country = ['' => ts('- select -')] + CRM_Core_PseudoConstant::country();
$form->add('select', 'prox_country_id', ts('Country'), $country, $proxRequired);
$form->add('text', 'prox_distance', ts('Distance'), NULL, $proxRequired);
- $proxUnits = array('km' => ts('km'), 'miles' => ts('miles'));
+ $proxUnits = ['km' => ts('km'), 'miles' => ts('miles')];
$form->add('select', 'prox_distance_unit', ts('Units'), $proxUnits, $proxRequired);
// prox_distance_unit
- $form->addFormRule(array('CRM_Contact_Form_Task_ProximityCommon', 'formRule'), $form);
+ $form->addFormRule(['CRM_Contact_Form_Task_ProximityCommon', 'formRule'], $form);
}
/**
@@ -101,15 +101,13 @@ static public function buildQuickForm($form, $proxSearch) {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
// If Distance is present, make sure state, country and city or postal code are populated.
if (!empty($fields['prox_distance'])) {
if (empty($fields['prox_state_province_id']) || empty($fields['prox_country_id'])) {
$errors["prox_state_province_id"] = ts("Country AND State/Province are required to search by distance.");
}
- if (!CRM_Utils_Array::value('prox_postal_code', $fields) AND
- !CRM_Utils_Array::value('prox_city', $fields)
- ) {
+ if (empty($fields['prox_postal_code']) && empty($fields['prox_city'])) {
$errors["prox_distance"] = ts("City OR Postal Code are required to search by distance.");
}
}
@@ -125,8 +123,8 @@ public static function formRule($fields, $files, $form) {
* @return array
* the default array reference
*/
- static public function setDefaultValues($form) {
- $defaults = array();
+ public static function setDefaultValues($form) {
+ $defaults = [];
$config = CRM_Core_Config::singleton();
$countryDefault = $config->defaultContactCountry;
diff --git a/CRM/Contact/Form/Task/RemoveFromGroup.php b/CRM/Contact/Form/Task/RemoveFromGroup.php
index 2a7988082b8f..d803f436e7b6 100644
--- a/CRM/Contact/Form/Task/RemoveFromGroup.php
+++ b/CRM/Contact/Form/Task/RemoveFromGroup.php
@@ -1,9 +1,9 @@
ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup();
- $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, TRUE, array('class' => 'crm-select2 huge'));
+ $group = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup();
+ $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, TRUE, ['class' => 'crm-select2 huge']);
CRM_Utils_System::setTitle(ts('Remove Contacts from Group'));
$this->addDefaultButtons(ts('Remove from Group'));
@@ -58,7 +58,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if ($this->get('context') === 'smog') {
$defaults['group_id'] = $this->get('gid');
@@ -75,24 +75,24 @@ public function postProcess() {
list($total, $removed, $notRemoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($this->_contactIds, $groupId);
- $status = array(
- ts("%count contact removed from '%2'", array(
+ $status = [
+ ts("%count contact removed from '%2'", [
'count' => $removed,
'plural' => "%count contacts removed from '%2'",
2 => $group[$groupId],
- )),
- );
+ ]),
+ ];
if ($notRemoved) {
- $status[] = ts('1 contact was already not in this group', array(
- 'count' => $notRemoved,
- 'plural' => '%count contacts were already not in this group',
- ));
+ $status[] = ts('1 contact was already not in this group', [
+ 'count' => $notRemoved,
+ 'plural' => '%count contacts were already not in this group',
+ ]);
}
$status = '
See console for backtrace
'; @@ -414,16 +421,16 @@ public static function handleUnhandledException($exception) { } catch (Exception $other) { // if the exception-handler generates an exception, then that sucks! oh, well. carry on. - CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other)); + CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other), TRUE, TRUE, '', PEAR_LOG_ERR); } $config = CRM_Core_Config::singleton(); - $vars = array( + $vars = [ 'message' => $exception->getMessage(), 'code' => NULL, 'exception' => $exception, - ); + ]; if (!$vars['message']) { - $vars['message'] = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/')); + $vars['message'] = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', [1 => 'https://civicrm.org/bug-reporting']); } // Case A: CLI @@ -452,24 +459,19 @@ function_exists($config->fatalErrorHandler) // Case C: Default error handler // log to file - CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE); + CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE, TRUE, '', PEAR_LOG_ERR); CRM_Core_Error::backtrace('backTrace', TRUE); // print to screen $template = CRM_Core_Smarty::singleton(); $template->assign($vars); $content = $template->fetch('CRM/common/fatal.tpl'); + if ($config->backtrace) { $content = self::formatHtmlException($exception) . $content; } - if ($config->userFramework == 'Joomla' && - class_exists('JError') - ) { - JError::raiseError('CiviCRM-001', $content); - } - else { - echo CRM_Utils_System::theme($content); - } + + echo CRM_Utils_System::theme($content); // fin self::abend(CRM_Core_Error::FATAL_ERROR); @@ -537,6 +539,8 @@ public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, * Log or return the output? * @param string $prefix * Prefix for output logfile. + * @param int $priority + * The log priority level. * * @return string * The generated output @@ -544,7 +548,7 @@ public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, * @see CRM_Core_Error::debug() * @see CRM_Core_Error::debug_log_message() */ - public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '') { + public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '', $priority = NULL) { // check if variable is set if (!isset($variable)) { $out = "\$$variable_name is not set"; @@ -567,7 +571,7 @@ public static function debug_var($variable_name, $variable, $print = TRUE, $log reset($variable); } } - return self::debug_log_message($out, FALSE, $prefix); + return self::debug_log_message($out, FALSE, $prefix, $priority); } /** @@ -610,7 +614,7 @@ public static function debug_log_message($message, $out = FALSE, $prefix = '', $ if (!empty(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) { // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why if ($config->userSystem->is_drupal and function_exists('watchdog')) { - watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG); + watchdog('civicrm', '%message', ['%message' => $message], isset($priority) ? $priority : WATCHDOG_DEBUG); } } @@ -628,7 +632,7 @@ public static function debug_query($string) { CRM_Core_Error::backtrace($string, TRUE); } elseif (CIVICRM_DEBUG_LOG_QUERY) { - CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log'); + CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log', PEAR_LOG_DEBUG); } } } @@ -640,7 +644,7 @@ public static function debug_query($string) { */ public static function debug_query_result($query) { $results = CRM_Core_DAO::executeQuery($query)->fetchAll(); - CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results)); + CRM_Core_Error::debug_var('dao result', ['query' => $query, 'results' => $results], TRUE, TRUE, '', PEAR_LOG_DEBUG); } /** @@ -666,12 +670,12 @@ public static function createDebugLogger($prefix = '') { */ public static function generateLogFileHash($config) { // Use multiple (but stable) inputs for hash information. - $md5inputs = array( + $md5inputs = [ defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY', $config->userFrameworkBaseURL, md5($config->dsn), $config->dsn, - ); + ]; // Trim 8 chars off the string, make it slightly easier to find // but reveals less information from the hash. return substr(md5(var_export($md5inputs, 1)), 8); @@ -680,7 +684,8 @@ public static function generateLogFileHash($config) { /** * Generate the name of the logfile to use and store it as a static. * - * This function includes poor man's log file management and a check as to whether the file exists. + * This function includes simplistic log rotation and a check as to whether + * the file exists. * * @param string $prefix */ @@ -693,9 +698,9 @@ protected static function generateLogFileName($prefix) { $hash = self::generateLogFileHash($config); $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . $hash . '.log'; - // Roll log file monthly or if greater than 256M - // note that PHP file functions have a limit of 2G and hence - // the alternative was introduce + // Roll log file monthly or if greater than 256M. + // Size-based rotation introduced in response to filesize limits on + // certain OS/PHP combos. if (file_exists($fileName)) { $fileTime = date("Ym", filemtime($fileName)); $fileSize = filesize($fileName); @@ -723,7 +728,7 @@ public static function backtrace($msg = 'backTrace', $log = FALSE) { CRM_Core_Error::debug($msg, $message); } else { - CRM_Core_Error::debug_var($msg, $message); + CRM_Core_Error::debug_var($msg, $message, TRUE, TRUE, '', PEAR_LOG_DEBUG); } } @@ -762,9 +767,9 @@ public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen * @see Exception::getTrace() */ public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) { - $ret = array(); + $ret = []; foreach ($backTrace as $trace) { - $args = array(); + $args = []; $fnName = CRM_Utils_Array::value('function', $trace); $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : ''; @@ -841,13 +846,13 @@ public static function formatHtmlException(Exception $e) { // Exception backtrace if ($e instanceof PEAR_Exception) { $ei = $e; - while (is_callable(array($ei, 'getCause'))) { + while (is_callable([$ei, 'getCause'])) { if ($ei->getCause() instanceof PEAR_Error) { $msg .= '%s | %s |
---|---|
%s | %s |
%s | %s |
',
+ 'pattern' => '/<(\s+)?p(\s+)?>/m',
+ ],
+ 'br' => [
+ 'oper' => '
',
+ 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
+ ],
+ ];
+
+ $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
+ foreach ($htmlMsg as $k => & $m) {
+ $messages = preg_split($newLineOperators['br']['pattern'], $m);
+ foreach ($messages as $key => & $msg) {
+ $msg = trim($msg);
+ $matches = [];
+ if (preg_match('/^( )+/', $msg, $matches)) {
+ $spaceLen = strlen($matches[0]) / 6;
+ $trimMsg = ltrim($msg, ' ');
+ $charLen = strlen($trimMsg);
+ $totalLen = $charLen + $spaceLen;
+ if ($totalLen > 100) {
+ $spacesCount = 10;
+ if ($spaceLen > 50) {
+ $spacesCount = 20;
+ }
+ if ($charLen > 100) {
+ $spacesCount = 1;
+ }
+ $msg = str_repeat(' ', $spacesCount) . $trimMsg;
+ }
+ }
+ }
+ $m = implode($newLineOperators['br']['oper'], $messages);
+ }
+ $message = implode($newLineOperators['p']['oper'], $htmlMsg);
+ }
+
+}
diff --git a/CRM/Core/Form/Task/PickProfile.php b/CRM/Core/Form/Task/PickProfile.php
new file mode 100644
index 000000000000..926fdf30973d
--- /dev/null
+++ b/CRM/Core/Form/Task/PickProfile.php
@@ -0,0 +1,170 @@
+_userContext = $session->readUserContext();
+
+ CRM_Utils_System::setTitle(ts('Update multiple ' . $this::$entityShortname . 's'));
+
+ // validations
+ if (count($this->_entityIds) > $this->_maxEntities) {
+ CRM_Core_Session::setStatus(ts("The maximum number of %3 you can select for Update multiple %3 is %1. You have selected %2. Please select fewer %3 from your search results and try again.", [
+ 1 => $this->_maxEntities,
+ 2 => count($this->_entityIds),
+ 3 => $this::$entityShortname . 's',
+ ]), ts('Update multiple records error'), 'error');
+ CRM_Utils_System::redirect($this->_userContext);
+ }
+ }
+
+ /**
+ * Build the form object.
+ *
+ * @return void
+ */
+ public function buildQuickForm() {
+ $types = [ucfirst($this::$entityShortname)];
+ $profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
+
+ if (empty($profiles)) {
+ CRM_Core_Session::setStatus(
+ ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple %2. Navigate to Administer > Customize Data and Screens > Profiles to configure a Profile. Consult the online Administrator documentation for more information.",
+ [
+ 1 => $types[0],
+ 2 => $this::$entityShortname . 's',
+ ]),
+ ts('Update multiple records error'),
+ 'error'
+ );
+ CRM_Utils_System::redirect($this->_userContext);
+ }
+
+ $this->add('select',
+ 'uf_group_id',
+ ts('Select Profile'),
+ [
+ '' => ts('- select profile -'),
+ ] + $profiles,
+ TRUE
+ );
+ $this->addDefaultButtons(ts('Continue'));
+
+ $taskComponent['lc'] = $this::$entityShortname;
+ $taskComponent['ucfirst'] = ucfirst($this::$entityShortname);
+ $this->assign('taskComponent', $taskComponent);
+ }
+
+ /**
+ * Add local and global form rules.
+ *
+ * @return void
+ */
+ public function addRules() {
+ $this->addFormRule(['CRM_' . ucfirst($this::$entityShortname) . '_Form_Task_PickProfile', 'formRule']);
+ }
+
+ /**
+ * Global validation rules for the form.
+ *
+ * @param array $fields
+ * Posted values of the form.
+ *
+ * @return bool|array
+ * true if no errors, else array of errors
+ */
+ public static function formRule($fields) {
+ return TRUE;
+ }
+
+ /**
+ * Process the form after the input has been submitted and validated.
+ *
+ * @return void
+ */
+ public function postProcess() {
+ $params = $this->exportValues();
+
+ $this->set('ufGroupId', $params['uf_group_id']);
+
+ // also reset the batch page so it gets new values from the db
+ $this->controller->resetPage('Batch');
+ }
+
+}
diff --git a/CRM/Core/HTMLInputCoder.php b/CRM/Core/HTMLInputCoder.php
index 15aaa3575f6d..b04a9f649e6e 100644
--- a/CRM/Core/HTMLInputCoder.php
+++ b/CRM/Core/HTMLInputCoder.php
@@ -1,9 +1,9 @@
sql])`.
+ *
+ * This option is not intended for general consumption. It is only intended
+ * for certain pre-boot/pre-install contexts.
+ *
+ * You might ask, "Why on Earth does string-translation have an opinion on
+ * SQL escaping?" Good question!
+ */
+ public static $SQL_ESCAPER = NULL;
+
+ /**
+ * Encode a string for use in SQL.
+ *
+ * @param string $text
+ * @return string
+ */
+ protected static function escapeSql($text) {
+ if (self::$SQL_ESCAPER == NULL) {
+ return CRM_Core_DAO::escapeString($text);
+ }
+ else {
+ return call_user_func(self::$SQL_ESCAPER, $text);
+ }
+ }
/**
* A PHP-gettext instance for string translation;
* should stay null if the strings are not to be translated (en_US).
+ * @var object
*/
private $_phpgettext = NULL;
/**
* Whether we are using native gettext or not.
+ * @var bool
*/
private $_nativegettext = FALSE;
@@ -55,8 +85,9 @@ class CRM_Core_I18n {
* Gettext cache for extension domains/streamers, depending on if native or phpgettext.
* - native gettext: we cache the value for textdomain()
* - phpgettext: we cache the file streamer.
+ * @var array
*/
- private $_extensioncache = array();
+ private $_extensioncache = [];
/**
* @var string
@@ -163,14 +194,22 @@ public static function languages($justEnabled = FALSE) {
if (!$all) {
$all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
+ // get labels
+ $rows = [];
+ $labels = [];
+ CRM_Core_OptionValue::getValues(['name' => 'languages'], $rows);
+ foreach ($rows as $id => $row) {
+ $labels[$row['name']] = $row['label'];
+ }
+
// check which ones are available; add them to $all if not there already
- $codes = array();
+ $codes = [];
if (is_dir(CRM_Core_I18n::getResourceDir()) && $dir = opendir(CRM_Core_I18n::getResourceDir())) {
while ($filename = readdir($dir)) {
if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
$codes[] = $filename;
if (!isset($all[$filename])) {
- $all[$filename] = $filename;
+ $all[$filename] = $labels[$filename];
}
}
}
@@ -186,14 +225,16 @@ public static function languages($justEnabled = FALSE) {
unset($all[$code]);
}
}
+
+ asort($all);
}
if ($enabled === NULL) {
- $config = CRM_Core_Config::singleton();
- $enabled = array();
- if (isset($config->languageLimit) and $config->languageLimit) {
+ $languageLimit = Civi::settings()->get('languageLimit');
+ $enabled = [];
+ if ($languageLimit) {
foreach ($all as $code => $name) {
- if (in_array($code, array_keys($config->languageLimit))) {
+ if (array_key_exists($code, $languageLimit)) {
$enabled[$code] = $name;
}
}
@@ -203,6 +244,28 @@ public static function languages($justEnabled = FALSE) {
return $justEnabled ? $enabled : $all;
}
+ /**
+ * Return the available UI languages
+ * @return array|string
+ * array(string languageCode => string languageName) if !$justCodes
+ */
+ public static function uiLanguages($justCodes = FALSE) {
+ // In multilang we only allow the languages that are configured in db
+ // Otherwise, the languages configured in uiLanguages
+ $settings = Civi::settings();
+ if (CRM_Core_I18n::isMultiLingual()) {
+ $codes = array_keys((array) $settings->get('languageLimit'));
+ }
+ else {
+ $codes = $settings->get('uiLanguages');
+ if (!$codes) {
+ $codes = [$settings->get('lcMessages')];
+ }
+ }
+ return $justCodes ? $codes
+ : CRM_Utils_Array::subset(CRM_Core_I18n::languages(), $codes);
+ }
+
/**
* Replace arguments in a string with their values. Arguments are represented by % followed by their number.
*
@@ -213,7 +276,7 @@ public static function languages($justEnabled = FALSE) {
* modified string
*/
public function strarg($str) {
- $tr = array();
+ $tr = [];
$p = 0;
for ($i = 1; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
@@ -263,11 +326,12 @@ public static function getResourceDir() {
* The params of the translation (if any).
* - domain: string|array a list of translation domains to search (in order)
* - context: string
+ * - skip_translation: flag (do only escape/replacement, skip the actual translation)
*
* @return string
* the translated string
*/
- public function crm_translate($text, $params = array()) {
+ public function crm_translate($text, $params = []) {
if (isset($params['escape'])) {
$escape = $params['escape'];
unset($params['escape']);
@@ -279,7 +343,7 @@ public function crm_translate($text, $params = array()) {
// in such cases we return early, only doing SQL/JS escaping
if (isset($params['skip']) and $params['skip']) {
if (isset($escape) and ($escape == 'sql')) {
- $text = CRM_Core_DAO::escapeString($text);
+ $text = self::escapeSql($text);
}
if (isset($escape) and ($escape == 'js')) {
$text = addcslashes($text, "'");
@@ -315,24 +379,26 @@ public function crm_translate($text, $params = array()) {
$raw = !empty($params['raw']);
unset($params['raw']);
- if (!empty($domain)) {
- // It might be prettier to cast to an array, but this is high-traffic stuff.
- if (is_array($domain)) {
- foreach ($domain as $d) {
- $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
- if ($candidate != $text) {
- $text = $candidate;
- break;
+ if (!isset($params['skip_translation'])) {
+ if (!empty($domain)) {
+ // It might be prettier to cast to an array, but this is high-traffic stuff.
+ if (is_array($domain)) {
+ foreach ($domain as $d) {
+ $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
+ if ($candidate != $text) {
+ $text = $candidate;
+ break;
+ }
}
}
+ else {
+ $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
+ }
}
else {
- $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
+ $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
}
}
- else {
- $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
- }
// replace the numbered %1, %2, etc. params if present
if (count($params) && !$raw) {
@@ -341,7 +407,7 @@ public function crm_translate($text, $params = array()) {
// escape SQL if we were asked for it
if (isset($escape) and ($escape == 'sql')) {
- $text = CRM_Core_DAO::escapeString($text);
+ $text = self::escapeSql($text);
}
// escape for JavaScript (if requested)
@@ -356,8 +422,8 @@ public function crm_translate($text, $params = array()) {
* Lookup the raw translation of a string (without any extra escaping or interpolation).
*
* @param string $text
- * @param string|NULL $domain
- * @param int|NULL $count
+ * @param string|null $domain
+ * @param int|null $count
* @param string $plural
* @param string $context
*
@@ -381,7 +447,7 @@ protected function crm_translate_raw($text, $domain, $count, $plural, $context)
Civi::$statics[__CLASS__][$replacementsLocale] = CRM_Core_BAO_WordReplacement::getLocaleCustomStrings($replacementsLocale);
}
else {
- Civi::$statics[__CLASS__][$replacementsLocale] = array();
+ Civi::$statics[__CLASS__][$replacementsLocale] = [];
}
}
$stringTable = Civi::$statics[__CLASS__][$replacementsLocale];
@@ -423,7 +489,7 @@ protected function crm_translate_raw($text, $domain, $count, $plural, $context)
}
// expand %count in translated string to $count
- $text = strtr($text, array('%count' => $count));
+ $text = strtr($text, ['%count' => $count]);
// if not plural, but the locale's set, translate
}
@@ -467,7 +533,7 @@ public function translate($string) {
*/
public function localizeArray(
&$array,
- $params = array()
+ $params = []
) {
$tsLocale = CRM_Core_I18n::getLocale();
@@ -495,7 +561,7 @@ public function localizeTitles(&$array) {
$array[$key] = $value;
}
elseif ((string ) $key == 'title') {
- $array[$key] = ts($value, array('context' => 'menu'));
+ $array[$key] = ts($value, ['context' => 'menu']);
}
}
}
@@ -557,7 +623,6 @@ public function setGettextDomain($key) {
return FALSE;
}
-
/**
* Is the CiviCRM in multilingual mode.
*
@@ -607,10 +672,16 @@ public function setLocale($locale) {
$this->setPhpGettextLocale($locale);
}
- // for sql queries
+ // For sql queries, if running in DB multi-lingual mode.
global $dbLocale;
- $dbLocale = "_{$locale}";
+ if ($dbLocale) {
+ $dbLocale = "_{$locale}";
+ }
+
+ // For self::getLocale()
+ global $tsLocale;
+ $tsLocale = $locale;
}
/**
@@ -619,14 +690,15 @@ public function setLocale($locale) {
* @return CRM_Core_I18n
*/
public static function &singleton() {
- static $singleton = array();
-
+ if (!isset(Civi::$statics[__CLASS__]['singleton'])) {
+ Civi::$statics[__CLASS__]['singleton'] = [];
+ }
$tsLocale = CRM_Core_I18n::getLocale();
- if (!isset($singleton[$tsLocale])) {
- $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
+ if (!isset(Civi::$statics[__CLASS__]['singleton'][$tsLocale])) {
+ Civi::$statics[__CLASS__]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
}
- return $singleton[$tsLocale];
+ return Civi::$statics[__CLASS__]['singleton'][$tsLocale];
}
/**
@@ -636,7 +708,7 @@ public static function &singleton() {
* the final LC_TIME that got set
*/
public static function setLcTime() {
- static $locales = array();
+ static $locales = [];
$tsLocale = CRM_Core_I18n::getLocale();
if (!isset($locales[$tsLocale])) {
@@ -663,10 +735,10 @@ public static function getContactDefaultLanguage() {
return NULL;
}
if (empty($language) || $language === '*default*') {
- $language = civicrm_api3('setting', 'getvalue', array(
+ $language = civicrm_api3('setting', 'getvalue', [
'name' => 'lcMessages',
'group' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
- ));
+ ]);
}
elseif ($language == 'current_site_language') {
return CRM_Core_I18n::getLocale();
@@ -698,9 +770,9 @@ public static function getLocale() {
* @return string
* the translated string
*/
-function ts($text, $params = array()) {
- static $config = NULL;
- static $locale = NULL;
+function ts($text, $params = []) {
+ static $bootstrapReady = FALSE;
+ static $lastLocale = NULL;
static $i18n = NULL;
static $function = NULL;
@@ -708,17 +780,26 @@ function ts($text, $params = array()) {
return '';
}
- if (!$config) {
- $config = CRM_Core_Config::singleton();
+ // When the settings become available, lookup customTranslateFunction.
+ if (!$bootstrapReady) {
+ $bootstrapReady = (bool) \Civi\Core\Container::isContainerBooted();
+ if ($bootstrapReady) {
+ // just got ready: determine whether there is a working custom translation function
+ $config = CRM_Core_Config::singleton();
+ if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
+ $function = $config->customTranslateFunction;
+ }
+ }
+ else {
+ // don't _translate_ anything until bootstrap has progressed enough
+ $params['skip_translation'] = 1;
+ }
}
- $tsLocale = CRM_Core_I18n::getLocale();
- if (!$i18n or $locale != $tsLocale) {
+ $activeLocale = CRM_Core_I18n::getLocale();
+ if (!$i18n or $lastLocale != $activeLocale) {
$i18n = CRM_Core_I18n::singleton();
- $locale = $tsLocale;
- if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
- $function = $config->customTranslateFunction;
- }
+ $lastLocale = $activeLocale;
}
if ($function) {
diff --git a/CRM/Core/I18n/Form.php b/CRM/Core/I18n/Form.php
index 98391172fd2d..dd7aa9bd31dc 100644
--- a/CRM/Core/I18n/Form.php
+++ b/CRM/Core/I18n/Form.php
@@ -1,9 +1,9 @@
addElement('hidden', 'field', $field);
$this->addElement('hidden', 'id', $id);
- $cols = array();
+ $cols = [];
foreach ($this->_locales as $locale) {
$cols[] = "{$field}_{$locale} {$locale}";
}
@@ -66,7 +67,7 @@ public function buildQuickForm() {
$widget = $widgets[$table][$field];
// attributes
- $attributes = array('class' => '');
+ $attributes = ['class' => ''];
if (isset($widget['rows'])) {
$attributes['rows'] = $widget['rows'];
}
@@ -77,7 +78,10 @@ public function buildQuickForm() {
if ($widget['type'] == 'RichTextEditor') {
$widget['type'] = 'wysiwyg';
- $attributes['class'] .= ' collapsed';
+ $attributes['class'] = 'collapsed';
+ }
+ elseif ($widget['type'] == 'Text') {
+ $attributes['class'] = 'huge';
}
$languages = CRM_Core_I18n::languages(TRUE);
@@ -123,12 +127,12 @@ public function postProcess() {
CRM_Core_Error::fatal("$table.$field is not internationalized.");
}
- $cols = array();
- $params = array(array($values['id'], 'Int'));
+ $cols = [];
+ $params = [[$values['id'], 'Int']];
$i = 1;
foreach ($this->_locales as $locale) {
$cols[] = "{$field}_{$locale} = %$i";
- $params[$i] = array($values["{$field}_{$locale}"], 'String');
+ $params[$i] = [$values["{$field}_{$locale}"], 'String'];
$i++;
}
$query = "UPDATE $table SET " . implode(', ', $cols) . " WHERE id = %0";
diff --git a/CRM/Core/I18n/NativeGettext.php b/CRM/Core/I18n/NativeGettext.php
index 84acac2bfc37..cec8fbfa6e59 100644
--- a/CRM/Core/I18n/NativeGettext.php
+++ b/CRM/Core/I18n/NativeGettext.php
@@ -1,9 +1,9 @@
'languages'), $rows);
+ $rows = [];
+ CRM_Core_OptionValue::getValues(['name' => 'languages'], $rows);
- $longForShortMapping = array();
+ $longForShortMapping = [];
foreach ($rows as $row) {
$longForShortMapping[$row['value']] = $row['name'];
}
@@ -84,12 +84,12 @@ public static function shortForLong($long) {
* @return array
*/
public static function getRTLlanguages() {
- $rtl = array(
+ $rtl = [
'ar',
'fa',
'he',
'ur',
- );
+ ];
return $rtl;
}
diff --git a/CRM/Core/I18n/Schema.php b/CRM/Core/I18n/Schema.php
index 46bd495326e2..64cb94b08f9f 100644
--- a/CRM/Core/I18n/Schema.php
+++ b/CRM/Core/I18n/Schema.php
@@ -1,9 +1,9 @@
$hash) {
// drop old indices
if (isset($indices[$table])) {
@@ -107,6 +107,9 @@ public static function makeMultilingual($locale) {
// update civicrm_domain.locales
$domain->locales = $locale;
$domain->save();
+
+ // CRM-21627 Updates the $dbLocale
+ CRM_Core_BAO_ConfigSetting::applyLocale(Civi::settings($domain->id), $domain->locales);
}
/**
@@ -164,7 +167,7 @@ public static function makeSinglelingualTable(
$retain,
$table,
$class = 'CRM_Core_I18n_SchemaStructure',
- $triggers = array()
+ $triggers = []
) {
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
@@ -177,8 +180,8 @@ public static function makeSinglelingualTable(
$columns =& $class::columns();
$indices =& $class::indices();
- $queries = array();
- $dropQueries = array();
+ $queries = [];
+ $dropQueries = [];
// drop indices
if (isset($indices[$table])) {
foreach ($indices[$table] as $index) {
@@ -188,18 +191,20 @@ public static function makeSinglelingualTable(
}
}
+ $dao = new CRM_Core_DAO();
// deal with columns
foreach ($columns[$table] as $column => $type) {
- $queries[] = "ALTER TABLE {$table} ADD {$column} {$type}";
- $queries[] = "UPDATE {$table} SET {$column} = {$column}_{$retain}";
+ $queries[] = "ALTER TABLE {$table} CHANGE `{$column}_{$retain}` `{$column}` {$type}";
foreach ($locales as $loc) {
- $dropQueries[] = "ALTER TABLE {$table} DROP {$column}_{$loc}";
+ if (strcmp($loc, $retain) !== 0) {
+ $dropQueries[] = "ALTER TABLE {$table} DROP {$column}_{$loc}";
+ }
}
}
// drop views
foreach ($locales as $loc) {
- $queries[] = "DROP VIEW {$table}_{$loc}";
+ $queries[] = "DROP VIEW IF EXISTS {$table}_{$loc}";
}
// add original indices
@@ -255,12 +260,12 @@ public static function addLocale($locale, $source) {
// build the required SQL queries
$columns = CRM_Core_I18n_SchemaStructure::columns();
$indices = CRM_Core_I18n_SchemaStructure::indices();
- $queries = array();
+ $queries = [];
foreach ($columns as $table => $hash) {
// add new columns
foreach ($hash as $column => $type) {
// CRM-7854: skip existing columns
- if (CRM_Core_DAO::checkFieldExists($table, "{$column}_{$locale}", FALSE)) {
+ if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists($table, "{$column}_{$locale}", FALSE)) {
continue;
}
$queries[] = "ALTER TABLE {$table} ADD {$column}_{$locale} {$type}";
@@ -295,8 +300,10 @@ public static function addLocale($locale, $source) {
* locales to be rebuilt.
* @param string $version
* version of schema structure to use.
+ * @param bool $isUpgradeMode
+ * Are we upgrading our database
*/
- public static function rebuildMultilingualSchema($locales, $version = NULL) {
+ public static function rebuildMultilingualSchema($locales, $version = NULL, $isUpgradeMode = FALSE) {
if ($version) {
$latest = self::getLatestSchema($version);
require_once "CRM/Core/I18n/SchemaStructure_{$latest}.php";
@@ -307,13 +314,13 @@ public static function rebuildMultilingualSchema($locales, $version = NULL) {
}
$indices =& $class::indices();
$tables =& $class::tables();
- $queries = array();
+ $queries = [];
$dao = new CRM_Core_DAO();
// get all of the already existing indices
- $existing = array();
+ $existing = [];
foreach (array_keys($indices) as $table) {
- $existing[$table] = array();
+ $existing[$table] = [];
$dao->query("SHOW INDEX FROM $table", FALSE);
while ($dao->fetch()) {
if (preg_match('/_[a-z][a-z]_[A-Z][A-Z]$/', $dao->Key_name)) {
@@ -337,7 +344,7 @@ public static function rebuildMultilingualSchema($locales, $version = NULL) {
// rebuild views
foreach ($locales as $locale) {
foreach ($tables as $table) {
- $queries[] = self::createViewQuery($locale, $table, $dao, $class);
+ $queries[] = self::createViewQuery($locale, $table, $dao, $class, $isUpgradeMode);
}
}
@@ -410,9 +417,9 @@ public static function getLatestSchema($version) {
$version = str_ireplace(".upgrade", "", $version);
// fetch all the SchemaStructure versions we ship and sort by version
- $schemas = array();
+ $schemas = [];
foreach (scandir(dirname(__FILE__)) as $file) {
- $matches = array();
+ $matches = [];
if (preg_match('/^SchemaStructure_([0-9a-z_]+)\.php$/', $file, $matches)) {
$schemas[] = str_replace('_', '.', $matches[1]);
}
@@ -444,10 +451,10 @@ private static function createIndexQueries($locale, $table, $class = 'CRM_Core_I
$indices =& $class::indices();
$columns =& $class::columns();
if (!isset($indices[$table])) {
- return array();
+ return [];
}
- $queries = array();
+ $queries = [];
foreach ($indices[$table] as $index) {
$unique = isset($index['unique']) && $index['unique'] ? 'UNIQUE' : '';
foreach ($index['field'] as $i => $col) {
@@ -481,13 +488,15 @@ private static function createIndexQueries($locale, $table, $class = 'CRM_Core_I
* A DAO object to run DESCRIBE queries.
* @param string $class
* schema structure class to use.
- *
+ * @param bool $isUpgradeMode
+ * Are we in upgrade mode therefore only build based off table not class
* @return array
* array of CREATE INDEX queries
*/
- private static function createViewQuery($locale, $table, &$dao, $class = 'CRM_Core_I18n_SchemaStructure') {
+ private static function createViewQuery($locale, $table, &$dao, $class = 'CRM_Core_I18n_SchemaStructure', $isUpgradeMode = FALSE) {
$columns =& $class::columns();
- $cols = array();
+ $cols = [];
+ $tableCols = [];
$dao->query("DESCRIBE {$table}", FALSE);
while ($dao->fetch()) {
// view non-internationalized columns directly
@@ -496,10 +505,16 @@ private static function createViewQuery($locale, $table, &$dao, $class = 'CRM_Co
) {
$cols[] = $dao->Field;
}
+ $tableCols[] = $dao->Field;
}
// view intrernationalized columns through an alias
foreach ($columns[$table] as $column => $_) {
- $cols[] = "{$column}_{$locale} {$column}";
+ if (!$isUpgradeMode) {
+ $cols[] = "{$column}_{$locale} {$column}";
+ }
+ elseif (in_array("{$column}_{$locale}", $tableCols)) {
+ $cols[] = "{$column}_{$locale} {$column}";
+ }
}
return "CREATE OR REPLACE VIEW {$table}_{$locale} AS SELECT " . implode(', ', $cols) . " FROM {$table}";
}
@@ -545,7 +560,7 @@ public static function triggerInfo(&$info, $tableName = NULL) {
continue;
}
- $trigger = array();
+ $trigger = [];
foreach ($hash as $column => $_) {
$trigger[] = "IF NEW.{$column}_{$locale} IS NOT NULL THEN";
@@ -554,9 +569,9 @@ public static function triggerInfo(&$info, $tableName = NULL) {
}
foreach ($locales as $old) {
$trigger[] = "ELSEIF NEW.{$column}_{$old} IS NOT NULL THEN";
- foreach (array_merge($locales, array(
+ foreach (array_merge($locales, [
$locale,
- )) as $loc) {
+ ]) as $loc) {
if ($loc == $old) {
continue;
}
@@ -567,17 +582,17 @@ public static function triggerInfo(&$info, $tableName = NULL) {
}
$sql = implode(' ', $trigger);
- $info[] = array(
- 'table' => array($table),
+ $info[] = [
+ 'table' => [$table],
'when' => 'BEFORE',
- 'event' => array('UPDATE'),
+ 'event' => ['UPDATE'],
'sql' => $sql,
- );
+ ];
}
// take care of the ON INSERT triggers
foreach ($columns as $table => $hash) {
- $trigger = array();
+ $trigger = [];
foreach ($hash as $column => $_) {
$trigger[] = "IF NEW.{$column}_{$locale} IS NOT NULL THEN";
foreach ($locales as $old) {
@@ -585,9 +600,9 @@ public static function triggerInfo(&$info, $tableName = NULL) {
}
foreach ($locales as $old) {
$trigger[] = "ELSEIF NEW.{$column}_{$old} IS NOT NULL THEN";
- foreach (array_merge($locales, array(
+ foreach (array_merge($locales, [
$locale,
- )) as $loc) {
+ ]) as $loc) {
if ($loc == $old) {
continue;
}
@@ -598,12 +613,12 @@ public static function triggerInfo(&$info, $tableName = NULL) {
}
$sql = implode(' ', $trigger);
- $info[] = array(
- 'table' => array($table),
+ $info[] = [
+ 'table' => [$table],
'when' => 'BEFORE',
- 'event' => array('INSERT'),
+ 'event' => ['INSERT'],
'sql' => $sql,
- );
+ ];
}
}
diff --git a/CRM/Core/I18n/SchemaStructure.php b/CRM/Core/I18n/SchemaStructure.php
new file mode 100644
index 000000000000..a093cbbff57f
--- /dev/null
+++ b/CRM/Core/I18n/SchemaStructure.php
@@ -0,0 +1,726 @@
+ [
+ 'display_name' => "varchar(64) COMMENT 'Location Type Display Name.'",
+ ],
+ 'civicrm_option_group' => [
+ 'title' => "varchar(255) COMMENT 'Option Group title.'",
+ 'description' => "varchar(255) COMMENT 'Option group description.'",
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => "varchar(64) COMMENT 'label for relationship of contact_a to contact_b.'",
+ 'label_b_a' => "varchar(64) COMMENT 'Optional label for relationship of contact_b to contact_a.'",
+ 'description' => "varchar(255) COMMENT 'Optional verbose description of the relationship type.'",
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => "varchar(64) COMMENT 'localized Name of Contact Type.'",
+ 'description' => "text COMMENT 'localized Optional verbose description of the type.'",
+ ],
+ 'civicrm_batch' => [
+ 'title' => "varchar(255) COMMENT 'Friendly Name.'",
+ 'description' => "text COMMENT 'Description of this batch set.'",
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => "varchar(255) COMMENT 'Title for Premiums section.'",
+ 'premiums_intro_text' => "text COMMENT 'Displayed in
', '
');
$text = $this->_substring_between($content, '"; - return FALSE; - } - $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $transaction = new CRM_Core_Transaction(); @@ -133,7 +135,7 @@ public function recur(&$input, &$ids, &$objects, $first) { $now = date('YmdHis'); // fix dates that already exist - $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date'); + $dates = ['create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date']; foreach ($dates as $name) { if ($recur->$name) { $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name); @@ -154,6 +156,7 @@ public function recur(&$input, &$ids, &$objects, $first) { $contribution->amount_level = $objects['contribution']->amount_level; $contribution->address_id = $objects['contribution']->address_id; $contribution->campaign_id = $objects['contribution']->campaign_id; + $contribution->_relatedObjects = $objects['contribution']->_relatedObjects; $objects['contribution'] = &$contribution; } @@ -161,8 +164,6 @@ public function recur(&$input, &$ids, &$objects, $first) { $objects['contribution']->total_amount = $input['amount']; $objects['contribution']->trxn_id = $input['trxn_id']; - $this->checkMD5($paymentProcessorObject, $input); - $isFirstOrLastRecurringPayment = FALSE; if ($input['response_code'] == 1) { // Approved @@ -191,7 +192,7 @@ public function recur(&$input, &$ids, &$objects, $first) { $recur->cancel_date = $now; $recur->save(); - $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text']))); + $message = ts("Subscription payment failed - %1", [1 => htmlspecialchars($input['response_reason_text'])]); CRM_Core_Error::debug_log_message($message); // the recurring contribution has declined a payment or has failed @@ -229,6 +230,7 @@ public function recur(&$input, &$ids, &$objects, $first) { * @param array $ids * * @return bool + * @throws \CRM_Core_Exception */ public function getInput(&$input, &$ids) { $input['amount'] = $this->retrieve('x_amount', 'String'); @@ -240,7 +242,7 @@ public function getInput(&$input, &$ids) { $input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0); $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE); $input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE); - $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, 'now'); + $input['receive_date'] = $this->retrieve('receive_date', 'String', FALSE, date('YmdHis', strtotime('now'))); if ($input['trxn_id']) { $input['is_test'] = 0; @@ -256,7 +258,7 @@ public function getInput(&$input, &$ids) { return FALSE; } $billingID = $ids['billing']; - $params = array( + $params = [ 'first_name' => 'x_first_name', 'last_name' => 'x_last_name', "street_address-{$billingID}" => 'x_address', @@ -265,7 +267,7 @@ public function getInput(&$input, &$ids) { "postal_code-{$billingID}" => 'x_zip', "country-{$billingID}" => 'x_country', "email-{$billingID}" => 'x_email', - ); + ]; foreach ($params as $civiName => $resName) { $input[$civiName] = $this->retrieve($resName, 'String', FALSE); } @@ -295,14 +297,14 @@ public function getIDs(&$ids, &$input) { $contRecur->fetch(); $ids['contributionRecur'] = $contRecur->id; if ($ids['contact'] != $contRecur->contact_id) { - $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", array(1 => $ids['contact'], 2 => $contRecur->contact_id)); + $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", [1 => $ids['contact'], 2 => $contRecur->contact_id]); CRM_Core_Error::debug_log_message($message); $ids['contact'] = $contRecur->contact_id; } if (!$ids['contributionRecur']) { $message = ts("Could not find contributionRecur id"); $log = new CRM_Utils_SystemLogger(); - $log->error('payment_notification', array('message' => $message, 'ids' => $ids, 'input' => $input)); + $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]); throw new CRM_Core_Exception($message); } @@ -356,25 +358,4 @@ public function retrieve($name, $type, $abort = TRUE, $default = NULL) { return $value; } - /** - * Check and validate gateway MD5 response if present. - * - * @param CRM_Core_Payment_AuthorizeNet $paymentObject - * @param array $input - * - * @throws CRM_Core_Exception - */ - public function checkMD5($paymentObject, $input) { - if (empty($input['trxn_id'])) { - // For decline we have nothing to check against. - return; - } - if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) { - $message = "Failure: Security verification failed"; - $log = new CRM_Utils_SystemLogger(); - $log->error('payment_notification', array('message' => $message, 'input' => $input)); - throw new CRM_Core_Exception($message); - } - } - } diff --git a/CRM/Core/Payment/BaseIPN.php b/CRM/Core/Payment/BaseIPN.php index c4a1af336ce7..9e7ed420ba3c 100644 --- a/CRM/Core/Payment/BaseIPN.php +++ b/CRM/Core/Payment/BaseIPN.php @@ -1,9 +1,9 @@ contribution_page_id + unset($ids['contributionPage']); + } + if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) { return FALSE; } @@ -156,10 +164,10 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces // default options are that we log an error & echo it out // note that we should refactor this error handling into error code @ some point // but for now setting up enough separation so we can do unit tests - $error_handling = array( + $error_handling = [ 'log_error' => 1, 'echo_error' => 1, - ); + ]; } $ids['paymentProcessor'] = $paymentProcessorID; if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) { @@ -187,10 +195,10 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces echo $e->getMessage(); } if (!empty($error_handling['return_error'])) { - return array( + return [ 'is_error' => 1, 'error_message' => ($e->getMessage()), - ); + ]; } } $objects = array_merge($objects, $contribution->_relatedObjects); @@ -205,14 +213,15 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces * @param array $input * * @return bool + * @throws \CiviCRM_API3_Exception */ - public function failed(&$objects, &$transaction, $input = array()) { + public function failed(&$objects, &$transaction, $input = []) { $contribution = &$objects['contribution']; - $memberships = array(); + $memberships = []; if (!empty($objects['membership'])) { $memberships = &$objects['membership']; if (is_numeric($memberships)) { - $memberships = array($objects['membership']); + $memberships = [$objects['membership']]; } } @@ -223,14 +232,14 @@ public function failed(&$objects, &$transaction, $input = array()) { $participant = &$objects['participant']; // CRM-15546 - $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); + $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [ + 'labelColumn' => 'name', + 'flip' => 1, + ]); + $contribution->contribution_status_id = $contributionStatuses['Failed']; $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); - $contribution->contribution_status_id = $contributionStatuses['Failed']; $contribution->save(); // Add line items for recurring payments. @@ -247,36 +256,19 @@ public function failed(&$objects, &$transaction, $input = array()) { if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { if (!empty($memberships)) { - // if transaction is failed then set "Cancelled" as membership status - $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); foreach ($memberships as $membership) { - if ($membership) { - $membership->status_id = $membershipStatuses['Cancelled']; - $membership->save(); - - //update related Memberships. - $params = array('status_id' => $membershipStatuses['Cancelled']); - CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params); - } + // @fixme Should we cancel only Pending memberships? per cancelled() + $this->cancelMembership($membership, $membership->status_id, FALSE); } } if ($participant) { - $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); - $participant->status_id = $participantStatuses['Cancelled']; - $participant->save(); + $this->cancelParticipant($participant->id); } } $transaction->commit(); - CRM_Core_Error::debug_log_message("Setting contribution status to failed"); - //echo "Success: Setting contribution status to failed
"; + Civi::log()->debug("Setting contribution status to Failed"); return TRUE; } @@ -290,7 +282,7 @@ public function failed(&$objects, &$transaction, $input = array()) { */ public function pending(&$objects, &$transaction) { $transaction->commit(); - CRM_Core_Error::debug_log_message("returning since contribution status is pending"); + Civi::log()->debug("Returning since contribution status is Pending"); echo "Success: Returning since contribution status is pending
"; return TRUE; } @@ -303,32 +295,38 @@ public function pending(&$objects, &$transaction) { * @param array $input * * @return bool + * @throws \CiviCRM_API3_Exception */ - public function cancelled(&$objects, &$transaction, $input = array()) { + public function cancelled(&$objects, &$transaction, $input = []) { $contribution = &$objects['contribution']; - $memberships = &$objects['membership']; - if (is_numeric($memberships)) { - $memberships = array($objects['membership']); + $memberships = []; + if (!empty($objects['membership'])) { + $memberships = &$objects['membership']; + if (is_numeric($memberships)) { + $memberships = [$objects['membership']]; + } } - $participant = &$objects['participant']; $addLineItems = FALSE; if (empty($contribution->id)) { $addLineItems = TRUE; } - $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); + $participant = &$objects['participant']; + + // CRM-15546 + $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [ + 'labelColumn' => 'name', + 'flip' => 1, + ]); $contribution->contribution_status_id = $contributionStatuses['Cancelled']; - $contribution->cancel_date = self::$_now; - $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input); $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); + $contribution->cancel_date = self::$_now; + $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input); $contribution->save(); - //add lineitems for recurring payments + // Add line items for recurring payments. if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) { CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution); } @@ -342,37 +340,19 @@ public function cancelled(&$objects, &$transaction, $input = array()) { if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { if (!empty($memberships)) { - $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); - // Cancel only Pending memberships - // CRM-18688 - $pendingStatusId = $membershipStatuses['Pending']; foreach ($memberships as $membership) { - if ($membership && ($membership->status_id == $pendingStatusId)) { - $membership->status_id = $membershipStatuses['Cancelled']; - $membership->save(); - - //update related Memberships. - $params = array('status_id' => $membershipStatuses['Cancelled']); - CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params); + if ($membership) { + $this->cancelMembership($membership, $membership->status_id); } } } if ($participant) { - $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array( - 'labelColumn' => 'name', - 'flip' => 1, - )); - $participant->status_id = $participantStatuses['Cancelled']; - $participant->save(); + $this->cancelParticipant($participant->id); } } $transaction->commit(); - CRM_Core_Error::debug_log_message("Setting contribution status to cancelled"); - //echo "Success: Setting contribution status to cancelled
"; + Civi::log()->debug("Setting contribution status to Cancelled"); return TRUE; } @@ -386,11 +366,60 @@ public function cancelled(&$objects, &$transaction, $input = array()) { */ public function unhandled(&$objects, &$transaction) { $transaction->rollback(); - CRM_Core_Error::debug_log_message("returning since contribution status: is not handled"); + Civi::log()->debug("Returning since contribution status is not handled"); echo "Failure: contribution status is not handled
"; return FALSE; } + /** + * Logic to cancel a participant record when the related contribution changes to failed/cancelled. + * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel() + * + * @param $participantID + * + * @throws \CiviCRM_API3_Exception + */ + private function cancelParticipant($participantID) { + // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it + $participantParams['id'] = $participantID; + $participantParams['status_id'] = 'Cancelled'; + civicrm_api3('Participant', 'create', $participantParams); + } + + /** + * Logic to cancel a membership record when the related contribution changes to failed/cancelled. + * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel() + * @param \CRM_Member_BAO_Membership $membership + * @param int $membershipStatusID + * @param boolean $onlyCancelPendingMembership + * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688) + * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now. + * + */ + private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) { + // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it + // Cancel only Pending memberships + $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending'); + if (($membershipStatusID == $pendingMembershipStatusId) || ($onlyCancelPendingMembership == FALSE)) { + $cancelledMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled'); + + $membership->status_id = $cancelledMembershipStatusId; + $membership->save(); + + $params = ['status_id' => $cancelledMembershipStatusId]; + CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params); + + // @todo Convert the above to API + // $membershipParams = [ + // 'id' => $membership->id, + // 'status_id' => $cancelledMembershipStatusId, + // ]; + // civicrm_api3('Membership', 'create', $membershipParams); + // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]); + } + + } + /** * @deprecated * @@ -413,7 +442,7 @@ public function unhandled(&$objects, &$transaction) { * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those. * - * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo + * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with * a shared function that updates related components. * @@ -445,6 +474,9 @@ public function unhandled(&$objects, &$transaction) { * @param array $objects * @param CRM_Core_Transaction $transaction * @param bool $recur + * + * @throws \CRM_Core_Exception + * @throws \CiviCRM_API3_Exception */ public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { $contribution = &$objects['contribution']; @@ -462,7 +494,7 @@ public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $r public function getBillingID(&$ids) { $ids['billing'] = CRM_Core_BAO_LocationType::getBilling(); if (!$ids['billing']) { - CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing'))); + CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing'])); echo "Failure: Could not find billing location type
";
return FALSE;
}
@@ -491,6 +523,8 @@ public function getBillingID(&$ids) {
* is because the function is also used to generate pdfs
*
* @return array
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
diff --git a/CRM/Core/Payment/Dummy.php b/CRM/Core/Payment/Dummy.php
index 1d68efe86812..717c4f3c6fb8 100644
--- a/CRM/Core/Payment/Dummy.php
+++ b/CRM/Core/Payment/Dummy.php
@@ -14,6 +14,8 @@
* $Id: Dummy.php 45429 2013-02-06 22:11:18Z lobo $
*/
+use Civi\Payment\Exception\PaymentProcessorException;
+
/**
* Dummy payment processor
*/
@@ -22,8 +24,8 @@ class CRM_Core_Payment_Dummy extends CRM_Core_Payment {
protected $_mode = NULL;
- protected $_params = array();
- protected $_doDirectPaymentResult = array();
+ protected $_params = [];
+ protected $_doDirectPaymentResult = [];
/**
* Set result from do Direct Payment for test purposes.
@@ -34,7 +36,7 @@ class CRM_Core_Payment_Dummy extends CRM_Core_Payment {
public function setDoDirectPaymentResult($doDirectPaymentResult) {
$this->_doDirectPaymentResult = $doDirectPaymentResult;
if (empty($this->_doDirectPaymentResult['trxn_id'])) {
- $this->_doDirectPaymentResult['trxn_id'] = array();
+ $this->_doDirectPaymentResult['trxn_id'] = [];
}
else {
$this->_doDirectPaymentResult['trxn_id'] = (array) $doDirectPaymentResult['trxn_id'];
@@ -73,6 +75,7 @@ public function __construct($mode, &$paymentProcessor) {
*
* @return array
* the result in a nice formatted array (or an error object)
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doDirectPayment(&$params) {
// Invoke hook_civicrm_paymentProcessor
@@ -99,21 +102,24 @@ public function doDirectPayment(&$params) {
//end of hook invocation
if (!empty($this->_doDirectPaymentResult)) {
$result = $this->_doDirectPaymentResult;
+ if (CRM_Utils_Array::value('payment_status_id', $result) === 'failed') {
+ throw new PaymentProcessorException($result['message'] ?? 'failed');
+ }
$result['trxn_id'] = array_shift($this->_doDirectPaymentResult['trxn_id']);
return $result;
}
if ($this->_mode == 'test') {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test\\_%'";
- $p = array();
- $trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
+ $p = [];
+ $trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p));
$trxn_id = str_replace('test_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
$params['trxn_id'] = 'test_' . $trxn_id . '_' . uniqid();
}
else {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'live_%'";
- $p = array();
- $trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
+ $p = [];
+ $trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p));
$trxn_id = str_replace('live_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
$params['trxn_id'] = 'live_' . $trxn_id . '_' . uniqid();
@@ -137,6 +143,33 @@ protected function supportsLiveMode() {
return TRUE;
}
+ /**
+ * Does this payment processor support refund?
+ *
+ * @return bool
+ */
+ public function supportsRefund() {
+ return TRUE;
+ }
+
+ /**
+ * Supports altering future start dates
+ * @return bool
+ */
+ public function supportsFutureRecurStartDate() {
+ return TRUE;
+ }
+
+ /**
+ * Submit a refund payment
+ *
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
+ *
+ * @param array $params
+ * Assoc array of input parameters for this transaction.
+ */
+ public function doRefund(&$params) {}
+
/**
* Generate error object.
*
@@ -195,7 +228,17 @@ public function checkConfig() {
* @return array
*/
public function getEditableRecurringScheduleFields() {
- return array('amount', 'next_sched_contribution_date');
+ return ['amount', 'next_sched_contribution_date'];
+ }
+
+ /**
+ * @param string $message
+ * @param array $params
+ *
+ * @return bool|object
+ */
+ public function cancelSubscription(&$message = '', $params = []) {
+ return TRUE;
}
}
diff --git a/CRM/Core/Payment/Elavon.php b/CRM/Core/Payment/Elavon.php
index b322859fe877..d0c4bbccfbd3 100644
--- a/CRM/Core/Payment/Elavon.php
+++ b/CRM/Core/Payment/Elavon.php
@@ -1,7 +1,7 @@
_mode == 'test') {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test%'";
- $p = array();
- $trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
+ $p = [];
+ $trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p));
$trxn_id = str_replace('test', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
$params['trxn_id'] = sprintf('test%08d', $trxn_id);
@@ -287,7 +287,7 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
*
*/
public function checkConfig() {
- $errorMsg = array();
+ $errorMsg = [];
if (empty($this->_paymentProcessor['user_name'])) {
$errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor');
@@ -343,7 +343,13 @@ public function buildXML($requestFields) {
$xml = '
" . CRM_Utils_Type::escape($name, 'String'); - exit(); + throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name"); } return $value; } /** - * @param $input - * @param $ids - * @param $objects - * @param $first + * @param array $input + * @param array $ids + * @param array $objects + * @param bool $first + * + * @return void * - * @return bool + * @throws \CRM_Core_Exception + * @throws \CiviCRM_API3_Exception */ public function recur(&$input, &$ids, &$objects, $first) { if (!isset($input['txnType'])) { - CRM_Core_Error::debug_log_message("Could not find txn_type in input request"); + Civi::log()->debug('PayPalIPN: Could not find txn_type in input request'); echo "Failure: Invalid parameters
"; - return FALSE; + return; } if ($input['txnType'] == 'subscr_payment' && $input['paymentStatus'] != 'Completed' ) { - CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed"); + Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed'); echo "Failure: Invalid parameters
"; - return FALSE; + return; } $recur = &$objects['contributionRecur']; @@ -110,15 +108,15 @@ public function recur(&$input, &$ids, &$objects, $first) { // make sure the invoice ids match // make sure the invoice is valid and matches what we have in the contribution record if ($recur->invoice_id != $input['invoice']) { - CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request"); + Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').'); echo "Failure: Invoice values dont match between database and IPN request
"; - return FALSE; + return; } $now = date('YmdHis'); // fix dates that already exist - $dates = array('create', 'start', 'end', 'cancel', 'modified'); + $dates = ['create', 'start', 'end', 'cancel', 'modified']; foreach ($dates as $date) { $name = "{$date}_date"; if ($recur->$name) { @@ -127,18 +125,19 @@ public function recur(&$input, &$ids, &$objects, $first) { } $sendNotification = FALSE; $subscriptionPaymentStatus = NULL; - //set transaction type + // set transaction type $txnType = $this->retrieve('txn_type', 'String'); + $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate')); switch ($txnType) { case 'subscr_signup': $recur->create_date = $now; - //some times subscr_signup response come after the - //subscr_payment and set to pending mode. + // sometimes subscr_signup response come after the subscr_payment and set to pending mode. + $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $recur->id, 'contribution_status_id' ); - if ($statusID != 5) { - $recur->contribution_status_id = 2; + if ($statusID != $contributionStatuses['In Progress']) { + $recur->contribution_status_id = $contributionStatuses['Pending']; } $recur->processor_id = $this->retrieve('subscr_id', 'String'); $recur->trxn_id = $recur->processor_id; @@ -147,8 +146,8 @@ public function recur(&$input, &$ids, &$objects, $first) { break; case 'subscr_eot': - if ($recur->contribution_status_id != 3) { - $recur->contribution_status_id = 1; + if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) { + $recur->contribution_status_id = $contributionStatuses['Completed']; } $recur->end_date = $now; $sendNotification = TRUE; @@ -156,19 +155,19 @@ public function recur(&$input, &$ids, &$objects, $first) { break; case 'subscr_cancel': - $recur->contribution_status_id = 3; + $recur->contribution_status_id = $contributionStatuses['Cancelled']; $recur->cancel_date = $now; break; case 'subscr_failed': - $recur->contribution_status_id = 4; + $recur->contribution_status_id = $contributionStatuses['Failed']; $recur->modified_date = $now; break; case 'subscr_modify': - CRM_Core_Error::debug_log_message("We do not handle modifications to subscriptions right now"); + Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').'); echo "Failure: We do not handle modifications to subscriptions right now
"; - return FALSE; + return; case 'subscr_payment': if ($first) { @@ -180,8 +179,8 @@ public function recur(&$input, &$ids, &$objects, $first) { // make sure the contribution status is not done // since order of ipn's is unknown - if ($recur->contribution_status_id != 1) { - $recur->contribution_status_id = 5; + if ($recur->contribution_status_id != $contributionStatuses['Completed']) { + $recur->contribution_status_id = $contributionStatuses['In Progress']; } break; } @@ -189,7 +188,6 @@ public function recur(&$input, &$ids, &$objects, $first) { $recur->save(); if ($sendNotification) { - $autoRenewMembership = FALSE; if ($recur->id && isset($ids['membership']) && $ids['membership'] @@ -211,27 +209,28 @@ public function recur(&$input, &$ids, &$objects, $first) { } if (!$first) { - //check if this contribution transaction is already processed - //if not create a contribution and then get it processed + // check if this contribution transaction is already processed + // if not create a contribution and then get it processed $contribution = new CRM_Contribute_BAO_Contribution(); $contribution->trxn_id = $input['trxn_id']; if ($contribution->trxn_id && $contribution->find()) { - CRM_Core_Error::debug_log_message("returning since contribution has already been handled"); + Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')'); echo "Success: Contribution has already been handled
"; - return TRUE; + return; } - $contribution->contact_id = $ids['contact']; - $contribution->financial_type_id = $objects['contributionType']->id; - $contribution->contribution_page_id = $ids['contributionPage']; - $contribution->contribution_recur_id = $ids['contributionRecur']; - $contribution->receive_date = $now; - $contribution->currency = $objects['contribution']->currency; - $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id; - $contribution->amount_level = $objects['contribution']->amount_level; - $contribution->campaign_id = $objects['contribution']->campaign_id; - - $objects['contribution'] = &$contribution; + if ($input['paymentStatus'] != 'Completed') { + throw new CRM_Core_Exception("Ignore all IPN payments that are not completed"); + } + + // In future moving to create pending & then complete, but this OK for now. + // Also consider accepting 'Failed' like other processors. + $input['contribution_status_id'] = $contributionStatuses['Completed']; + $input['original_contribution_id'] = $ids['contribution']; + $input['contribution_recur_id'] = $ids['contributionRecur']; + + civicrm_api3('Contribution', 'repeattransaction', $input); + return; } $this->single($input, $ids, $objects, @@ -240,27 +239,23 @@ public function recur(&$input, &$ids, &$objects, $first) { } /** - * @param $input - * @param $ids - * @param $objects + * @param array $input + * @param array $ids + * @param array $objects * @param bool $recur * @param bool $first * - * @return bool + * @return void */ - public function single( - &$input, &$ids, &$objects, - $recur = FALSE, - $first = FALSE - ) { + public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) { $contribution = &$objects['contribution']; // make sure the invoice is valid and matches what we have in the contribution record if ((!$recur) || ($recur && $first)) { if ($contribution->invoice_id != $input['invoice']) { - CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request"); + Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').'); echo "Failure: Invoice values dont match between database and IPN request
"; - return FALSE; + return; } } else { @@ -269,9 +264,9 @@ public function single( if (!$recur) { if ($contribution->total_amount != $input['amount']) { - CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request"); + Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').'); echo "Failure: Amount values dont match between database and IPN request
"; - return FALSE; + return; } } else { @@ -280,9 +275,6 @@ public function single( $transaction = new CRM_Core_Transaction(); - $participant = &$objects['participant']; - $membership = &$objects['membership']; - $status = $input['paymentStatus']; if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') { return $this->failed($objects, $transaction); @@ -298,11 +290,12 @@ public function single( } // check if contribution is already completed, if so we ignore this ipn - if ($contribution->contribution_status_id == 1) { + $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); + if ($contribution->contribution_status_id == $completedStatusId) { $transaction->commit(); - CRM_Core_Error::debug_log_message("returning since contribution has already been handled"); + Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').'); echo "Success: Contribution has already been handled
"; - return TRUE; + return; } $this->completeTransaction($input, $ids, $objects, $transaction, $recur); @@ -311,16 +304,18 @@ public function single( /** * Main function. * - * @return bool + * @throws \CRM_Core_Exception + * @throws \CiviCRM_API3_Exception */ public function main() { - - $objects = $ids = $input = array(); + $objects = $ids = $input = []; $component = $this->retrieve('module', 'String'); $input['component'] = $component; $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE); - $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE); + $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE); + $membershipID = $this->retrieve('membershipID', 'Integer', FALSE); + $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE); $this->getInput($input, $ids); @@ -330,30 +325,51 @@ public function main() { } else { // get the optional ids - $ids['membership'] = $this->retrieve('membershipID', 'Integer', FALSE); - $ids['contributionRecur'] = $this->retrieve('contributionRecurID', 'Integer', FALSE); + $ids['membership'] = $membershipID; + $ids['contributionRecur'] = $contributionRecurID; $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE); $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE); $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE); } - $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE); - if (empty($paymentProcessorID)) { - $processorParams = array( - 'user_name' => $this->retrieve('business', 'String', FALSE), - 'payment_processor_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name'), - 'is_test' => empty($input['is_test']) ? 0 : 1, + $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids); + + Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').'); + + // Debugging related to possible missing membership linkage + if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) { + $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecurID); + $membershipPayment = civicrm_api3('MembershipPayment', 'get', [ + 'contribution_id' => $templateContribution['id'], + 'membership_id' => $membershipID, + ]); + $lineItems = civicrm_api3('LineItem', 'get', [ + 'contribution_id' => $templateContribution['id'], + 'entity_id' => $membershipID, + 'entity_table' => 'civicrm_membership', + ]); + Civi::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID + . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is ' + . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count'] + . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.' + . ' it is expected the original contribution will be linked by both entities to the membership.' ); - - $processorInfo = array(); - if (!CRM_Financial_BAO_PaymentProcessor::retrieve($processorParams, $processorInfo)) { - return FALSE; + if (empty($membershipPayment['count']) && empty($lineItems['count'])) { + Civi::log()->debug('PayPalIPN: Will attempt to compensate'); + $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE); + } + if ($contributionRecurID) { + $recurLinks = civicrm_api3('ContributionRecur', 'get', [ + 'membership_id' => $membershipID, + 'contribution_recur_id' => $contributionRecurID, + ]); + Civi::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID + . ' ' . $recurLinks['count'] . 'links found' + ); } - $paymentProcessorID = $processorInfo['id']; } - if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) { - return FALSE; + return; } self::$_paymentProcessor = &$objects['paymentProcessor']; @@ -361,29 +377,26 @@ public function main() { if ($ids['contributionRecur']) { // check if first contribution is completed, else complete first contribution $first = TRUE; - if ($objects['contribution']->contribution_status_id == 1) { + $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); + if ($objects['contribution']->contribution_status_id == $completedStatusId) { $first = FALSE; } - return $this->recur($input, $ids, $objects, $first); + $this->recur($input, $ids, $objects, $first); + return; } - else { - return $this->single($input, $ids, $objects, FALSE, FALSE); - } - } - else { - return $this->single($input, $ids, $objects, FALSE, FALSE); } + $this->single($input, $ids, $objects, FALSE, FALSE); } /** - * @param $input - * @param $ids + * @param array $input + * @param array $ids * - * @return bool + * @throws \CRM_Core_Exception */ public function getInput(&$input, &$ids) { if (!$this->getBillingID($ids)) { - return FALSE; + return; } $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE); @@ -393,7 +406,7 @@ public function getInput(&$input, &$ids) { $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE); $billingID = $ids['billing']; - $lookup = array( + $lookup = [ "first_name" => 'first_name', "last_name" => 'last_name', "street_address-{$billingID}" => 'address_street', @@ -401,7 +414,7 @@ public function getInput(&$input, &$ids) { "state-{$billingID}" => 'address_state', "postal_code-{$billingID}" => 'address_zip', "country-{$billingID}" => 'address_country_code', - ); + ]; foreach ($lookup as $name => $paypalName) { $value = $this->retrieve($paypalName, 'String', FALSE); $input[$name] = $value ? $value : NULL; @@ -411,6 +424,67 @@ public function getInput(&$input, &$ids) { $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE); $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE); $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE); + + $paymentDate = $this->retrieve('payment_date', 'String', FALSE); + if (!empty($paymentDate)) { + $receiveDateTime = new DateTime($paymentDate); + /** + * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST + * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system + */ + $input['receive_date'] = CRM_Utils_Date::convertDateToLocalTime($receiveDateTime); + } + } + + /** + * Gets PaymentProcessorID for PayPal + * + * @param array $input + * @param array $ids + * + * @return int + * @throws \CRM_Core_Exception + * @throws \CiviCRM_API3_Exception + */ + public function getPayPalPaymentProcessorID($input, $ids) { + // First we try and retrieve from POST params + $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE); + if (!empty($paymentProcessorID)) { + return $paymentProcessorID; + } + + // Then we try and get it from recurring contribution ID + if (!empty($ids['contributionRecur'])) { + $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [ + 'id' => $ids['contributionRecur'], + 'return' => ['payment_processor_id'], + ]); + if (!empty($contributionRecur['payment_processor_id'])) { + return $contributionRecur['payment_processor_id']; + } + } + + // This is an unreliable method as there could be more than one instance. + // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment + // processor id & the handleNotification function (which should call the completetransaction api & by-pass this + // entirely). The only thing the IPN class should really do is extract data from the request, validate it + // & call completetransaction or call fail? (which may not exist yet). + + Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal IPN - this will cause problems if you have more than one instance'); + // Then we try and retrieve based on business email ID + $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name'); + $processorParams = [ + 'user_name' => $this->retrieve('business', 'String', FALSE), + 'payment_processor_type_id' => $paymentProcessorTypeID, + 'is_test' => empty($input['is_test']) ? 0 : 1, + 'options' => ['limit' => 1], + 'return' => ['id'], + ]; + $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams); + if (empty($paymentProcessorID)) { + throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID'); + } + return $paymentProcessorID; } } diff --git a/CRM/Core/Payment/PayPalImpl.php b/CRM/Core/Payment/PayPalImpl.php index 427477386ef1..905e369a61b7 100644 --- a/CRM/Core/Payment/PayPalImpl.php +++ b/CRM/Core/Payment/PayPalImpl.php @@ -1,9 +1,9 @@ _mode = $mode; $this->_paymentProcessor = $paymentProcessor; - $this->_processorName = ts('PayPal Pro'); - $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name'); - if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) { + if ($this->isPayPalType($this::PAYPAL_STANDARD)) { $this->_processorName = ts('PayPal Standard'); - return; } - elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) { + elseif ($this->isPayPalType($this::PAYPAL_EXPRESS)) { $this->_processorName = ts('PayPal Express'); } + elseif ($this->isPayPalType($this::PAYPAL_PRO)) { + $this->_processorName = ts('PayPal Pro'); + } + else { + throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!'); + } + } + /** + * Helper function to check which payment processor type is being used. + * + * @param $typeName + * + * @return bool + * @throws \Civi\Payment\Exception\PaymentProcessorException + */ + public function isPayPalType($typeName) { + // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id + if (empty($this->_paymentProcessor['payment_processor_type_id']) && empty($this->_paymentProcessor['payment_processor_type'])) { + // We need one of them to be set! + throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!'); + } + if (empty($this->_paymentProcessor['payment_processor_type_id']) && !empty($this->_paymentProcessor['payment_processor_type'])) { + // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not. + $this->_paymentProcessor['payment_processor_type_id'] + = CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor['payment_processor_type']); + } + if ((int) $this->_paymentProcessor['payment_processor_type_id'] === + CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) { + return TRUE; + } + return FALSE; } /** @@ -74,9 +107,10 @@ public function __construct($mode, &$paymentProcessor) { * with someone else's login. * * @return bool + * @throws \Civi\Payment\Exception\PaymentProcessorException */ protected function supportsBackOffice() { - if ($this->_processorName == ts('PayPal Pro')) { + if ($this->isPayPalType($this::PAYPAL_PRO)) { return TRUE; } return FALSE; @@ -92,9 +126,10 @@ protected function supportsBackOffice() { * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do. * * @return bool + * @throws \Civi\Payment\Exception\PaymentProcessorException */ protected function supportsPreApproval() { - if ($this->_processorName == ts('PayPal Express') || $this->_processorName == ts('PayPal Pro')) { + if ($this->isPayPalType($this::PAYPAL_EXPRESS) || $this->isPayPalType($this::PAYPAL_PRO)) { return TRUE; } return FALSE; @@ -107,20 +142,21 @@ protected function supportsPreApproval() { * * @return bool * Should form building stop at this point? + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function buildForm(&$form) { - if ($this->_processorName == 'PayPal Express' || $this->_processorName == 'PayPal Pro') { + if ($this->supportsPreApproval()) { $this->addPaypalExpressCode($form); - if ($this->_processorName == 'PayPal Express') { - CRM_Core_Region::instance('billing-block-post')->add(array( + if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { + CRM_Core_Region::instance('billing-block-post')->add([ 'template' => 'CRM/Financial/Form/PaypalExpress.tpl', 'name' => 'paypal_express', - )); + ]); } - if ($this->_processorName == 'PayPal Pro') { - CRM_Core_Region::instance('billing-block-pre')->add(array( + if ($this->isPayPalType($this::PAYPAL_PRO)) { + CRM_Core_Region::instance('billing-block-pre')->add([ 'template' => 'CRM/Financial/Form/PaypalPro.tpl', - )); + ]); } } return FALSE; @@ -139,13 +175,25 @@ public function buildForm(&$form) { protected function addPaypalExpressCode(&$form) { // @todo use $this->isBackOffice() instead, test. if (empty($form->isBackOffice)) { - $form->_expressButtonName = $form->getButtonName('upload', 'express'); + + /** + * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment', + * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name + * and then clicking on express button it redirect to confirm screen rather than PayPal Express form + */ + + if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName) { + $form->_expressButtonName = '_qf_' . $form->_formName . '_upload_express'; + } + else { + $form->_expressButtonName = $form->getButtonName('upload', 'express'); + } $form->assign('expressButtonName', $form->_expressButtonName); $form->add( 'image', $form->_expressButtonName, $this->_paymentProcessor['url_button'], - array('class' => 'crm-form-submit') + ['class' => 'crm-form-submit'] ); } } @@ -174,9 +222,11 @@ protected function supportsRecurContributionsForPledges() { * * @param array $values * @param array $errors + * + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function validatePaymentInstrument($values, &$errors) { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) { + if ($this->isPayPalType($this::PAYPAL_PRO) && !$this->isPaypalExpress($values)) { CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']); CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors); } @@ -195,7 +245,7 @@ public function validatePaymentInstrument($values, &$errors) { * @throws \Civi\Payment\Exception\PaymentProcessorException */ protected function setExpressCheckOut(&$params) { - $args = array(); + $args = []; $this->initialize($args, 'SetExpressCheckout'); @@ -239,9 +289,10 @@ protected function setExpressCheckOut(&$params) { * @param array $storedDetails * * @return array + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function getPreApprovalDetails($storedDetails) { - return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']); + return empty($storedDetails['token']) ? [] : $this->getExpressCheckoutDetails($storedDetails['token']); } /** @@ -254,9 +305,10 @@ public function getPreApprovalDetails($storedDetails) { * * @return array * the result in an nice formatted array (or an error object) + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function getExpressCheckoutDetails($token) { - $args = array(); + $args = []; $this->initialize($args, 'GetExpressCheckoutDetails'); $args['token'] = $token; @@ -270,7 +322,7 @@ public function getExpressCheckoutDetails($token) { } /* Success */ - $fieldMap = array( + $fieldMap = [ 'token' => 'token', 'payer_status' => 'payerstatus', 'payer_id' => 'payerid', @@ -283,7 +335,7 @@ public function getExpressCheckoutDetails($token) { 'postal_code' => 'shiptozip', 'state_province' => 'shiptostate', 'country' => 'shiptocountrycode', - ); + ]; return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result); } @@ -300,11 +352,10 @@ public function getExpressCheckoutDetails($token) { * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function doExpressCheckout(&$params) { - $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id'); if (!empty($params['is_recur'])) { return $this->createRecurringPayments($params); } - $args = array(); + $args = []; $this->initialize($args, 'DoExpressCheckoutPayment'); $args['token'] = $params['token']; @@ -327,7 +378,6 @@ public function doExpressCheckout(&$params) { } /* Success */ - $params['trxn_id'] = $result['transactionid']; $params['gross_amount'] = $result['amt']; $params['fee_amount'] = $result['feeamt']; @@ -339,10 +389,10 @@ public function doExpressCheckout(&$params) { $params['pending_reason'] = $result['pendingreason']; if (!empty($params['is_recur'])) { // See comment block. - $params['payment_status_id'] = array_search('Pending', $statuses); + $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'); } else { - $params['payment_status_id'] = array_search('Completed', $statuses); + $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); } return $params; } @@ -350,13 +400,16 @@ public function doExpressCheckout(&$params) { /** * Create recurring payments. * + * Use a pre-authorisation token to activate a recurring payment profile + * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/ + * * @param array $params * * @return mixed + * @throws \Exception */ public function createRecurringPayments(&$params) { - $args = array(); - // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result) + $args = []; $this->initialize($args, 'CreateRecurringPaymentsProfile'); $start_time = strtotime(date('m/d/Y')); @@ -368,15 +421,12 @@ public function createRecurringPayments(&$params) { $args['currencyCode'] = $params['currencyID']; $args['payerID'] = $params['payer_id']; $args['invnum'] = $params['invoiceID']; - $args['returnURL'] = $params['returnURL']; - $args['cancelURL'] = $params['cancelURL']; $args['profilestartdate'] = $start_date; $args['method'] = 'CreateRecurringPaymentsProfile'; $args['billingfrequency'] = $params['frequency_interval']; $args['billingperiod'] = ucwords($params['frequency_unit']); $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit']; - //$args['desc'] = 'Recurring Contribution'; - $args['totalbillingcycles'] = $params['installments']; + $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params); $args['version'] = '56.0'; $args['profilereference'] = "i={$params['invoiceID']}" . "&m=" . @@ -394,16 +444,18 @@ public function createRecurringPayments(&$params) { return $result; } - /* Success */ - $params['trxn_id'] = $result['transactionid']; - $params['gross_amount'] = $result['amt']; - $params['fee_amount'] = $result['feeamt']; - $params['net_amount'] = $result['settleamt']; - if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) { - $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2); - } - $params['payment_status'] = $result['paymentstatus']; - $params['pending_reason'] = $result['pendingreason']; + /* Success - result looks like" + * array ( + * 'profileid' => 'I-CP1U0PLG91R2', + * 'profilestatus' => 'ActiveProfile', + * 'timestamp' => '2018-05-07T03:55:52Z', + * 'correlationid' => 'e717999e9bf62', + * 'ack' => 'Success', + * 'version' => '56.0', + * 'build' => '39949200',) + */ + $params['trxn_id'] = $result['profileid']; + $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'); return $params; } @@ -424,7 +476,7 @@ public function initialize(&$args, $method) { } /** - * Process payment - this function wraps around both doTransferPayment and doDirectPayment. + * Process payment - this function wraps around both doTransferCheckout and doDirectPayment. * * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms * more agnostic. @@ -449,9 +501,7 @@ public function initialize(&$args, $method) { * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function doPayment(&$params, $component = 'contribute') { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express' - || ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !empty($params['token'])) - ) { + if ($this->isPayPalType($this::PAYPAL_EXPRESS) || ($this->isPayPalType($this::PAYPAL_PRO) && !empty($params['token']))) { $this->_component = $component; return $this->doExpressCheckout($params); @@ -469,15 +519,16 @@ public function doPayment(&$params, $component = 'contribute') { * @param string $component * @return array * the result in an nice formatted array (or an error object) + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function doDirectPayment(&$params, $component = 'contribute') { - $args = array(); + $args = []; $this->initialize($args, 'DoDirectPayment'); $args['paymentAction'] = 'Sale'; - $args['amt'] = $params['amount']; - $args['currencyCode'] = $params['currencyID']; + $args['amt'] = $this->getAmount($params); + $args['currencyCode'] = $this->getCurrency($params); $args['invnum'] = $params['invoiceID']; $args['ipaddress'] = $params['ip_address']; $args['creditCardType'] = $params['credit_card_type']; @@ -512,7 +563,7 @@ public function doDirectPayment(&$params, $component = 'contribute') { $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit']; - $args['amt'] = $params['amount']; + $args['amt'] = $this->getAmount($params); $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params); $args['version'] = 56.0; $args['PROFILEREFERENCE'] = "" . @@ -526,7 +577,7 @@ public function doDirectPayment(&$params, $component = 'contribute') { $result = $this->invokeAPI($args); - //WAG + // WAG if (is_a($result, 'CRM_Core_Error')) { return $result; } @@ -566,33 +617,33 @@ public function doDirectPayment(&$params, $component = 'contribute') { public function doQuery($params) { //CRM-18140 - trxn_id not returned for recurring paypal transaction if (!empty($params['is_recur'])) { - return array(); + return []; } elseif (empty($params['trxn_id'])) { throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set'); } - $args = array( + $args = [ 'TRANSACTIONID' => $params['trxn_id'], - ); + ]; $this->initialize($args, 'GetTransactionDetails'); $result = $this->invokeAPI($args); - return array( + return [ 'fee_amount' => $result['feeamt'], 'net_amount' => $params['gross_amount'] - $result['feeamt'], - ); + ]; } /** * This function checks to see if we have the right config values. * - * @return string + * @return null|string * the error message if any + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function checkConfig() { - $error = array(); - $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name'); + $error = []; - if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) { + if (!$this->isPayPalType($this::PAYPAL_STANDARD)) { if (empty($this->_paymentProcessor['signature'])) { $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.'); } @@ -615,9 +666,10 @@ public function checkConfig() { /** * @return null|string + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function cancelSubscriptionURL() { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') { + if ($this->isPayPalType($this::PAYPAL_STANDARD)) { return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']); } else { @@ -632,9 +684,10 @@ public function cancelSubscriptionURL() { * Method to check for. * * @return bool + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function isSupported($method) { - if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') { + if (!$this->isPayPalType($this::PAYPAL_PRO)) { // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported // by standard or express. return FALSE; @@ -647,9 +700,10 @@ public function isSupported($method) { * * @return bool * Should the form button by suppressed? + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function isSuppressSubmitButtons() { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') { + if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { return TRUE; } return FALSE; @@ -660,10 +714,11 @@ public function isSuppressSubmitButtons() { * @param array $params * * @return array|bool|object + * @throws \Civi\Payment\Exception\PaymentProcessorException */ - public function cancelSubscription(&$message = '', $params = array()) { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') { - $args = array(); + public function cancelSubscription(&$message = '', $params = []) { + if ($this->isPayPalType($this::PAYPAL_PRO) || $this->isPayPalType($this::PAYPAL_EXPRESS)) { + $args = []; $this->initialize($args, 'ManageRecurringPaymentsProfileStatus'); $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params); @@ -682,23 +737,44 @@ public function cancelSubscription(&$message = '', $params = array()) { /** * Process incoming notification. + * + * @throws \CRM_Core_Exception + * @throws \CiviCRM_API3_Exception */ - static public function handlePaymentNotification() { + public static function handlePaymentNotification() { $params = array_merge($_GET, $_REQUEST); $q = explode('/', CRM_Utils_Array::value('q', $params, '')); $lastParam = array_pop($q); if (is_numeric($lastParam)) { $params['processor_id'] = $lastParam; } - if (civicrm_api3('PaymentProcessor', 'getvalue', array( - 'id' => $params['processor_id'], - 'return' => 'class_name') - ) == 'Payment_PayPalImpl') { - $paypalIPN = new CRM_Core_Payment_PayPalIPN($params); + $result = civicrm_api3('PaymentProcessor', 'get', [ + 'sequential' => 1, + 'id' => $params['processor_id'], + 'api.PaymentProcessorType.getvalue' => ['return' => "name"], + ]); + if (!$result['count']) { + throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'."); } - else { - $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params); + + $paymentProcessorType = CRM_Utils_Array::value('api.PaymentProcessorType.getvalue', $result['values'][0]); + switch ($paymentProcessorType) { + case 'PayPal': + // "PayPal - Website Payments Pro" + $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params); + break; + + case 'PayPal_Standard': + // "PayPal - Website Payments Standard" + $paypalIPN = new CRM_Core_Payment_PayPalIPN($params); + break; + + default: + // If we don't have PayPal Standard or PayPal Pro, something's wrong. + // Log an error and exit. + throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context."); } + $paypalIPN->main(); } @@ -707,15 +783,16 @@ static public function handlePaymentNotification() { * @param array $params * * @return array|bool|object + * @throws \Civi\Payment\Exception\PaymentProcessorException */ - public function updateSubscriptionBillingInfo(&$message = '', $params = array()) { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') { + public function updateSubscriptionBillingInfo(&$message = '', $params = []) { + if ($this->isPayPalType($this::PAYPAL_PRO)) { $config = CRM_Core_Config::singleton(); - $args = array(); + $args = []; $this->initialize($args, 'UpdateRecurringPaymentsProfile'); $args['PROFILEID'] = $params['subscriptionId']; - $args['AMT'] = $params['amount']; + $args['AMT'] = $this->getAmount($params); $args['CURRENCYCODE'] = $config->defaultCurrency; $args['CREDITCARDTYPE'] = $params['credit_card_type']; $args['ACCT'] = $params['credit_card_number']; @@ -745,15 +822,16 @@ public function updateSubscriptionBillingInfo(&$message = '', $params = array()) * @param array $params * * @return array|bool|object + * @throws \Civi\Payment\Exception\PaymentProcessorException */ - public function changeSubscriptionAmount(&$message = '', $params = array()) { - if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') { + public function changeSubscriptionAmount(&$message = '', $params = []) { + if ($this->isPayPalType($this::PAYPAL_PRO)) { $config = CRM_Core_Config::singleton(); - $args = array(); + $args = []; $this->initialize($args, 'UpdateRecurringPaymentsProfile'); $args['PROFILEID'] = $params['subscriptionId']; - $args['AMT'] = $params['amount']; + $args['AMT'] = $this->getAmount($params); $args['CURRENCYCODE'] = $config->defaultCurrency; $args['BILLINGFREQUENCY'] = $params['installments']; @@ -777,17 +855,18 @@ public function changeSubscriptionAmount(&$message = '', $params = array()) { * @return array * - pre_approval_parameters (this will be stored on the calling form & available later) * - redirect_url (if set the browser will be redirected to this. + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function doPreApproval(&$params) { if (!$this->isPaypalExpress($params)) { - return array(); + return []; } $this->_component = $params['component']; $token = $this->setExpressCheckOut($params); - return array( - 'pre_approval_parameters' => array('token' => $token), + return [ + 'pre_approval_parameters' => ['token' => $token], 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token", - ); + ]; } /** @@ -798,8 +877,8 @@ public function doPreApproval(&$params) { */ public function doTransferCheckout(&$params, $component = 'contribute') { - $notifyParameters = array('module' => $component); - $notifyParameterMap = array( + $notifyParameters = ['module' => $component]; + $notifyParameterMap = [ 'contactID' => 'contactID', 'contributionID' => 'contributionID', 'eventID' => 'eventID', @@ -810,7 +889,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') { 'accountingCode' => 'accountingCode', 'contributionRecurID' => 'contributionRecurID', 'contributionPageID' => 'contributionPageID', - ); + ]; foreach ($notifyParameterMap as $paramsName => $notifyName) { if (!empty($params[$paramsName])) { $notifyParameters[$notifyName] = $params[$paramsName]; @@ -833,7 +912,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') { TRUE, NULL, FALSE ); - $paypalParams = array( + $paypalParams = [ 'business' => $this->_paymentProcessor['user_name'], 'notify_url' => $notifyURL, 'item_name' => $this->getPaymentDescription($params, 127), @@ -850,10 +929,10 @@ public function doTransferCheckout(&$params, $component = 'contribute') { 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8', 'custom' => json_encode($notifyParameters), 'bn' => 'CiviCRM_SP', - ); + ]; // add name and address if available, CRM-3130 - $otherVars = array( + $otherVars = [ 'first_name' => 'first_name', 'last_name' => 'last_name', 'street_address' => 'address1', @@ -863,7 +942,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') { 'state_province' => 'state', 'postal_code' => 'zip', 'email' => 'email', - ); + ]; foreach (array_keys($params) as $p) { // get the base name without the location type suffixed to it @@ -895,9 +974,9 @@ public function doTransferCheckout(&$params, $component = 'contribute') { CRM_Core_Error::fatal(ts('Recurring contribution, but no database id')); } - $paypalParams += array( + $paypalParams += [ 'cmd' => '_xclick-subscriptions', - 'a3' => $params['amount'], + 'a3' => $this->getAmount($params), 'p3' => $params['frequency_interval'], 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)), 'src' => 1, @@ -905,13 +984,13 @@ public function doTransferCheckout(&$params, $component = 'contribute') { 'srt' => CRM_Utils_Array::value('installments', $params), 'no_note' => 1, 'modify' => 0, - ); + ]; } else { - $paypalParams += array( + $paypalParams += [ 'cmd' => '_xclick', 'amount' => $params['amount'], - ); + ]; } // Allow further manipulation of the arguments via custom hooks .. @@ -964,6 +1043,14 @@ public function invokeAPI($args, $url = NULL) { $url = $this->_paymentProcessor['url_api'] . 'nvp'; } + $p = []; + foreach ($args as $n => $v) { + $p[] = "$n=" . urlencode($v); + } + + //NVPRequest for submitting to server + $nvpreq = implode('&', $p); + if (!function_exists('curl_init')) { CRM_Core_Error::fatal("curl functions NOT available."); } @@ -980,14 +1067,6 @@ public function invokeAPI($args, $url = NULL) { curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); - $p = array(); - foreach ($args as $n => $v) { - $p[] = "$n=" . urlencode($v); - } - - //NVPRequest for submitting to server - $nvpreq = implode('&', $p); - //setting the nvpreq as POST FIELD to curl curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); @@ -1009,9 +1088,9 @@ public function invokeAPI($args, $url = NULL) { curl_close($ch); } - if (strtolower($result['ack']) != 'success' && - strtolower($result['ack']) != 'successwithwarning' - ) { + $outcome = strtolower(CRM_Utils_Array::value('ack', $result)); + + if ($outcome != 'success' && $outcome != 'successwithwarning') { throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}"); $e = CRM_Core_Error::singleton(); $e->push($result['l_errorcode0'], @@ -1034,7 +1113,7 @@ public function invokeAPI($args, $url = NULL) { * @return array */ public static function deformat($str) { - $result = array(); + $result = []; while (strlen($str)) { // position of key @@ -1060,14 +1139,14 @@ public static function deformat($str) { * Get array of fields that should be displayed on the payment form. * * @return array - * @throws CiviCRM_API3_Exception + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function getPaymentFormFields() { - if ($this->_processorName == ts('PayPal Pro')) { + if ($this->isPayPalType($this::PAYPAL_PRO)) { return $this->getCreditCardFormFields(); } else { - return array(); + return []; } } @@ -1080,7 +1159,7 @@ public function getPaymentFormFields() { * @return array */ protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) { - $params = array(); + $params = []; foreach ($fieldMap as $civicrmField => $paypalField) { $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL; } @@ -1095,9 +1174,10 @@ protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) { * @param array $params * * @return bool + * @throws \Civi\Payment\Exception\PaymentProcessorException */ protected function isPaypalExpress($params) { - if ($this->_processorName == ts('PayPal Express')) { + if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { return TRUE; } @@ -1111,10 +1191,10 @@ protected function isPaypalExpress($params) { // The contribution form passes a 'button' but the event form might still set one of these fields. // @todo more standardisation & get paypal fully out of the form layer. - $possibleExpressFields = array( + $possibleExpressFields = [ '_qf_Register_upload_express_x', '_qf_Payment_upload_express_x', - ); + ]; if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) { return TRUE; } diff --git a/CRM/Core/Payment/PayPalProIPN.php b/CRM/Core/Payment/PayPalProIPN.php index e557541c362f..0324019d9ff2 100644 --- a/CRM/Core/Payment/PayPalProIPN.php +++ b/CRM/Core/Payment/PayPalProIPN.php @@ -1,9 +1,9 @@ _inputParameters['rp_invoice_id']); // for clarify let's also store without the single letter unreadable //@todo after more refactoring we might ditch storing the one letter stuff - $mapping = array( + $mapping = [ 'i' => 'invoice_id', 'm' => 'component', 'c' => 'contact_id', @@ -111,7 +115,7 @@ public function setInvoiceData() { 'r' => 'contribution_recur_id', 'p' => 'participant_id', 'e' => 'event_id', - ); + ]; foreach ($rpInvoiceArray as $rpInvoiceValue) { $rpValueArray = explode('=', $rpInvoiceValue); $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1]; @@ -161,21 +165,13 @@ public function retrieve($name, $type, $location = 'POST', $abort = TRUE) { * @param array $ids * @param array $objects * @param bool $first - * @return bool + * @return void */ public function recur(&$input, &$ids, &$objects, $first) { if (!isset($input['txnType'])) { - CRM_Core_Error::debug_log_message("Could not find txn_type in input request"); - echo "Failure: Invalid parameters
"; - return FALSE; - } - - if ($input['txnType'] == 'recurring_payment' && - $input['paymentStatus'] != 'Completed' - ) { - CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed"); + Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.'); echo "Failure: Invalid parameters
"; - return FALSE; + return; } $recur = &$objects['contributionRecur']; @@ -184,15 +180,15 @@ public function recur(&$input, &$ids, &$objects, $first) { // make sure the invoice is valid and matches what we have in // the contribution record if ($recur->invoice_id != $input['invoice']) { - CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']); + Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']); echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']; - return FALSE; + return; } $now = date('YmdHis'); // fix dates that already exist - $dates = array('create', 'start', 'end', 'cancel', 'modified'); + $dates = ['create', 'start', 'end', 'cancel', 'modified']; foreach ($dates as $date) { $name = "{$date}_date"; if ($recur->$name) { @@ -219,21 +215,20 @@ public function recur(&$input, &$ids, &$objects, $first) { //set transaction type $txnType = $this->retrieve('txn_type', 'String'); //Changes for paypal pro recurring payment - $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id')); - $contributionStatuses = $contributionStatuses['values']; + $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate')); switch ($txnType) { case 'recurring_payment_profile_created': - if (in_array($recur->contribution_status_id, array( - array_search('Pending', $contributionStatuses), - array_search('In Progress', $contributionStatuses), - )) + if (in_array($recur->contribution_status_id, [ + $contributionStatuses['Pending'], + $contributionStatuses['In Progress'], + ]) && !empty($recur->processor_id) ) { echo "already handled"; - return FALSE; + return; } $recur->create_date = $now; - $recur->contribution_status_id = 2; + $recur->contribution_status_id = $contributionStatuses['Pending']; $recur->processor_id = $this->retrieve('recurring_payment_id', 'String'); $recur->trxn_id = $recur->processor_id; $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START; @@ -245,16 +240,28 @@ public function recur(&$input, &$ids, &$objects, $first) { $recur->start_date = $now; } else { - $recur->modified_date = $now; + if ($input['paymentStatus'] != 'Completed') { + throw new CRM_Core_Exception("Ignore all IPN payments that are not completed"); + } + + // In future moving to create pending & then complete, but this OK for now. + // Also consider accepting 'Failed' like other processors. + $input['contribution_status_id'] = $contributionStatuses['Completed']; + $input['invoice_id'] = md5(uniqid(rand(), TRUE)); + $input['original_contribution_id'] = $ids['contribution']; + $input['contribution_recur_id'] = $ids['contributionRecur']; + + civicrm_api3('Contribution', 'repeattransaction', $input); + return; } //contribution installment is completed if ($this->retrieve('profile_status', 'String') == 'Expired') { if (!empty($recur->end_date)) { echo "already handled"; - return FALSE; + return; } - $recur->contribution_status_id = 1; + $recur->contribution_status_id = $contributionStatuses['Completed']; $recur->end_date = $now; $sendNotification = TRUE; $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END; @@ -262,8 +269,8 @@ public function recur(&$input, &$ids, &$objects, $first) { // make sure the contribution status is not done // since order of ipn's is unknown - if ($recur->contribution_status_id != 1) { - $recur->contribution_status_id = 5; + if ($recur->contribution_status_id != $contributionStatuses['Completed']) { + $recur->contribution_status_id = $contributionStatuses['In Progress']; } break; } @@ -287,7 +294,7 @@ public function recur(&$input, &$ids, &$objects, $first) { } if ($txnType != 'recurring_payment') { - return TRUE; + return; } if (!$first) { @@ -296,9 +303,9 @@ public function recur(&$input, &$ids, &$objects, $first) { $contribution = new CRM_Contribute_BAO_Contribution(); $contribution->trxn_id = $input['trxn_id']; if ($contribution->trxn_id && $contribution->find()) { - CRM_Core_Error::debug_log_message("returning since contribution has already been handled"); + Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.'); echo "Success: Contribution has already been handled
"; - return TRUE; + return; } $contribution->contact_id = $recur->contact_id; @@ -310,23 +317,22 @@ public function recur(&$input, &$ids, &$objects, $first) { $contribution->amount_level = $objects['contribution']->amount_level; $contribution->campaign_id = $objects['contribution']->campaign_id; $objects['contribution'] = &$contribution; + $contribution->invoice_id = md5(uniqid(rand(), TRUE)); } // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now; - $this->single($input, $ids, $objects, - TRUE, $first - ); + $this->single($input, $ids, $objects, TRUE, $first); } /** - * @param $input - * @param $ids - * @param $objects + * @param array $input + * @param array $ids + * @param array $objects * @param bool $recur * @param bool $first * - * @return bool + * @return void */ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) { $contribution = &$objects['contribution']; @@ -334,9 +340,9 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE // make sure the invoice is valid and matches what we have in the contribution record if ((!$recur) || ($recur && $first)) { if ($contribution->invoice_id != $input['invoice']) { - CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request"); + Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.'); echo "Failure: Invoice values dont match between database and IPN request
contribution is" . $contribution->invoice_id . " and input is " . $input['invoice']; - return FALSE; + return; } } else { @@ -345,9 +351,9 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE if (!$recur) { if ($contribution->total_amount != $input['amount']) { - CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request"); + Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.'); echo "Failure: Amount values dont match between database and IPN request
"; - return FALSE; + return; } } else { @@ -356,29 +362,31 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE $transaction = new CRM_Core_Transaction(); - $participant = &$objects['participant']; - $membership = &$objects['membership']; - $status = $input['paymentStatus']; if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') { - return $this->failed($objects, $transaction); + $this->failed($objects, $transaction); + return; } elseif ($status == 'Pending') { - return $this->pending($objects, $transaction); + $this->pending($objects, $transaction); + return; } elseif ($status == 'Refunded' || $status == 'Reversed') { - return $this->cancelled($objects, $transaction); + $this->cancelled($objects, $transaction); + return; } elseif ($status != 'Completed') { - return $this->unhandled($objects, $transaction); + $this->unhandled($objects, $transaction); + return; } // check if contribution is already completed, if so we ignore this ipn - if ($contribution->contribution_status_id == 1) { + $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); + if ($contribution->contribution_status_id == $completedStatusId) { $transaction->commit(); - CRM_Core_Error::debug_log_message("returning since contribution has already been handled"); + Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.'); echo "Success: Contribution has already been handled
"; - return TRUE; + return; } $this->completeTransaction($input, $ids, $objects, $transaction, $recur); @@ -395,15 +403,18 @@ public function getPayPalPaymentProcessorID() { // processor id & the handleNotification function (which should call the completetransaction api & by-pass this // entirely). The only thing the IPN class should really do is extract data from the request, validate it // & call completetransaction or call fail? (which may not exist yet). + + Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance'); + $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal', 'id', 'name' ); - return (int) civicrm_api3('PaymentProcessor', 'getvalue', array( + return (int) civicrm_api3('PaymentProcessor', 'getvalue', [ 'is_test' => 0, - 'options' => array('limit' => 1), + 'options' => ['limit' => 1], 'payment_processor_type_id' => $paymentProcessorTypeID, 'return' => 'id', - )); + ]); } @@ -412,16 +423,16 @@ public function getPayPalPaymentProcessorID() { * (with the input parameters) & call this & all will be done * * @todo the references to POST throughout this class need to be removed - * @return bool + * @return void */ public function main() { CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE); CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE); if ($this->_isPaymentExpress) { $this->handlePaymentExpress(); - return FALSE; + return; } - $objects = $ids = $input = array(); + $objects = $ids = $input = []; $this->_component = $input['component'] = self::getValue('m'); $input['invoice'] = self::getValue('i', TRUE); // get the contribution and contact ids from the GET params @@ -453,25 +464,19 @@ public function main() { INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1 WHERE m.contribution_recur_id = %2 LIMIT 1"; - $sqlParams = array( - 1 => array($ids['contribution'], 'Integer'), - 2 => array($ids['contributionRecur'], 'Integer'), - ); + $sqlParams = [ + 1 => [$ids['contribution'], 'Integer'], + 2 => [$ids['contributionRecur'], 'Integer'], + ]; if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) { $ids['membership'] = $membershipId; } } - // This is an unreliable method as there could be more than one instance. - // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment - // processor id & the handleNotification function (which should call the completetransaction api & by-pass this - // entirely). The only thing the IPN class should really do is extract data from the request, validate it - // & call completetransaction or call fail? (which may not exist yet). - $paymentProcessorID = self::getPayPalPaymentProcessorID(); if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) { - return FALSE; + return; } self::$_paymentProcessor = &$objects['paymentProcessor']; @@ -482,31 +487,27 @@ public function main() { if ($ids['contributionRecur']) { // check if first contribution is completed, else complete first contribution $first = TRUE; - if ($objects['contribution']->contribution_status_id == 1) { + $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); + if ($objects['contribution']->contribution_status_id == $completedStatusId) { $first = FALSE; } - return $this->recur($input, $ids, $objects, $first); + $this->recur($input, $ids, $objects, $first); + return; } - else { - return $this->single($input, $ids, $objects, FALSE, FALSE); - } - } - else { - return $this->single($input, $ids, $objects, FALSE, FALSE); } + $this->single($input, $ids, $objects, FALSE, FALSE); } /** - * @param $input - * @param $ids + * @param array $input + * @param array $ids * - * @return bool + * @return void * @throws CRM_Core_Exception */ public function getInput(&$input, &$ids) { - if (!$this->getBillingID($ids)) { - return FALSE; + return; } $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE); @@ -516,7 +517,7 @@ public function getInput(&$input, &$ids) { $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE); $billingID = $ids['billing']; - $lookup = array( + $lookup = [ "first_name" => 'first_name', "last_name" => 'last_name', "street_address-{$billingID}" => 'address_street', @@ -524,7 +525,7 @@ public function getInput(&$input, &$ids) { "state-{$billingID}" => 'address_state', "postal_code-{$billingID}" => 'address_zip', "country-{$billingID}" => 'address_country_code', - ); + ]; foreach ($lookup as $name => $paypalName) { $value = self::retrieve($paypalName, 'String', 'POST', FALSE); $input[$name] = $value ? $value : NULL; @@ -535,10 +536,12 @@ public function getInput(&$input, &$ids) { $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE); $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE); $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE); + $input['total_amount'] = $input['amount']; } /** * Handle payment express IPNs. + * * For one off IPNS no actual response is required * Recurring is more difficult as we have limited confirmation material * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no @@ -555,49 +558,56 @@ public function handlePaymentExpress() { // also note that a lot of the complexity above could be removed if we used // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal // as membership id etc can be derived by the load objects fn - $objects = $ids = $input = array(); + $objects = $ids = $input = []; $isFirst = FALSE; + $input['invoice'] = self::getValue('i', FALSE); + //Avoid return in case of unit test. + if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) { + return; + } $input['txnType'] = $this->retrieve('txn_type', 'String'); - if ($input['txnType'] != 'recurring_payment') { + $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [ + 'return' => 'contact_id, id, payment_processor_id', + 'invoice_id' => $input['invoice'], + ]); + + if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') { throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments'); } - $input['invoice'] = self::getValue('i', FALSE); + $this->getInput($input, $ids); - if ($this->transactionExists($input['trxn_id'])) { + if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) { throw new CRM_Core_Exception('This transaction has already been processed'); } - $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array( - 'return' => 'contact_id, id', - 'invoice_id' => $input['invoice'], - )); $ids['contact'] = $contributionRecur['contact_id']; $ids['contributionRecur'] = $contributionRecur['id']; - $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'])); + $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']); $ids['contribution'] = $result['id']; - //@todo hard - coding 'pending' for now - if ($result['contribution_status_id'] == 2) { + //@todo hardcoding 'pending' for now + $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'); + if ($result['contribution_status_id'] == $pendingStatusId) { $isFirst = TRUE; } // arg api won't get this - fix it - $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array( - 1 => array( - $ids['contribution'], - 'Integer', - ), - )); + $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [ + 1 => [ + $ids['contribution'], + 'Integer', + ], + ]); // only handle component at this stage - not terribly sure how a recurring event payment would arise // & suspec main function may be a victom of copy & paste // membership would be an easy add - but not relevant to my customer... $this->_component = $input['component'] = 'contribute'; $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String'))); - $paymentProcessorID = self::getPayPalPaymentProcessorID(); + $paymentProcessorID = $contributionRecur['payment_processor_id']; if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) { throw new CRM_Core_Exception('Data did not validate'); } - return $this->recur($input, $ids, $objects, $isFirst); + $this->recur($input, $ids, $objects, $isFirst); } /** @@ -607,9 +617,9 @@ public function handlePaymentExpress() { */ public function transactionExists($trxn_id) { if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1", - array( - 1 => array($trxn_id, 'String'), - )) + [ + 1 => [$trxn_id, 'String'], + ]) ) { return TRUE; } diff --git a/CRM/Core/Payment/PayflowPro.php b/CRM/Core/Payment/PayflowPro.php index 0a914317ba25..1d4b92c5e96c 100644 --- a/CRM/Core/Payment/PayflowPro.php +++ b/CRM/Core/Payment/PayflowPro.php @@ -1,7 +1,7 @@ $user, 'VENDOR' => $this->_paymentProcessor['user_name'], 'PARTNER' => $this->_paymentProcessor['signature'], @@ -102,7 +103,7 @@ public function doDirectPayment(&$params) { 'CVV2' => $params['cvv2'], 'EXPDATE' => urlencode(sprintf('%02d', (int) $params['month']) . substr($params['year'], 2, 2)), 'ACCTTYPE' => urlencode($params['credit_card_type']), - 'AMT' => urlencode($params['amount']), + 'AMT' => urlencode($this->getAmount($params)), 'CURRENCY' => urlencode($params['currency']), 'FIRSTNAME' => $params['billing_first_name'], //credit card name @@ -121,7 +122,7 @@ public function doDirectPayment(&$params) { 'ORDERDESC' => urlencode($params['description']), 'VERBOSITY' => 'MEDIUM', 'BILLTOCOUNTRY' => urlencode($params['country']), - ); + ]; if ($params['installments'] == 1) { $params['is_recur'] = FALSE; @@ -131,7 +132,7 @@ public function doDirectPayment(&$params) { $payflow_query_array['TRXTYPE'] = 'R'; $payflow_query_array['OPTIONALTRX'] = 'S'; - $payflow_query_array['OPTIONALTRXAMT'] = $params['amount']; + $payflow_query_array['OPTIONALTRXAMT'] = $this->getAmount($params); //Amount of the initial Transaction. Required $payflow_query_array['ACTION'] = 'A'; //A for add recurring (M-modify,C-cancel,R-reactivate,I-inquiry,P-payment @@ -272,7 +273,7 @@ public function doDirectPayment(&$params) { return self::errorExit(9016, "No RESULT code from PayPal."); } - $nvpArray = array(); + $nvpArray = []; while (strlen($result)) { // name $keypos = strpos($result, '='); @@ -303,7 +304,7 @@ public function doDirectPayment(&$params) { /******************************************************* * Success ! - * This is a successful transaction. PayFlow Pro does return further information + * This is a successful transaction. Payflow Pro does return further information * about transactions to help you identify fraud including whether they pass * the cvv check, the avs check. This is stored in * CiviCRM as part of the transact @@ -344,10 +345,9 @@ public function doDirectPayment(&$params) { return self::errorExit(9014, "Check the code - all transactions should have been headed off before they got here. Something slipped through the net"); } - /* - * Produces error message and returns from class - */ /** + * Produces error message and returns from class + * * @param null $errorCode * @param null $errorMessage * @@ -364,11 +364,9 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) { return $e; } - - /* - * NOTE: 'doTransferCheckout' not implemented - */ /** + * NOTE: 'doTransferCheckout' not implemented + * * @param array $params * @param $component * @@ -378,37 +376,23 @@ public function doTransferCheckout(&$params, $component) { CRM_Core_Error::fatal(ts('This function is not implemented')); } - /* + /** * This public function checks to see if we have the right processor config values set * * NOTE: Called by Events and Contribute to check config params are set prior to trying * register any credit card details * - * @param string $mode - * The mode we are operating in (live or test) - not used. - * - * returns string $errorMsg if any errors found - null if OK - */ - - // function checkConfig( $mode ) // CiviCRM V1.9 Declaration - - /** - * CiviCRM V2.0 Declaration - * This function checks to see if we have the right config values - * - * @internal param string $mode the mode we are operating in (live or test) - * - * @return string - * the error message if any + * @return string|null + * the error message if any, null if OK */ public function checkConfig() { - $errorMsg = array(); + $errorMsg = []; if (empty($this->_paymentProcessor['user_name'])) { $errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor'); } if (empty($this->_paymentProcessor['url_site'])) { - $errorMsg[] = ' ' . ts('URL is not set for %1', array(1 => $this->_paymentProcessor['name'])); + $errorMsg[] = ' ' . ts('URL is not set for %1', [1 => $this->_paymentProcessor['name']]); } if (!empty($errorMsg)) { @@ -418,12 +402,10 @@ public function checkConfig() { return NULL; } } - //end check config - /* - * convert to a name/value pair (nvp) string - */ /** + * convert to a name/value pair (nvp) string + * * @param $payflow_query_array * * @return array|string @@ -437,22 +419,15 @@ public function convert_to_nvp($payflow_query_array) { return $payflow_query; } - /* - * Submit transaction using CuRL - * @submiturl string Url to direct HTTPS GET to - * @payflow_query value string to be posted - */ /** - * @param $submiturl - * @param $payflow_query + * Submit transaction using cURL + * + * @param string $submiturl Url to direct HTTPS GET to + * @param $payflow_query value string to be posted * * @return mixed|object */ public function submit_transaction($submiturl, $payflow_query) { - /* - * Submit transaction using CuRL - */ - // get data ready for API $user_agent = $_SERVER['HTTP_USER_AGENT']; // Here's your custom headers; adjust appropriately for your setup: @@ -467,7 +442,7 @@ public function submit_transaction($submiturl, $payflow_query) { $headers[] = "X-VPS-Timeout: 45"; //random unique number - the transaction is retried using this transaction ID // in this function but if that doesn't work and it is re- submitted - // it is treated as a new attempt. PayflowPro doesn't allow + // it is treated as a new attempt. Payflow Pro doesn't allow // you to change details (e.g. card no) when you re-submit // you can only try the same details $headers[] = "X-VPS-Request-ID: " . rand(1, 1000000000); @@ -529,7 +504,7 @@ public function submit_transaction($submiturl, $payflow_query) { } } if ($responseHeaders['http_code'] != 200) { - return self::errorExit(9015, "Error connecting to the payflo API server."); + return self::errorExit(9015, "Error connecting to the Payflow Pro API server."); } /* @@ -591,84 +566,5 @@ public function submit_transaction($submiturl, $payflow_query) { curl_close($ch); return $responseData; } - //end submit_transaction - - /** - * @param int $recurringProfileID - * @param int $processorID - * - * @throws Exception - */ - public function getRecurringTransactionStatus($recurringProfileID, $processorID) { - if (!defined('CURLOPT_SSLCERT')) { - CRM_Core_Error::fatal(ts('PayFlowPro requires curl with SSL support')); - } - - /* - * define variables for connecting with the gateway - */ - - //if you have not set up a separate user account the vendor name is used as the username - if (!$this->_paymentProcessor['subject']) { - $user = $this->_paymentProcessor['user_name']; - } - else { - $user = $this->_paymentProcessor['subject']; - } - //$recurringProfileID = "RT0000000001"; - // c $trythis = $this->getRecurringTransactionStatus($recurringProfileID,17); - - /* - *Create the array of variables to be sent to the processor from the $params array - * passed into this function - * - */ - - $payflow_query_array = array( - 'USER' => $user, - 'VENDOR' => $this->_paymentProcessor['user_name'], - 'PARTNER' => $this->_paymentProcessor['signature'], - 'PWD' => $this->_paymentProcessor['password'], - // C - Direct Payment using credit card - 'TENDER' => 'C', - // A - Authorization, S - Sale - 'TRXTYPE' => 'R', - 'ACTION' => 'I', - //A for add recurring - //(M-modify,C-cancel,R-reactivate, - //I-inquiry,P-payment - 'ORIGPROFILEID' => $recurringProfileID, - 'PAYMENTHISTORY' => 'Y', - ); - - $payflow_query = $this->convert_to_nvp($payflow_query_array); - echo $payflow_query; - $submiturl = $this->_paymentProcessor['url_site']; - //ie. url at payment processor to submit to. - $responseData = self::submit_transaction($submiturl, $payflow_query); - /* - * Payment successfully sent to gateway - process the response now - */ - - $result = strstr($responseData, "RESULT"); - $nvpArray = array(); - while (strlen($result)) { - // name - $keypos = strpos($result, '='); - $keyval = substr($result, 0, $keypos); - // value - $valuepos = strpos($result, '&') ? strpos($result, '&') : strlen($result); - $valval = substr($result, $keypos + 1, $valuepos - $keypos - 1); - // decoding the respose - $nvpArray[$keyval] = $valval; - $result = substr($result, $valuepos + 1, strlen($result)); - } - // get the result code to validate. - $result_code = $nvpArray['RESULT']; - print_r($responseData); - - //RESPMSG=Invalid Profile ID: Invalid recurring profile ID - //RT0000000001 - } } diff --git a/CRM/Core/Payment/PaymentExpress.php b/CRM/Core/Payment/PaymentExpress.php index f26ddfd571ba..28552293feed 100644 --- a/CRM/Core/Payment/PaymentExpress.php +++ b/CRM/Core/Payment/PaymentExpress.php @@ -1,7 +1,7 @@ _paymentProcessor['user_name'])) { $error[] = ts('UserID is not set in the Administer » System Settings » Payment Processors'); @@ -159,7 +159,7 @@ public function doTransferCheckout(&$params, $component) { } - $dpsParams = array( + $dpsParams = [ 'AmountInput' => str_replace(",", "", number_format($params['amount'], 2)), 'CurrencyInput' => $params['currencyID'], 'MerchantReference' => $merchantRef, @@ -171,7 +171,7 @@ public function doTransferCheckout(&$params, $component) { 'TxnId' => '', 'UrlFail' => $url, 'UrlSuccess' => $url, - ); + ]; // Allow further manipulation of params via custom hooks CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $dpsParams); diff --git a/CRM/Core/Payment/PaymentExpressIPN.php b/CRM/Core/Payment/PaymentExpressIPN.php index 079f81b1aa5a..207bc59a9b9c 100644 --- a/CRM/Core/Payment/PaymentExpressIPN.php +++ b/CRM/Core/Payment/PaymentExpressIPN.php @@ -1,7 +1,7 @@ invoice_id != $input['invoice']) { CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request"); echo "Failure: Invoice values dont match between database and IPN request
"; - return; + return FALSE; } // lets replace invoice-id with Payment Processor -number because thats what is common and unique @@ -157,7 +157,7 @@ public function newOrderNotify($success, $privateData, $component, $amount, $tra if ($contribution->total_amount != $input['amount']) { CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request"); echo "Failure: Amount values dont match between database and IPN request. " . $contribution->total_amount . "/" . $input['amount'] . "
";
- return;
+ return FALSE;
}
$transaction = new CRM_Core_Transaction();
@@ -255,7 +255,7 @@ public static function getContext($privateData, $orderNo) {
}
}
- return array($isTest, $component, $duplicateTransaction);
+ return [$isTest, $component, $duplicateTransaction];
}
/**
@@ -286,11 +286,11 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
}
if ($dps_method == "pxpay") {
- $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml(array(
+ $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml([
'PxPayUserId' => $dps_user,
'PxPayKey' => $dps_key,
'Response' => $_GET['result'],
- ));
+ ]);
$processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml('ProcessResponse', $processResponse);
fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
@@ -307,8 +307,8 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
if ($response = curl_exec($curl)) {
$info = curl_getinfo($curl);
if ($info['http_code'] < 200 || $info['http_code'] > 299) {
- $log_message = "DPS error: HTTP %1 retrieving %2.";
- CRM_Core_Error::fatal(ts($log_message, array(1 => $info['http_code'], 2 => $info['url'])));
+ $log_message = "DPS error: HTTP {$info['http_code']} retrieving {$info['url']}.";
+ CRM_Core_Error::fatal($log_message);
}
else {
fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"), $response));
@@ -318,7 +318,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
$valid = CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute($response, 'valid');
// CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute() returns NULL if preg fails.
if (is_null($valid)) {
- CRM_Core_Error::fatal(ts("DPS error: Unable to parse XML response from DPS.", array(1 => $valid)));
+ CRM_Core_Error::fatal(ts("DPS error: Unable to parse XML response from DPS.", [1 => $valid]));
}
$success = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'Success');
$txnId = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'TxnId');
@@ -343,8 +343,8 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
require_once 'PaymentExpress/pxaccess.inc.php';
global $pxaccess;
$pxaccess = new PxAccess($dps_url, $dps_user, $dps_key, $mac_key);
- #getResponse method in PxAccess object returns PxPayResponse object
- #which encapsulates all the response data
+ // GetResponse method in PxAccess object returns PxPayResponse object
+ // which encapsulates all the response data
$rsp = $pxaccess->getResponse($rawPostData);
$qfKey = $rsp->getTxnData1();
@@ -439,7 +439,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
* @return array
*/
public static function stringToArray($str) {
- $vars = $labels = array();
+ $vars = $labels = [];
$labels = explode(',', $str);
foreach ($labels as $label) {
$terms = explode('=', $label);
diff --git a/CRM/Core/Payment/PaymentExpressUtils.php b/CRM/Core/Payment/PaymentExpressUtils.php
index 194f870b9b62..c4a544e29e73 100644
--- a/CRM/Core/Payment/PaymentExpressUtils.php
+++ b/CRM/Core/Payment/PaymentExpressUtils.php
@@ -1,7 +1,7 @@
assign('suppressSubmitButton', $form->_paymentObject->isSuppressSubmitButtons());
- $currency = CRM_Utils_Array::value('currency', $form->_values);
- // For event forms, currency is in a different spot
- if (empty($currency)) {
- $currency = CRM_Utils_Array::value('currency', $form->_values['event']);
- }
- $form->assign('currency', $currency);
+ CRM_Financial_Form_Payment::addCreditCardJs($form->getPaymentProcessorID());
+ $form->assign('paymentProcessorID', $form->getPaymentProcessorID());
+
+ $form->assign('currency', $form->getCurrency());
// also set cancel subscription url
if (!empty($form->_paymentProcessor['is_recur']) && !empty($form->_values['is_recur'])) {
@@ -85,12 +84,12 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
}
if (!empty($form->_values['custom_pre_id'])) {
- $profileAddressFields = array();
+ $profileAddressFields = [];
$fields = CRM_Core_BAO_UFGroup::getFields($form->_values['custom_pre_id'], FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
foreach ((array) $fields as $key => $value) {
- CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, array('uf_group_id' => $form->_values['custom_pre_id']));
+ CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, ['uf_group_id' => $form->_values['custom_pre_id']]);
}
if (count($profileAddressFields)) {
$form->set('profileAddressFields', $profileAddressFields);
@@ -133,7 +132,7 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
) {
CRM_Core_Error::fatal(ts('This contribution page is configured to support separate contribution and membership payments. This %1 plugin does not currently support multiple simultaneous payments, or the option to "Execute real-time monetary transactions" is disabled. Please contact the site administrator and notify them of this error',
- array(1 => $form->_paymentProcessor['payment_processor_type'])
+ [1 => $form->_paymentProcessor['payment_processor_type']]
)
);
}
diff --git a/CRM/Core/Payment/Realex.php b/CRM/Core/Payment/Realex.php
index 9af1649742ae..5a4931d214b4 100644
--- a/CRM/Core/Payment/Realex.php
+++ b/CRM/Core/Payment/Realex.php
@@ -1,7 +1,7 @@
get('verifySSL'));
@@ -204,12 +204,12 @@ public function doDirectPayment(&$params) {
// FIXME: We are using the trxn_result_code column to store all these extra details since there
// seems to be nowhere else to put them. This is THE WRONG THING TO DO!
- $extras = array(
+ $extras = [
'authcode' => $response['AUTHCODE'],
'batch_id' => $response['BATCHID'],
'message' => $response['MESSAGE'],
'trxn_result_code' => $response['RESULT'],
- );
+ ];
$params['trxn_id'] = $response['PASREF'];
$params['trxn_result_code'] = serialize($extras);
@@ -230,8 +230,8 @@ public function doDirectPayment(&$params) {
* An array of the result with following keys:
*/
public function xml_parse_into_assoc($xml) {
- $input = array();
- $result = array();
+ $input = [];
+ $result = [];
$result['#error'] = FALSE;
$result['#return'] = NULL;
@@ -250,11 +250,11 @@ public function xml_parse_into_assoc($xml) {
}
else {
$result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
- array(
+ [
1 => xml_get_error_code($xmlparser),
2 => xml_get_current_line_number($xmlparser),
3 => xml_get_current_column_number($xmlparser),
- )
+ ]
);
}
}
@@ -269,8 +269,8 @@ public function xml_parse_into_assoc($xml) {
* @return array
*/
public function _xml_parse($input, $depth = 1) {
- $output = array();
- $children = array();
+ $output = [];
+ $children = [];
foreach ($input as $data) {
if ($data['level'] == $depth) {
@@ -280,7 +280,7 @@ public function _xml_parse($input, $depth = 1) {
break;
case 'open':
- $children = array();
+ $children = [];
break;
case 'close':
@@ -475,7 +475,7 @@ public function &error($errorCode = NULL, $errorMessage = NULL) {
* the error message if any
*/
public function checkConfig() {
- $error = array();
+ $error = [];
if (empty($this->_paymentProcessor['user_name'])) {
$error[] = ts('Merchant ID is not set for this payment processor');
}
diff --git a/CRM/Core/Payment/eWAY.php b/CRM/Core/Payment/eWAY.php
index 10be2be36621..8f198b46c824 100644
--- a/CRM/Core/Payment/eWAY.php
+++ b/CRM/Core/Payment/eWAY.php
@@ -1,7 +1,7 @@
_paymentProcessor['user_name'])) {
$errorMsg[] = ts('eWAY CustomerID is not set for this payment processor');
diff --git a/CRM/Core/Permission.php b/CRM/Core/Permission.php
index 0b9979d599f0..6623bfd1f38e 100644
--- a/CRM/Core/Permission.php
+++ b/CRM/Core/Permission.php
@@ -1,9 +1,9 @@
[
+ * ['access CiviCRM', 'access Ajax API'],
+ * ['access CiviEvent', 'access CiviContribute']
+ * ],
*
- * Ex 4 Must have 'access CiviCRM' or 'access Ajax API' AND 'access CiviEvent'
- * array(
- * array('access CiviCRM', 'access Ajax API'),
- * 'access CiviEvent',
- * ),
+ * @param string|array $permissions
+ * The permission to check as an array or string -see examples.
*
- * Note that in permissions.php this is keyed by the action eg.
- * (access Civi || access AJAX) && (access CiviEvent || access CiviContribute)
- * 'myaction' => array(
- * array('access CiviCRM', 'access Ajax API'),
- * array('access CiviEvent', 'access CiviContribute')
- * ),
+ * @param int $contactId
+ * Contact id to check permissions for. Defaults to current logged-in user.
*
* @return bool
- * true if yes, else false
+ * true if contact has permission(s), else false
*/
- public static function check($permissions) {
+ public static function check($permissions, $contactId = NULL) {
$permissions = (array) $permissions;
+ $userId = CRM_Core_BAO_UFMatch::getUFId($contactId);
+ /** @var CRM_Core_Permission_Temp $tempPerm */
$tempPerm = CRM_Core_Config::singleton()->userPermissionTemp;
foreach ($permissions as $permission) {
if (is_array($permission)) {
foreach ($permission as $orPerm) {
- if (self::check($orPerm)) {
+ if (self::check($orPerm, $contactId)) {
//one of our 'or' permissions has succeeded - stop checking this permission
- return TRUE;;
+ return TRUE;
}
}
//none of our our conditions was met
@@ -135,9 +135,9 @@ public static function check($permissions) {
}
else {
// This is an individual permission
- $granted = CRM_Core_Config::singleton()->userPermissionClass->check($permission);
+ $granted = CRM_Core_Config::singleton()->userPermissionClass->check($permission, $userId);
// Call the permission_check hook to permit dynamic escalation (CRM-19256)
- CRM_Utils_Hook::permission_check($permission, $granted);
+ CRM_Utils_Hook::permission_check($permission, $granted, $contactId);
if (
!$granted
&& !($tempPerm && $tempPerm->check($permission))
@@ -249,8 +249,8 @@ public static function customGroupAdmin() {
*/
public static function customGroup($type = CRM_Core_Permission::VIEW, $reset = FALSE) {
$customGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id',
- array('fresh' => $reset));
- $defaultGroups = array();
+ ['fresh' => $reset]);
+ $defaultGroups = [];
// check if user has all powerful permission
// or administer civicrm permission (CRM-1905)
@@ -375,7 +375,7 @@ public static function event($type = CRM_Core_Permission::VIEW, $eventID = NULL,
}
}
$events = CRM_Event_PseudoConstant::event(NULL, TRUE);
- $includeEvents = array();
+ $includeEvents = [];
// check if user has all powerful permission
if (self::check('register for events')) {
@@ -472,7 +472,7 @@ public static function checkActionPermission($module, $action) {
$permissionName = "delete in $module";
}
else {
- $editPermissions = array(
+ $editPermissions = [
'CiviEvent' => 'edit event participants',
'CiviMember' => 'edit memberships',
'CiviPledge' => 'edit pledges',
@@ -480,7 +480,7 @@ public static function checkActionPermission($module, $action) {
'CiviGrant' => 'edit grants',
'CiviMail' => 'access CiviMail',
'CiviAuction' => 'add auction items',
- );
+ ];
$permissionName = CRM_Utils_Array::value($module, $editPermissions);
}
@@ -580,7 +580,7 @@ public static function checkMenuItem(&$item) {
* @return array
*/
public static function basicPermissions($all = FALSE, $descriptions = FALSE) {
- $cacheKey = implode('-', array($all, $descriptions));
+ $cacheKey = implode('-', [$all, $descriptions]);
if (empty(Civi::$statics[__CLASS__][__FUNCTION__][$cacheKey])) {
Civi::$statics[__CLASS__][__FUNCTION__][$cacheKey] = self::assembleBasicPermissions($all, $descriptions);
}
@@ -600,7 +600,7 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
$permissions = self::getCorePermissions($descriptions);
if (self::isMultisiteEnabled()) {
- $permissions['administer Multiple Organizations'] = array($prefix . ts('administer Multiple Organizations'));
+ $permissions['administer Multiple Organizations'] = [$prefix . ts('administer Multiple Organizations')];
}
if (!$descriptions) {
@@ -616,13 +616,13 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
}
foreach ($components as $comp) {
- $perm = $comp->getPermissions(FALSE, $descriptions);
+ $perm = $comp->getPermissions($all, $descriptions);
if ($perm) {
$info = $comp->getInfo();
foreach ($perm as $p => $attr) {
if (!is_array($attr)) {
- $attr = array($attr);
+ $attr = [$attr];
}
$attr[0] = $info['translatedName'] . ': ' . $attr[0];
@@ -648,11 +648,11 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
* @return array
*/
public static function getAnonymousPermissionsWarnings() {
- static $permissions = array();
+ static $permissions = [];
if (empty($permissions)) {
- $permissions = array(
+ $permissions = [
'administer CiviCRM',
- );
+ ];
$components = CRM_Core_Component::getComponents();
foreach ($components as $comp) {
if (!method_exists($comp, 'getAnonymousPermissionWarnings')) {
@@ -680,196 +680,236 @@ public static function validateForPermissionWarnings($anonymous_perms) {
*/
public static function getCorePermissions() {
$prefix = ts('CiviCRM') . ': ';
- $permissions = array(
- 'add contacts' => array(
+ $permissions = [
+ 'add contacts' => [
$prefix . ts('add contacts'),
ts('Create a new contact record in CiviCRM'),
- ),
- 'view all contacts' => array(
+ ],
+ 'view all contacts' => [
$prefix . ts('view all contacts'),
ts('View ANY CONTACT in the CiviCRM database, export contact info and perform activities such as Send Email, Phone Call, etc.'),
- ),
- 'edit all contacts' => array(
+ ],
+ 'edit all contacts' => [
$prefix . ts('edit all contacts'),
ts('View, Edit and Delete ANY CONTACT in the CiviCRM database; Create and edit relationships, tags and other info about the contacts'),
- ),
- 'view my contact' => array(
+ ],
+ 'view my contact' => [
$prefix . ts('view my contact'),
- ),
- 'edit my contact' => array(
+ ],
+ 'edit my contact' => [
$prefix . ts('edit my contact'),
- ),
- 'delete contacts' => array(
+ ],
+ 'delete contacts' => [
$prefix . ts('delete contacts'),
- ),
- 'access deleted contacts' => array(
+ ],
+ 'access deleted contacts' => [
$prefix . ts('access deleted contacts'),
ts('Access contacts in the trash'),
- ),
- 'import contacts' => array(
+ ],
+ 'import contacts' => [
$prefix . ts('import contacts'),
ts('Import contacts and activities'),
- ),
- 'import SQL datasource' => array(
+ ],
+ 'import SQL datasource' => [
$prefix . ts('import SQL datasource'),
ts('When importing, consume data directly from a SQL datasource'),
- ),
- 'edit groups' => array(
+ ],
+ 'edit groups' => [
$prefix . ts('edit groups'),
ts('Create new groups, edit group settings (e.g. group name, visibility...), delete groups'),
- ),
- 'administer CiviCRM' => array(
+ ],
+ 'administer CiviCRM' => [
$prefix . ts('administer CiviCRM'),
ts('Perform all tasks in the Administer CiviCRM control panel and Import Contacts'),
- ),
- 'skip IDS check' => array(
+ ],
+ 'skip IDS check' => [
$prefix . ts('skip IDS check'),
- ts('IDS system is bypassed for users with this permission. Prevents false errors for admin users.'),
- ),
- 'access uploaded files' => array(
+ ts('Warning: Give to trusted roles only; this permission has security implications. IDS system is bypassed for users with this permission. Prevents false errors for admin users.'),
+ ],
+ 'access uploaded files' => [
$prefix . ts('access uploaded files'),
ts('View / download files including images and photos'),
- ),
- 'profile listings and forms' => array(
+ ],
+ 'profile listings and forms' => [
$prefix . ts('profile listings and forms'),
- ts('Access the profile Search form and listings'),
- ),
- 'profile listings' => array(
+ ts('Warning: Give to trusted roles only; this permission has privacy implications. Add/edit data in online forms and access public searchable directories.'),
+ ],
+ 'profile listings' => [
$prefix . ts('profile listings'),
- ),
- 'profile create' => array(
+ ts('Warning: Give to trusted roles only; this permission has privacy implications. Access public searchable directories.'),
+ ],
+ 'profile create' => [
$prefix . ts('profile create'),
- ts('Use profiles in Create mode'),
- ),
- 'profile edit' => array(
+ ts('Add data in a profile form.'),
+ ],
+ 'profile edit' => [
$prefix . ts('profile edit'),
- ts('Use profiles in Edit mode'),
- ),
- 'profile view' => array(
+ ts('Edit data in a profile form.'),
+ ],
+ 'profile view' => [
$prefix . ts('profile view'),
- ),
- 'access all custom data' => array(
+ ts('View data in a profile.'),
+ ],
+ 'access all custom data' => [
$prefix . ts('access all custom data'),
ts('View all custom fields regardless of ACL rules'),
- ),
- 'view all activities' => array(
+ ],
+ 'view all activities' => [
$prefix . ts('view all activities'),
ts('View all activities (for visible contacts)'),
- ),
- 'delete activities' => array(
+ ],
+ 'delete activities' => [
$prefix . ts('Delete activities'),
- ),
- 'access CiviCRM' => array(
- $prefix . ts('access CiviCRM'),
- ts('Master control for access to the main CiviCRM backend and API'),
- ),
- 'access Contact Dashboard' => array(
+ ],
+ 'edit inbound email basic information' => [
+ $prefix . ts('edit inbound email basic information'),
+ ts('Edit all inbound email activities (for visible contacts) basic information. Content editing not allowed.'),
+ ],
+ 'edit inbound email basic information and content' => [
+ $prefix . ts('edit inbound email basic information and content'),
+ ts('Edit all inbound email activities (for visible contacts) basic information and content.'),
+ ],
+ 'access CiviCRM' => [
+ $prefix . ts('access CiviCRM backend and API'),
+ ts('Master control for access to the main CiviCRM backend and API. Give to trusted roles only.'),
+ ],
+ 'access Contact Dashboard' => [
$prefix . ts('access Contact Dashboard'),
ts('View Contact Dashboard (for themselves and visible contacts)'),
- ),
- 'translate CiviCRM' => array(
+ ],
+ 'translate CiviCRM' => [
$prefix . ts('translate CiviCRM'),
ts('Allow User to enable multilingual'),
- ),
- 'manage tags' => array(
+ ],
+ 'manage tags' => [
$prefix . ts('manage tags'),
ts('Create and rename tags'),
- ),
- 'administer reserved groups' => array(
+ ],
+ 'administer reserved groups' => [
$prefix . ts('administer reserved groups'),
ts('Edit and disable Reserved Groups (Needs Edit Groups)'),
- ),
- 'administer Tagsets' => array(
+ ],
+ 'administer Tagsets' => [
$prefix . ts('administer Tagsets'),
- ),
- 'administer reserved tags' => array(
+ ],
+ 'administer reserved tags' => [
$prefix . ts('administer reserved tags'),
- ),
- 'administer dedupe rules' => array(
+ ],
+ 'administer dedupe rules' => [
$prefix . ts('administer dedupe rules'),
ts('Create and edit rules, change the supervised and unsupervised rules'),
- ),
- 'merge duplicate contacts' => array(
+ ],
+ 'merge duplicate contacts' => [
$prefix . ts('merge duplicate contacts'),
ts('Delete Contacts must also be granted in order for this to work.'),
- ),
- 'force merge duplicate contacts' => array(
+ ],
+ 'force merge duplicate contacts' => [
$prefix . ts('force merge duplicate contacts'),
ts('Delete Contacts must also be granted in order for this to work.'),
- ),
- 'view debug output' => array(
+ ],
+ 'view debug output' => [
$prefix . ts('view debug output'),
ts('View results of debug and backtrace'),
- ),
+ ],
- 'view all notes' => array(
+ 'view all notes' => [
$prefix . ts('view all notes'),
ts("View notes (for visible contacts) even if they're marked admin only"),
- ),
- 'access AJAX API' => array(
+ ],
+ 'add contact notes' => [
+ $prefix . ts('add contact notes'),
+ ts("Create notes for contacts"),
+ ],
+ 'access AJAX API' => [
$prefix . ts('access AJAX API'),
ts('Allow API access even if Access CiviCRM is not granted'),
- ),
- 'access contact reference fields' => array(
+ ],
+ 'access contact reference fields' => [
$prefix . ts('access contact reference fields'),
ts('Allow entering data into contact reference fields'),
- ),
- 'create manual batch' => array(
+ ],
+ 'create manual batch' => [
$prefix . ts('create manual batch'),
ts('Create an accounting batch (with Access to CiviContribute and View Own/All Manual Batches)'),
- ),
- 'edit own manual batches' => array(
+ ],
+ 'edit own manual batches' => [
$prefix . ts('edit own manual batches'),
ts('Edit accounting batches created by user'),
- ),
- 'edit all manual batches' => array(
+ ],
+ 'edit all manual batches' => [
$prefix . ts('edit all manual batches'),
ts('Edit all accounting batches'),
- ),
- 'view own manual batches' => array(
+ ],
+ 'close own manual batches' => [
+ $prefix . ts('close own manual batches'),
+ ts('Close accounting batches created by user (with Access to CiviContribute)'),
+ ],
+ 'close all manual batches' => [
+ $prefix . ts('close all manual batches'),
+ ts('Close all accounting batches (with Access to CiviContribute)'),
+ ],
+ 'reopen own manual batches' => [
+ $prefix . ts('reopen own manual batches'),
+ ts('Reopen accounting batches created by user (with Access to CiviContribute)'),
+ ],
+ 'reopen all manual batches' => [
+ $prefix . ts('reopen all manual batches'),
+ ts('Reopen all accounting batches (with Access to CiviContribute)'),
+ ],
+ 'view own manual batches' => [
$prefix . ts('view own manual batches'),
ts('View accounting batches created by user (with Access to CiviContribute)'),
- ),
- 'view all manual batches' => array(
+ ],
+ 'view all manual batches' => [
$prefix . ts('view all manual batches'),
ts('View all accounting batches (with Access to CiviContribute)'),
- ),
- 'delete own manual batches' => array(
+ ],
+ 'delete own manual batches' => [
$prefix . ts('delete own manual batches'),
ts('Delete accounting batches created by user'),
- ),
- 'delete all manual batches' => array(
+ ],
+ 'delete all manual batches' => [
$prefix . ts('delete all manual batches'),
ts('Delete all accounting batches'),
- ),
- 'export own manual batches' => array(
+ ],
+ 'export own manual batches' => [
$prefix . ts('export own manual batches'),
ts('Export accounting batches created by user'),
- ),
- 'export all manual batches' => array(
+ ],
+ 'export all manual batches' => [
$prefix . ts('export all manual batches'),
ts('Export all accounting batches'),
- ),
- 'administer payment processors' => array(
+ ],
+ 'administer payment processors' => [
$prefix . ts('administer payment processors'),
ts('Add, Update, or Disable Payment Processors'),
- ),
- 'edit message templates' => array(
+ ],
+ 'edit message templates' => [
$prefix . ts('edit message templates'),
- ),
- 'view my invoices' => array(
+ ],
+ 'edit system workflow message templates' => [
+ $prefix . ts('edit system workflow message templates'),
+ ],
+ 'edit user-driven message templates' => [
+ $prefix . ts('edit user-driven message templates'),
+ ],
+ 'view my invoices' => [
$prefix . ts('view my invoices'),
ts('Allow users to view/ download their own invoices'),
- ),
- 'edit api keys' => array(
+ ],
+ 'edit api keys' => [
$prefix . ts('edit api keys'),
ts('Edit API keys'),
- ),
- 'edit own api keys' => array(
+ ],
+ 'edit own api keys' => [
$prefix . ts('edit own api keys'),
ts('Edit user\'s own API keys'),
- ),
- );
+ ],
+ 'send SMS' => [
+ $prefix . ts('send SMS'),
+ ts('Send an SMS'),
+ ],
+ ];
return $permissions;
}
@@ -893,59 +933,68 @@ public static function getCorePermissions() {
* @return array of permissions
*/
public static function getEntityActionPermissions() {
- $permissions = array();
+ $permissions = [];
// These are the default permissions - if any entity does not declare permissions for a given action,
// (or the entity does not declare permissions at all) - then the action will be used from here
- $permissions['default'] = array(
+ $permissions['default'] = [
// applies to getfields, getoptions, etc.
- 'meta' => array('access CiviCRM'),
+ 'meta' => ['access CiviCRM'],
// catch-all, applies to create, get, delete, etc.
// If an entity declares it's own 'default' action it will override this one
- 'default' => array('administer CiviCRM'),
- );
+ 'default' => ['administer CiviCRM'],
+ ];
// Note: Additional permissions in DynamicFKAuthorization
- $permissions['attachment'] = array(
- 'default' => array(
- array('access CiviCRM', 'access AJAX API'),
- ),
- );
+ $permissions['attachment'] = [
+ 'default' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ ];
// Contact permissions
- $permissions['contact'] = array(
- 'create' => array(
+ $permissions['contact'] = [
+ 'create' => [
'access CiviCRM',
'add contacts',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'delete contacts',
- ),
+ ],
// managed by query object
- 'get' => array(),
+ 'get' => [],
// managed by _civicrm_api3_check_edit_permissions
- 'update' => array(),
- 'getquick' => array(
- array('access CiviCRM', 'access AJAX API'),
- ),
- );
+ 'update' => [],
+ 'getquick' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ 'duplicatecheck' => [
+ 'access CiviCRM',
+ ],
+ 'merge' => ['merge duplicate contacts'],
+ ];
+
+ $permissions['dedupe'] = [
+ 'getduplicates' => ['access CiviCRM'],
+ 'getstatistics' => ['access CiviCRM'],
+ ];
// CRM-16963 - Permissions for country.
- $permissions['country'] = array(
- 'get' => array(
+ $permissions['country'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'administer CiviCRM',
- ),
- );
+ ],
+ ];
// Contact-related data permissions.
- $permissions['address'] = array(
+ $permissions['address'] = [
// get is managed by BAO::addSelectWhereClause
// create/delete are managed by _civicrm_api3_check_edit_permissions
- 'default' => array(),
- );
+ 'default' => [],
+ ];
$permissions['email'] = $permissions['address'];
$permissions['phone'] = $permissions['address'];
$permissions['website'] = $permissions['address'];
@@ -953,490 +1002,509 @@ public static function getEntityActionPermissions() {
$permissions['open_i_d'] = $permissions['address'];
// Also managed by ACLs - CRM-19448
- $permissions['entity_tag'] = array('default' => array());
+ $permissions['entity_tag'] = ['default' => []];
$permissions['note'] = $permissions['entity_tag'];
// Allow non-admins to get and create tags to support tagset widget
// Delete is still reserved for admins
- $permissions['tag'] = array(
- 'get' => array('access CiviCRM'),
- 'create' => array('access CiviCRM'),
- 'update' => array('access CiviCRM'),
- );
+ $permissions['tag'] = [
+ 'get' => ['access CiviCRM'],
+ 'create' => ['access CiviCRM'],
+ 'update' => ['access CiviCRM'],
+ ];
//relationship permissions
- $permissions['relationship'] = array(
+ $permissions['relationship'] = [
// get is managed by BAO::addSelectWhereClause
- 'get' => array(),
- 'delete' => array(
+ 'get' => [],
+ 'delete' => [
'access CiviCRM',
'edit all contacts',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit all contacts',
- ),
- );
+ ],
+ ];
// CRM-17741 - Permissions for RelationshipType.
- $permissions['relationship_type'] = array(
- 'get' => array(
+ $permissions['relationship_type'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'administer CiviCRM',
- ),
- );
+ ],
+ ];
// Activity permissions
- $permissions['activity'] = array(
- 'delete' => array(
+ $permissions['activity'] = [
+ 'delete' => [
'access CiviCRM',
'delete activities',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
// Note that view all activities is also required within the api
// if the id is not passed in. Where the id is passed in the activity
// specific check functions are used and tested.
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'view all activities',
- ),
- );
+ ],
+ ];
+ $permissions['activity_contact'] = $permissions['activity'];
// Case permissions
- $permissions['case'] = array(
- 'create' => array(
+ $permissions['case'] = [
+ 'create' => [
'access CiviCRM',
'add cases',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'delete in CiviCase',
- ),
- 'restore' => array(
+ ],
+ 'restore' => [
'administer CiviCase',
- ),
- 'merge' => array(
+ ],
+ 'merge' => [
'administer CiviCase',
- ),
- 'default' => array(
+ ],
+ 'default' => [
// At minimum the user needs one of the following. Finer-grained access is controlled by CRM_Case_BAO_Case::addSelectWhereClause
- array('access my cases and activities', 'access all cases and activities'),
- ),
- );
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
$permissions['case_contact'] = $permissions['case'];
- $permissions['case_type'] = array(
- 'default' => array('administer CiviCase'),
- 'get' => array(
+ $permissions['case_type'] = [
+ 'default' => ['administer CiviCase'],
+ 'get' => [
// nested array = OR
- array('access my cases and activities', 'access all cases and activities'),
- ),
- );
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
// Campaign permissions
- $permissions['campaign'] = array(
- 'get' => array('access CiviCRM'),
- 'default' => array(
+ $permissions['campaign'] = [
+ 'get' => ['access CiviCRM'],
+ 'default' => [
// nested array = OR
- array('administer CiviCampaign', 'manage campaign'),
- ),
- );
+ ['administer CiviCampaign', 'manage campaign'],
+ ],
+ ];
$permissions['survey'] = $permissions['campaign'];
// Financial permissions
- $permissions['contribution'] = array(
- 'get' => array(
+ $permissions['contribution'] = [
+ 'get' => [
'access CiviCRM',
'access CiviContribute',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'completetransaction' => array(
+ ],
+ 'completetransaction' => [
'edit contributions',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
$permissions['line_item'] = $permissions['contribution'];
// Payment permissions
- $permissions['payment'] = array(
- 'get' => array(
+ $permissions['payment'] = [
+ 'get' => [
'access CiviCRM',
'access CiviContribute',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'cancel' => array(
+ ],
+ 'cancel' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- 'create' => array(
+ ],
+ 'create' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
+ $permissions['contribution_recur'] = $permissions['payment'];
// Custom field permissions
- $permissions['custom_field'] = array(
- 'default' => array(
+ $permissions['custom_field'] = [
+ 'default' => [
'administer CiviCRM',
'access all custom data',
- ),
- );
+ ],
+ ];
$permissions['custom_group'] = $permissions['custom_field'];
// Event permissions
- $permissions['event'] = array(
- 'create' => array(
+ $permissions['event'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'edit all events',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'delete in CiviEvent',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event info',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit all events',
- ),
- );
+ ],
+ ];
+ // Exception refers to dedupe_exception.
+ $permissions['exception'] = [
+ 'default' => ['merge duplicate contacts'],
+ ];
+
+ $permissions['job'] = [
+ 'process_batch_merge' => ['merge duplicate contacts'],
+ ];
+ $permissions['rule_group']['get'] = [['merge duplicate contacts', 'administer CiviCRM']];
// Loc block is only used for events
$permissions['loc_block'] = $permissions['event'];
- $permissions['state_province'] = array(
- 'get' => array(
+ $permissions['state_province'] = [
+ 'get' => [
'access CiviCRM',
- ),
- );
+ ],
+ ];
// Price sets are shared by several components, user needs access to at least one of them
- $permissions['price_set'] = array(
- 'default' => array(
- array('access CiviEvent', 'access CiviContribute', 'access CiviMember'),
- ),
- 'get' => array(
- array('access CiviCRM', 'view event info', 'make online contributions'),
- ),
- );
+ $permissions['price_set'] = [
+ 'default' => [
+ ['access CiviEvent', 'access CiviContribute', 'access CiviMember'],
+ ],
+ 'get' => [
+ ['access CiviCRM', 'view event info', 'make online contributions'],
+ ],
+ ];
// File permissions
- $permissions['file'] = array(
- 'default' => array(
+ $permissions['file'] = [
+ 'default' => [
'access CiviCRM',
'access uploaded files',
- ),
- );
+ ],
+ ];
$permissions['files_by_entity'] = $permissions['file'];
// Group permissions
- $permissions['group'] = array(
- 'get' => array(
+ $permissions['group'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit groups',
- ),
- );
+ ],
+ ];
$permissions['group_nesting'] = $permissions['group'];
$permissions['group_organization'] = $permissions['group'];
//Group Contact permission
- $permissions['group_contact'] = array(
- 'get' => array(
+ $permissions['group_contact'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit all contacts',
- ),
- );
+ ],
+ ];
// CiviMail Permissions
- $civiMailBasePerms = array(
+ $civiMailBasePerms = [
// To get/preview/update, one must have least one of these perms:
// Mailing API implementations enforce nuances of create/approve/schedule permissions.
'access CiviMail',
'create mailings',
'schedule mailings',
'approve mailings',
- );
- $permissions['mailing'] = array(
- 'get' => array(
+ ];
+ $permissions['mailing'] = [
+ 'get' => [
'access CiviCRM',
$civiMailBasePerms,
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
$civiMailBasePerms,
'delete in CiviMail',
- ),
- 'submit' => array(
+ ],
+ 'submit' => [
'access CiviCRM',
- array('access CiviMail', 'schedule mailings'),
- ),
- 'default' => array(
+ ['access CiviMail', 'schedule mailings'],
+ ],
+ 'default' => [
'access CiviCRM',
$civiMailBasePerms,
- ),
- );
+ ],
+ ];
$permissions['mailing_group'] = $permissions['mailing'];
$permissions['mailing_job'] = $permissions['mailing'];
$permissions['mailing_recipients'] = $permissions['mailing'];
- $permissions['mailing_a_b'] = array(
- 'get' => array(
+ $permissions['mailing_a_b'] = [
+ 'get' => [
'access CiviCRM',
'access CiviMail',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMail',
'delete in CiviMail',
- ),
- 'submit' => array(
+ ],
+ 'submit' => [
'access CiviCRM',
- array('access CiviMail', 'schedule mailings'),
- ),
- 'default' => array(
+ ['access CiviMail', 'schedule mailings'],
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviMail',
- ),
- );
+ ],
+ ];
// Membership permissions
- $permissions['membership'] = array(
- 'get' => array(
+ $permissions['membership'] = [
+ 'get' => [
'access CiviCRM',
'access CiviMember',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMember',
'delete in CiviMember',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
- ),
- );
+ ],
+ ];
$permissions['membership_status'] = $permissions['membership'];
$permissions['membership_type'] = $permissions['membership'];
- $permissions['membership_payment'] = array(
- 'create' => array(
+ $permissions['membership_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMember',
'delete in CiviMember',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviMember',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Participant permissions
- $permissions['participant'] = array(
- 'create' => array(
+ $permissions['participant'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'register for events',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event participants',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
- ),
- );
- $permissions['participant_payment'] = array(
- 'create' => array(
+ ],
+ ];
+ $permissions['participant_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'register for events',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event participants',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Pledge permissions
- $permissions['pledge'] = array(
- 'create' => array(
+ $permissions['pledge'] = [
+ 'create' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviPledge',
'delete in CiviPledge',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviPledge',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
- ),
- );
+ ],
+ ];
//CRM-16777: Disable schedule reminder for user that have 'edit all events' and 'administer CiviCRM' permission.
- $permissions['action_schedule'] = array(
- 'update' => array(
- array(
+ $permissions['action_schedule'] = [
+ 'update' => [
+ [
'access CiviCRM',
'edit all events',
- ),
- ),
- );
+ ],
+ ],
+ ];
- $permissions['pledge_payment'] = array(
- 'create' => array(
+ $permissions['pledge_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviPledge',
'delete in CiviPledge',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviPledge',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Profile permissions
- $permissions['profile'] = array(
- 'get' => array(), // the profile will take care of this
- );
+ $permissions['profile'] = [
+ // the profile will take care of this
+ 'get' => [],
+ ];
- $permissions['uf_group'] = array(
- 'create' => array(
+ $permissions['uf_group'] = [
+ 'create' => [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- ),
- 'get' => array(
+ ],
+ ],
+ 'get' => [
'access CiviCRM',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- ),
- );
+ ],
+ ],
+ ];
$permissions['uf_field'] = $permissions['uf_join'] = $permissions['uf_group'];
- $permissions['uf_field']['delete'] = array(
+ $permissions['uf_field']['delete'] = [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- );
+ ],
+ ];
$permissions['option_value'] = $permissions['uf_group'];
$permissions['option_group'] = $permissions['option_value'];
- $permissions['message_template'] = array(
- 'get' => array('access CiviCRM'),
- 'create' => array('edit message templates'),
- 'update' => array('edit message templates'),
- );
+ $permissions['custom_value'] = [
+ 'gettree' => ['access CiviCRM'],
+ ];
+
+ $permissions['message_template'] = [
+ 'get' => ['access CiviCRM'],
+ 'create' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
+ 'update' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
+ ];
+
+ $permissions['report_template']['update'] = 'save Report Criteria';
+ $permissions['report_template']['create'] = 'save Report Criteria';
return $permissions;
}
@@ -1487,17 +1555,17 @@ public static function giveMeAllACLs() {
//check for acl.
$aclPermission = self::getPermission();
- if (in_array($aclPermission, array(
+ if (in_array($aclPermission, [
CRM_Core_Permission::EDIT,
CRM_Core_Permission::VIEW,
- ))
+ ])
) {
return TRUE;
}
// run acl where hook and see if the user is supplying an ACL clause
// that is not false
- $tables = $whereTables = array();
+ $tables = $whereTables = [];
$where = NULL;
CRM_Utils_Hook::aclWhereClause(CRM_Core_Permission::VIEW,
@@ -1522,7 +1590,7 @@ public static function getComponentName($permission) {
return $componentName;
}
- static $allCompPermissions = array();
+ static $allCompPermissions = [];
if (empty($allCompPermissions)) {
$components = CRM_Core_Component::getComponents();
foreach ($components as $name => $comp) {
@@ -1586,8 +1654,7 @@ public static function isMultisiteEnabled() {
* invoices permission and the invoice author is the current user.
*/
public static function checkDownloadInvoice() {
- global $user;
- $cid = CRM_Core_BAO_UFMatch::getContactId($user->uid);
+ $cid = CRM_Core_Session::getLoggedInContactID();
if (CRM_Core_Permission::check('access CiviContribute') ||
(CRM_Core_Permission::check('view my invoices') && $_GET['cid'] == $cid)
) {
diff --git a/CRM/Core/Permission/Backdrop.php b/CRM/Core/Permission/Backdrop.php
index 2c1f7e399967..915b95f614c7 100644
--- a/CRM/Core/Permission/Backdrop.php
+++ b/CRM/Core/Permission/Backdrop.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -85,7 +85,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -145,7 +149,7 @@ public function upgradePermissions($permissions) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
@@ -153,27 +157,27 @@ public function permissionEmails($permissionName) {
// FIXME!!!!
/**
- $uids = array();
- $sql = "
- SELECT {users}.uid, {role_permission}.permission
- FROM {users}
- JOIN {users_roles}
- ON {users}.uid = {users_roles}.uid
- JOIN {role_permission}
- ON {role_permission}.rid = {users_roles}.rid
- WHERE {role_permission}.permission = '{$permissionName}'
- AND {users}.status = 1
- ";
-
- $result = db_query($sql);
- foreach ($result as $record) {
- $uids[] = $record->uid;
- }
-
- $_cache[$permissionName] = self::getContactEmails($uids);
- return $_cache[$permissionName];
+ * $uids = array();
+ * $sql = "
+ * SELECT {users}.uid, {role_permission}.permission
+ * FROM {users}
+ * JOIN {users_roles}
+ * ON {users}.uid = {users_roles}.uid
+ * JOIN {role_permission}
+ * ON {role_permission}.rid = {users_roles}.rid
+ * WHERE {role_permission}.permission = '{$permissionName}'
+ * AND {users}.status = 1
+ * ";
+ *
+ * $result = db_query($sql);
+ * foreach ($result as $record) {
+ * $uids[] = $record->uid;
+ * }
+ *
+ * $_cache[$permissionName] = self::getContactEmails($uids);
+ * return $_cache[$permissionName];
*/
- return array();
+ return [];
}
}
diff --git a/CRM/Core/Permission/Base.php b/CRM/Core/Permission/Base.php
index 5a56ef143530..d598e15cb3b0 100644
--- a/CRM/Core/Permission/Base.php
+++ b/CRM/Core/Permission/Base.php
@@ -1,9 +1,9 @@
$label) {
- $permissions[$permission] = (is_array($label)) ? $label : array($label);
+ $permissions[$permission] = (is_array($label)) ? $label : [$label];
}
}
else {
diff --git a/CRM/Core/Permission/Drupal.php b/CRM/Core/Permission/Drupal.php
index d83d795af5e9..f49c0dd52ec5 100644
--- a/CRM/Core/Permission/Drupal.php
+++ b/CRM/Core/Permission/Drupal.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -85,7 +84,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -142,13 +145,13 @@ public function upgradePermissions($permissions) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {role_permission}.permission
FROM {users}
diff --git a/CRM/Core/Permission/Drupal6.php b/CRM/Core/Permission/Drupal6.php
index 131663af091e..eb1a8801fefe 100644
--- a/CRM/Core/Permission/Drupal6.php
+++ b/CRM/Core/Permission/Drupal6.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal6', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal6', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -84,7 +84,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -100,7 +104,7 @@ public function check($str, $contactID = NULL) {
*/
public function checkGroupRole($array) {
if (function_exists('user_load') && isset($array)) {
- $user = user_load(array('uid' => $GLOBALS['user']->uid));
+ $user = user_load(['uid' => $GLOBALS['user']->uid]);
//if giver roles found in user roles - return true
foreach ($array as $key => $value) {
if (in_array($value, $user->roles)) {
@@ -121,13 +125,13 @@ public function checkGroupRole($array) {
* a comma separated list of email addresses
*/
public function roleEmails($roleName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$roleName])) {
return $_cache[$roleName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid
FROM {users}
@@ -156,13 +160,13 @@ public function roleEmails($roleName) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {permission}.perm
FROM {users}
@@ -207,7 +211,7 @@ public function upgradePermissions($permissions) {
* Array of permissions, in the same format as CRM_Core_Permission::getCorePermissions().
*/
public static function getModulePermissions($module) {
- $return_permissions = array();
+ $return_permissions = [];
$fn_name = "{$module}_civicrm_permission";
if (function_exists($fn_name)) {
$fn_name($return_permissions);
diff --git a/CRM/Core/Permission/Drupal8.php b/CRM/Core/Permission/Drupal8.php
index 34fb06212f6a..dc2e4df2154e 100644
--- a/CRM/Core/Permission/Drupal8.php
+++ b/CRM/Core/Permission/Drupal8.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
@@ -58,7 +59,8 @@ public function check($str, $contactID = NULL) {
if ($str == CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION) {
return TRUE;
}
- return \Drupal::currentUser()->hasPermission($str);
+ $acct = $userId ? \Drupal\user\Entity\User::load($userId) : \Drupal::currentUser();
+ return $acct->hasPermission($str);
}
/**
@@ -71,7 +73,7 @@ public function check($str, $contactID = NULL) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
@@ -82,7 +84,7 @@ function (\Drupal\user\RoleInterface $role) {
return $role->id();
}, user_roles(TRUE, $permissionName)
);
- $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('roles' => $role_ids));
+ $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['roles' => $role_ids]);
$uids = array_keys($users);
$_cache[$permissionName] = self::getContactEmails($uids);
diff --git a/CRM/Core/Permission/DrupalBase.php b/CRM/Core/Permission/DrupalBase.php
index bfcfe96848c5..74baeac71cb9 100644
--- a/CRM/Core/Permission/DrupalBase.php
+++ b/CRM/Core/Permission/DrupalBase.php
@@ -1,9 +1,9 @@
_viewPermissionedGroups)) {
- $this->_viewPermissionedGroups = $this->_editPermissionedGroups = array();
+ $this->_viewPermissionedGroups = $this->_editPermissionedGroups = [];
}
$groupKey = $groupType ? $groupType : 'all';
if (!isset($this->_viewPermissionedGroups[$groupKey])) {
- $this->_viewPermissionedGroups[$groupKey] = $this->_editPermissionedGroups[$groupKey] = array();
+ $this->_viewPermissionedGroups[$groupKey] = $this->_editPermissionedGroups[$groupKey] = [];
$groups = CRM_Core_PseudoConstant::allGroup($groupType, $excludeHidden);
@@ -162,7 +163,7 @@ public function groupClause($type, &$tables, &$whereTables) {
$clause = ' ( 0 ) ';
}
else {
- $clauses = array();
+ $clauses = [];
$groups = implode(', ', $this->_editPermissionedGroups[$groupKey]);
$clauses[] = ' ( civicrm_group_contact.group_id IN ( ' . implode(', ', array_keys($this->_editPermissionedGroups[$groupKey])) . " ) AND civicrm_group_contact.status = 'Added' ) ";
$tables['civicrm_group_contact'] = 1;
@@ -193,7 +194,7 @@ public function groupClause($type, &$tables, &$whereTables) {
$clause = ' ( 0 ) ';
}
else {
- $clauses = array();
+ $clauses = [];
$groups = implode(', ', $this->_viewPermissionedGroups[$groupKey]);
$clauses[] = ' civicrm_group.id IN (' . implode(', ', array_keys($this->_viewPermissionedGroups[$groupKey])) . " ) ";
$tables['civicrm_group'] = 1;
@@ -245,7 +246,7 @@ public function getContactEmails($uids) {
$dao = CRM_Core_DAO::executeQuery($sql);
- $emails = array();
+ $emails = [];
while ($dao->fetch()) {
$emails[] = $dao->email;
}
@@ -292,13 +293,13 @@ public function isModulePermissionSupported() {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {role_permission}.permission
FROM {users}
diff --git a/CRM/Core/Permission/Joomla.php b/CRM/Core/Permission/Joomla.php
index 417ddb6ca94f..97c7a054c282 100644
--- a/CRM/Core/Permission/Joomla.php
+++ b/CRM/Core/Permission/Joomla.php
@@ -1,9 +1,9 @@
translateJoomlaPermission($str);
if ($translated === CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
@@ -61,7 +67,7 @@ public function check($str) {
// we've not yet figured out how to bootstrap joomla, so we should
// not execute hooks if joomla is not loaded
if (defined('_JEXEC')) {
- $user = JFactory::getUser();
+ $user = JFactory::getUser($userId);
$api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
// If we are coming from REST we don't have a user but we do have the api_key for a user.
@@ -69,7 +75,7 @@ public function check($str) {
// This is a codeblock copied from /Civicrm/Utils/REST
$uid = NULL;
if (!$uid) {
- $store = NULL;
+ $store = NULL;
$contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
@@ -90,6 +96,10 @@ public function check($str) {
}
}
+ public function isModulePermissionSupported() {
+ return TRUE;
+ }
+
/**
* @param $perm
*
@@ -111,7 +121,7 @@ public function translateJoomlaPermission($perm) {
return CRM_Core_Permission::ALWAYS_DENY_PERMISSION;
case NULL:
- return array('civicrm.' . CRM_Utils_String::munge(strtolower($name)), 'com_civicrm');
+ return ['civicrm.' . CRM_Utils_String::munge(strtolower($name)), 'com_civicrm'];
default:
return CRM_Core_Permission::ALWAYS_DENY_PERMISSION;
@@ -131,4 +141,75 @@ public function checkGroupRole($array) {
return FALSE;
}
+ /**
+ * @inheritDoc
+ */
+ public function upgradePermissions($permissions) {
+ $translatedPerms = [];
+
+ // Flipping the $permissions array gives us just the raw names of the
+ // permissions. The descriptions, etc., are irrelevant for the purposes of
+ // this method.
+ foreach (array_flip($permissions) as $perm) {
+ $translated = $this->translateJoomlaPermission($perm);
+ $translatedPerms[] = $translated[0];
+ }
+
+ $associations = $this->getUserGroupPermsAssociations();
+ $cmsPermsHaveGoneStale = FALSE;
+ foreach (array_keys(get_object_vars($associations)) as $permName) {
+ if (!in_array($permName, $translatedPerms)) {
+ unset($associations->$permName);
+ $cmsPermsHaveGoneStale = TRUE;
+ }
+ }
+
+ if ($cmsPermsHaveGoneStale) {
+ $this->updateGroupPermsAssociations($associations);
+ }
+ }
+
+ /**
+ * Fetches the associations between user groups and CiviCRM permissions.
+ *
+ * @see https://docs.joomla.org/Selecting_data_using_JDatabase
+ * @return object
+ * Properties of the object are Joomla-fied permission names.
+ */
+ private function getUserGroupPermsAssociations() {
+ $db = JFactory::getDbo();
+ $query = $db->getQuery(TRUE);
+
+ $query
+ ->select($db->quoteName('rules'))
+ ->from($db->quoteName('#__assets'))
+ ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
+
+ $db->setQuery($query);
+
+ // Joomla gotcha: loadObject returns NULL in the case of no matches.
+ $result = $db->loadObject();
+ return $result ? json_decode($result->rules) : (object) [];
+ }
+
+ /**
+ * Writes user-group/permissions associations back to Joomla.
+ *
+ * @see https://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase
+ * @param object $associations
+ * Same format as the return of
+ * CRM_Core_Permission_Joomla->getUserGroupPermsAssociations().
+ */
+ private function updateGroupPermsAssociations($associations) {
+ $db = JFactory::getDbo();
+ $query = $db->getQuery(TRUE);
+
+ $query
+ ->update($db->quoteName('#__assets'))
+ ->set($db->quoteName('rules') . ' = ' . $db->quote(json_encode($associations)))
+ ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
+
+ $db->setQuery($query)->execute();
+ }
+
}
diff --git a/CRM/Core/Permission/Soap.php b/CRM/Core/Permission/Soap.php
index fcb87791b2d0..dd746e631ed8 100644
--- a/CRM/Core/Permission/Soap.php
+++ b/CRM/Core/Permission/Soap.php
@@ -1,9 +1,9 @@
array($perm))
@@ -103,7 +103,7 @@ public function check($perm) {
* Array(string $permName => bool $granted).
*/
protected function index($grants) {
- $idx = array();
+ $idx = [];
foreach ($grants as $grant) {
foreach ($grant as $perm) {
$idx[$perm] = 1;
diff --git a/CRM/Core/Permission/UnitTests.php b/CRM/Core/Permission/UnitTests.php
index 86b199bff690..0dccf48cdfee 100644
--- a/CRM/Core/Permission/UnitTests.php
+++ b/CRM/Core/Permission/UnitTests.php
@@ -1,9 +1,9 @@
translatePermission($str, 'WordPress', array(
+ $str = $this->translatePermission($str, 'WordPress', [
'administer users' => 'edit_users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -74,16 +76,18 @@ public function check($str) {
return TRUE;
}
- if (current_user_can('super admin') || current_user_can('administrator')) {
+ $user = $userId ? get_userdata($userId) : wp_get_current_user();
+
+ if ($user->has_cap('super admin') || $user->has_cap('administrator')) {
return TRUE;
}
// Make string lowercase and convert spaces into underscore
$str = CRM_Utils_String::munge(strtolower($str));
- if (is_user_logged_in()) {
+ if ($user->exists()) {
// Check whether the logged in user has the capabilitity
- if (current_user_can($str)) {
+ if ($user->has_cap($str)) {
return TRUE;
}
}
diff --git a/CRM/Core/PrevNextCache/Interface.php b/CRM/Core/PrevNextCache/Interface.php
new file mode 100644
index 000000000000..f0b72aa9c9d3
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Interface.php
@@ -0,0 +1,138 @@
+ ['foo', 'String']]
+ * @return bool
+ * @see CRM_Core_DAO::composeQuery
+ */
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []);
+
+ /**
+ * Store the contents of an array in the cache.
+ *
+ * @param string $cacheKey
+ * @param array $rows
+ * A list of cache records. Each record should have keys:
+ * - entity_id1
+ * - data
+ * @return bool
+ */
+ public function fillWithArray($cacheKey, $rows);
+
+ /**
+ * Save checkbox selections.
+ *
+ * @param string $cacheKey
+ * @param string $action
+ * Ex: 'select', 'unselect'.
+ * @param array|int|null $ids
+ * A list of contact IDs to (un)select.
+ * To unselect all contact IDs, use NULL.
+ */
+ public function markSelection($cacheKey, $action, $ids = NULL);
+
+ /**
+ * Get the selections.
+ *
+ * @param string $cacheKey
+ * Cache key.
+ * @param string $action
+ * One of the following:
+ * - 'get' - get only selection records
+ * - 'getall' - get all the records of the specified cache key
+ *
+ * @return array|NULL
+ */
+ public function getSelection($cacheKey, $action = 'get');
+
+ /**
+ * Get the previous and next keys.
+ *
+ * @param string $cacheKey
+ * @param int $id1
+ *
+ * @return array
+ * List of neighbors.
+ * [
+ * 'foundEntry' => 1,
+ * 'prev' => ['id1' => 123, 'data'=>'foo'],
+ * 'next' => ['id1' => 456, 'data'=>'foo'],
+ * ]
+ */
+ public function getPositions($cacheKey, $id1);
+
+ /**
+ * Delete an item from the prevnext cache table based on the entity.
+ *
+ * @param int $id
+ * @param string $cacheKey
+ */
+ public function deleteItem($id = NULL, $cacheKey = NULL);
+
+ /**
+ * Get count of matching rows.
+ *
+ * @param string $cacheKey
+ * @return int
+ */
+ public function getCount($cacheKey);
+
+ /**
+ * Fetch a list of contacts from the prev/next cache for displaying a search results page
+ *
+ * @param string $cacheKey
+ * @param int $offset
+ * @param int $rowCount
+ * @return array
+ * List of contact IDs (entity_id1).
+ */
+ public function fetch($cacheKey, $offset, $rowCount);
+
+ /**
+ * Remove items from prev/next cache no longer current
+ */
+ public function cleanup();
+
+}
diff --git a/CRM/Core/PrevNextCache/Redis.php b/CRM/Core/PrevNextCache/Redis.php
new file mode 100644
index 000000000000..340f5c60a30f
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Redis.php
@@ -0,0 +1,263 @@
+redis = CRM_Utils_Cache_Redis::connect($settings);
+ $this->prefix = isset($settings['prefix']) ? $settings['prefix'] : '';
+ $this->prefix .= \CRM_Utils_Cache::DELIMITER . 'prevnext' . \CRM_Utils_Cache::DELIMITER;
+ }
+
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []) {
+ $dao = CRM_Core_DAO::executeQuery($sql, $sqlParams, FALSE, NULL, FALSE, TRUE, TRUE);
+ if (is_a($dao, 'DB_Error')) {
+ throw new CRM_Core_Exception($dao->message);
+ }
+
+ list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
+
+ while ($dao->fetch()) {
+ list (, $entity_id, $data) = array_values($dao->toArray());
+ $maxScore++;
+ $this->redis->zAdd($allKey, $maxScore, $entity_id);
+ $this->redis->hSet($dataKey, $entity_id, $data);
+ }
+
+ return TRUE;
+ }
+
+ public function fillWithArray($cacheKey, $rows) {
+ list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
+
+ foreach ($rows as $row) {
+ $maxScore++;
+ $this->redis->zAdd($allKey, $maxScore, $row['entity_id1']);
+ $this->redis->hSet($dataKey, $row['entity_id1'], $row['data']);
+ }
+
+ return TRUE;
+ }
+
+ public function fetch($cacheKey, $offset, $rowCount) {
+ $allKey = $this->key($cacheKey, 'all');
+ return $this->redis->zRange($allKey, $offset, $offset + $rowCount - 1);
+ }
+
+ public function markSelection($cacheKey, $action, $ids = NULL) {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+
+ if ($action === 'select') {
+ foreach ((array) $ids as $id) {
+ $score = $this->redis->zScore($allKey, $id);
+ $this->redis->zAdd($selKey, $score, $id);
+ }
+ }
+ elseif ($action === 'unselect' && $ids === NULL) {
+ $this->redis->delete($selKey);
+ $this->redis->setTimeout($selKey, self::TTL);
+ }
+ elseif ($action === 'unselect' && $ids !== NULL) {
+ foreach ((array) $ids as $id) {
+ $this->redis->zDelete($selKey, $id);
+ }
+ }
+ }
+
+ public function getSelection($cacheKey, $action = 'get') {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+
+ if ($action === 'get') {
+ $result = [];
+ foreach ($this->redis->zRange($selKey, 0, -1) as $entity_id) {
+ $result[$entity_id] = 1;
+ }
+ return [$cacheKey => $result];
+ }
+ elseif ($action === 'getall') {
+ $result = [];
+ foreach ($this->redis->zRange($allKey, 0, -1) as $entity_id) {
+ $result[$entity_id] = 1;
+ }
+ return [$cacheKey => $result];
+ }
+ else {
+ throw new \CRM_Core_Exception("Unrecognized action: $action");
+ }
+ }
+
+ public function getPositions($cacheKey, $id1) {
+ $allKey = $this->key($cacheKey, 'all');
+ $dataKey = $this->key($cacheKey, 'data');
+
+ $rank = $this->redis->zRank($allKey, $id1);
+ if (!is_int($rank) || $rank < 0) {
+ return ['foundEntry' => 0];
+ }
+
+ $pos = ['foundEntry' => 1];
+
+ if ($rank > 0) {
+ $pos['prev'] = [];
+ foreach ($this->redis->zRange($allKey, $rank - 1, $rank - 1) as $value) {
+ $pos['prev']['id1'] = $value;
+ }
+ $pos['prev']['data'] = $this->redis->hGet($dataKey, $pos['prev']['id1']);
+ }
+
+ $count = $this->getCount($cacheKey);
+ if ($count > $rank + 1) {
+ $pos['next'] = [];
+ foreach ($this->redis->zRange($allKey, $rank + 1, $rank + 1) as $value) {
+ $pos['next']['id1'] = $value;
+ }
+ $pos['next']['data'] = $this->redis->hGet($dataKey, $pos['next']['id1']);
+ }
+
+ return $pos;
+ }
+
+ public function deleteItem($id = NULL, $cacheKey = NULL) {
+ if ($id === NULL && $cacheKey !== NULL) {
+ // Delete by cacheKey.
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+ $dataKey = $this->key($cacheKey, 'data');
+ $this->redis->delete($allKey, $selKey, $dataKey);
+ }
+ elseif ($id === NULL && $cacheKey === NULL) {
+ // Delete everything.
+ $keys = $this->redis->keys($this->prefix . '*');
+ $this->redis->del($keys);
+ }
+ elseif ($id !== NULL && $cacheKey !== NULL) {
+ // Delete a specific contact, within a specific cache.
+ $this->redis->zDelete($this->key($cacheKey, 'all'), $id);
+ $this->redis->zDelete($this->key($cacheKey, 'sel'), $id);
+ $this->redis->hDel($this->key($cacheKey, 'data'), $id);
+ }
+ elseif ($id !== NULL && $cacheKey === NULL) {
+ // Delete a specific contact, across all prevnext caches.
+ $allKeys = $this->redis->keys($this->key('*', 'all'));
+ foreach ($allKeys as $allKey) {
+ $parts = explode(\CRM_Utils_Cache::DELIMITER, $allKey);
+ array_pop($parts);
+ $tmpCacheKey = array_pop($parts);
+ $this->deleteItem($id, $tmpCacheKey);
+ }
+ }
+ else {
+ throw new CRM_Core_Exception("Not implemented: Redis::deleteItem");
+ }
+ }
+
+ public function getCount($cacheKey) {
+ $allKey = $this->key($cacheKey, 'all');
+ return $this->redis->zSize($allKey);
+ }
+
+ /**
+ * Construct the full path to a cache item.
+ *
+ * @param string $cacheKey
+ * Identifier for this saved search.
+ * Ex: 'abcd1234abcd1234'.
+ * @param string $item
+ * Ex: 'list', 'rel', 'data'.
+ * @return string
+ * Ex: 'dmaster/prevnext/abcd1234abcd1234/list'
+ */
+ private function key($cacheKey, $item) {
+ return $this->prefix . $cacheKey . \CRM_Utils_Cache::DELIMITER . $item;
+ }
+
+ /**
+ * Initialize any data-structures or timeouts for the cache-key.
+ *
+ * This is non-destructive -- if data already exists, it's preserved.
+ *
+ * @return array
+ * 0 => string $allItemsCacheKey,
+ * 1 => string $dataItemsCacheKey,
+ * 2 => string $selectedItemsCacheKey,
+ * 3 => int $maxExistingScore
+ */
+ private function initCacheKey($cacheKey) {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+ $dataKey = $this->key($cacheKey, 'data');
+
+ $this->redis->setTimeout($allKey, self::TTL);
+ $this->redis->setTimeout($dataKey, self::TTL);
+ $this->redis->setTimeout($selKey, self::TTL);
+
+ $maxScore = 0;
+ foreach ($this->redis->zRange($allKey, -1, -1, TRUE) as $lastElem => $lastScore) {
+ $maxScore = $lastScore;
+ }
+ return [$allKey, $dataKey, $selKey, $maxScore];
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function cleanup() {
+ // Redis already handles cleaning up stale keys.
+ return;
+ }
+
+}
diff --git a/CRM/Core/PrevNextCache/Sql.php b/CRM/Core/PrevNextCache/Sql.php
new file mode 100644
index 000000000000..678482656102
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Sql.php
@@ -0,0 +1,301 @@
+ ['foo', 'String']]
+ * @return bool
+ * @throws CRM_Core_Exception
+ * @see CRM_Core_DAO::composeQuery
+ */
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []) {
+ $insertSQL = "
+INSERT INTO civicrm_prevnext_cache (cachekey, entity_id1, data)
+";
+ $result = CRM_Core_DAO::executeQuery($insertSQL . $sql, $sqlParams, FALSE, NULL, FALSE, TRUE, TRUE);
+ if (is_a($result, 'DB_Error')) {
+ throw new CRM_Core_Exception($result->message);
+ }
+ return TRUE;
+ }
+
+ public function fillWithArray($cacheKey, $rows) {
+ if (empty($rows)) {
+ return;
+ }
+
+ $insert = CRM_Utils_SQL_Insert::into('civicrm_prevnext_cache')
+ ->columns([
+ 'entity_id1',
+ 'cachekey',
+ 'data',
+ ]);
+
+ foreach ($rows as &$row) {
+ $insert->row($row + ['cachekey' => $cacheKey]);
+ }
+
+ CRM_Core_DAO::executeQuery($insert->toSQL());
+ return TRUE;
+ }
+
+ /**
+ * Save checkbox selections.
+ *
+ * @param string $cacheKey
+ * @param string $action
+ * Ex: 'select', 'unselect'.
+ * @param array|int|null $ids
+ * A list of contact IDs to (un)select.
+ * To unselect all contact IDs, use NULL.
+ */
+ public function markSelection($cacheKey, $action, $ids = NULL) {
+ if (!$cacheKey) {
+ return;
+ }
+ $params = [];
+
+ if ($ids && $cacheKey && $action) {
+ if (is_array($ids)) {
+ $cIdFilter = "(" . implode(',', $ids) . ")";
+ $whereClause = "
+WHERE cachekey = %1
+AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
+";
+ }
+ else {
+ $whereClause = "
+WHERE cachekey = %1
+AND (entity_id1 = %2 OR entity_id2 = %2)
+";
+ $params[2] = ["{$ids}", 'Integer'];
+ }
+ if ($action == 'select') {
+ $whereClause .= "AND is_selected = 0";
+ $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause}";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ elseif ($action == 'unselect') {
+ $whereClause .= "AND is_selected = 1";
+ $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause}";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ // default action is reseting
+ }
+ elseif (!$ids && $cacheKey && $action == 'unselect') {
+ $sql = "
+UPDATE civicrm_prevnext_cache
+SET is_selected = 0
+WHERE cachekey = %1 AND is_selected = 1
+";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
+ /**
+ * Get the selections.
+ *
+ * @param string $cacheKey
+ * Cache key.
+ * @param string $action
+ * One of the following:
+ * - 'get' - get only selection records
+ * - 'getall' - get all the records of the specified cache key
+ *
+ * @return array|NULL
+ */
+ public function getSelection($cacheKey, $action = 'get') {
+ if (!$cacheKey) {
+ return NULL;
+ }
+ $params = [];
+
+ if ($cacheKey && ($action == 'get' || $action == 'getall')) {
+ $actionGet = ($action == "get") ? " AND is_selected = 1 " : "";
+ $sql = "
+SELECT entity_id1 FROM civicrm_prevnext_cache
+WHERE cachekey = %1
+ $actionGet
+ORDER BY id
+";
+ $params[1] = [$cacheKey, 'String'];
+
+ $contactIds = [$cacheKey => []];
+ $cIdDao = CRM_Core_DAO::executeQuery($sql, $params);
+ while ($cIdDao->fetch()) {
+ $contactIds[$cacheKey][$cIdDao->entity_id1] = 1;
+ }
+ return $contactIds;
+ }
+ }
+
+ /**
+ * Get the previous and next keys.
+ *
+ * @param string $cacheKey
+ * @param int $id1
+ *
+ * @return array
+ */
+ public function getPositions($cacheKey, $id1) {
+ $mergeId = CRM_Core_DAO::singleValueQuery(
+ "SELECT id FROM civicrm_prevnext_cache WHERE cachekey = %2 AND entity_id1 = %1",
+ [
+ 1 => [$id1, 'Integer'],
+ 2 => [$cacheKey, 'String'],
+ ]
+ );
+
+ $pos = ['foundEntry' => 0];
+ if ($mergeId) {
+ $pos['foundEntry'] = 1;
+
+ $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn ";
+ $wherePrev = " WHERE pn.id < %1 AND pn.cachekey = %2 ORDER BY ID DESC LIMIT 1";
+ $whereNext = " WHERE pn.id > %1 AND pn.cachekey = %2 ORDER BY ID ASC LIMIT 1";
+ $p = [
+ 1 => [$mergeId, 'Integer'],
+ 2 => [$cacheKey, 'String'],
+ ];
+
+ $dao = CRM_Core_DAO::executeQuery($sql . $wherePrev, $p);
+ if ($dao->fetch()) {
+ $pos['prev']['id1'] = $dao->entity_id1;
+ $pos['prev']['mergeId'] = $dao->id;
+ $pos['prev']['data'] = $dao->data;
+ }
+
+ $dao = CRM_Core_DAO::executeQuery($sql . $whereNext, $p);
+ if ($dao->fetch()) {
+ $pos['next']['id1'] = $dao->entity_id1;
+ $pos['next']['mergeId'] = $dao->id;
+ $pos['next']['data'] = $dao->data;
+ }
+ }
+ return $pos;
+
+ }
+
+ /**
+ * Delete an item from the prevnext cache table based on the entity.
+ *
+ * @param int $id
+ * @param string $cacheKey
+ */
+ public function deleteItem($id = NULL, $cacheKey = NULL) {
+ $sql = "DELETE FROM civicrm_prevnext_cache WHERE (1)";
+ $params = [];
+
+ if (is_numeric($id)) {
+ $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
+ $params[2] = [$id, 'Integer'];
+ }
+
+ if (isset($cacheKey)) {
+ $sql .= " AND cachekey = %3";
+ $params[3] = [$cacheKey, 'String'];
+ }
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
+ /**
+ * Get count of matching rows.
+ *
+ * @param string $cacheKey
+ * @return int
+ */
+ public function getCount($cacheKey) {
+ $query = "SELECT COUNT(*) FROM civicrm_prevnext_cache pn WHERE pn.cachekey = %1";
+ $params = [1 => [$cacheKey, 'String']];
+ return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
+ }
+
+ /**
+ * Fetch a list of contacts from the prev/next cache for displaying a search results page
+ *
+ * @param string $cacheKey
+ * @param int $offset
+ * @param int $rowCount
+ * @return array
+ * List of contact IDs.
+ */
+ public function fetch($cacheKey, $offset, $rowCount) {
+ $cids = [];
+ $dao = CRM_Utils_SQL_Select::from('civicrm_prevnext_cache pnc')
+ ->where('pnc.cachekey = @cacheKey', ['cacheKey' => $cacheKey])
+ ->select('pnc.entity_id1 as cid')
+ ->orderBy('pnc.id')
+ ->limit($rowCount, $offset)
+ ->execute();
+ while ($dao->fetch()) {
+ $cids[] = $dao->cid;
+ }
+ return $cids;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function cleanup() {
+ // clean up all prev next caches older than $cacheTimeIntervalDays days
+ // first find all the cacheKeys that match this
+ $sql = "
+ DELETE pn, c
+ FROM civicrm_cache c
+ INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cachekey
+ WHERE c.group_name = %1
+ AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
+ ";
+ $params = [
+ 1 => [CRM_Core_BAO_Cache::cleanKey('CiviCRM Search PrevNextCache'), 'String'],
+ 2 => [self::cacheDays, 'Integer'],
+ ];
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
+}
diff --git a/CRM/Core/PseudoConstant.php b/CRM/Core/PseudoConstant.php
index 419664441890..cb5f8d175910 100644
--- a/CRM/Core/PseudoConstant.php
+++ b/CRM/Core/PseudoConstant.php
@@ -1,9 +1,9 @@
FALSE,
- 'localize' => FALSE,
+ 'localize' => $localizeDefault,
'onlyActive' => ($context == 'validate' || $context == 'get') ? FALSE : TRUE,
'fresh' => FALSE,
'context' => $context,
- );
+ ];
$entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getCanonicalClassName($daoName));
// Custom fields are not in the schema
@@ -224,14 +220,12 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
if ($options && $flip) {
$options = array_flip($options);
}
- $customField->free();
return $options;
}
// Core field: load schema
$dao = new $daoName();
$fieldSpec = $dao->getFieldSpec($fieldName);
- $dao->free();
// Ensure we have the canonical name for this field
$fieldName = CRM_Utils_Array::value('name', $fieldSpec, $fieldName);
@@ -253,25 +247,11 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
}
// Merge params with schema defaults
- $params += array(
- 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()),
+ $params += [
+ 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, []),
'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant),
'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant),
- );
-
- if ($context == 'abbreviate') {
- switch ($fieldName) {
- case 'state_province_id':
- $params['labelColumn'] = 'abbreviation';
- break;
-
- case 'country_id':
- $params['labelColumn'] = 'iso_code';
- break;
-
- default:
- }
- }
+ ];
// Fetch option group from option_value table
if (!empty($pseudoconstant['optionGroupName'])) {
@@ -306,8 +286,8 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$cacheKey = $daoName . $fieldName . serialize($params);
// Retrieve cached options
- if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) {
- $output = self::$cache[$cacheKey];
+ if (isset(\Civi::$statics[__CLASS__][$cacheKey]) && empty($params['fresh'])) {
+ $output = \Civi::$statics[__CLASS__][$cacheKey];
}
else {
$daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
@@ -317,11 +297,10 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
// Get list of fields for the option table
$dao = new $daoName();
$availableFields = array_keys($dao->fieldKeys());
- $dao->free();
$select = "SELECT %1 AS id, %2 AS label";
$from = "FROM %3";
- $wheres = array();
+ $wheres = [];
$order = "ORDER BY %2";
// Use machine name in certain contexts
@@ -334,13 +313,19 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$params[$nameField] = 'name';
}
}
+
+ // Use abbrColum if context is abbreviate
+ if ($context == 'abbreviate' && (in_array('abbreviation', $availableFields) || !empty($pseudoconstant['abbrColumn']))) {
+ $params['labelColumn'] = $pseudoconstant['abbrColumn'] ?? 'abbreviation';
+ }
+
// Condition param can be passed as an sql clause string or an array of clauses
if (!empty($params['condition'])) {
$wheres[] = implode(' AND ', (array) $params['condition']);
}
// onlyActive param will automatically filter on common flags
if (!empty($params['onlyActive'])) {
- foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
+ foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
if (in_array($flag, $availableFields)) {
$wheres[] = "$flag = $val";
}
@@ -350,14 +335,14 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
if (in_array('domain_id', $availableFields)) {
$wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
}
- $queryParams = array(
- 1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- );
+ $queryParams = [
+ 1 => [$params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ 2 => [$params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ ];
// Add orderColumn param
if (!empty($params['orderColumn'])) {
- $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES);
+ $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES];
$order = "ORDER BY %4";
}
// Support no sorting if $params[orderColumn] is FALSE
@@ -369,7 +354,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$order = "ORDER BY weight";
}
- $output = array();
+ $output = [];
$query = "$select $from";
if ($wheres) {
$query .= " WHERE " . implode($wheres, ' AND ');
@@ -379,15 +364,11 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
while ($dao->fetch()) {
$output[$dao->id] = $dao->label;
}
- $dao->free();
// Localize results
if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') {
- $I18nParams = array();
- if ($pseudoconstant['table'] == 'civicrm_country') {
- $I18nParams['context'] = 'country';
- }
- if ($pseudoconstant['table'] == 'civicrm_state_province') {
- $I18nParams['context'] = 'province';
+ $I18nParams = [];
+ if (isset($fieldSpec['localize_context'])) {
+ $I18nParams['context'] = $fieldSpec['localize_context'];
}
$i18n = CRM_Core_I18n::singleton();
$i18n->localizeArray($output, $I18nParams);
@@ -397,7 +378,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
}
}
CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
- self::$cache[$cacheKey] = $output;
+ \Civi::$statics[__CLASS__][$cacheKey] = $output;
}
return $flip ? array_flip($output) : $output;
}
@@ -405,7 +386,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
// Return "Yes" and "No" for boolean fields
elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
- $output = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean();
+ $output = $context == 'validate' ? [0, 1] : CRM_Core_SelectValues::boolean();
CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
return $flip ? array_flip($output) : $output;
}
@@ -418,7 +399,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
*
* @param string $baoName
* @param string $fieldName
- * @param string|Int $key
+ * @param string|int $key
*
* TODO: Accept multivalued input?
*
@@ -440,7 +421,7 @@ public static function getLabel($baoName, $fieldName, $key) {
*
* @param string $baoName
* @param string $fieldName
- * @param string|Int $key
+ * @param string|int $key
*
* @return bool|null|string
* FALSE if the given field has no associated option list
@@ -460,7 +441,7 @@ public static function getName($baoName, $fieldName, $key) {
*
* @param string $baoName
* @param string $fieldName
- * @param string|Int $value
+ * @param string|int $value
*
* @return bool|null|string|int
* FALSE if the given field has no associated option list
@@ -497,13 +478,13 @@ public static function getOptionEditUrl($fieldSpec) {
WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
ORDER BY page_callback
LIMIT 1";
- return CRM_Core_Dao::singleValueQuery($sql);
+ return CRM_Core_DAO::singleValueQuery($sql);
}
return NULL;
}
/**
- * DEPRECATED generic populate method.
+ * @deprecated generic populate method.
* All pseudoconstant functions that use this method are also @deprecated
*
* The static array $var is populated from the db
@@ -541,10 +522,10 @@ public static function populate(
$key = 'id',
$force = NULL
) {
- $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
+ $cacheKey = CRM_Utils_Cache::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
$cache = CRM_Utils_Cache::singleton();
$var = $cache->get($cacheKey);
- if ($var && empty($force)) {
+ if ($var !== NULL && empty($force)) {
return $var;
}
@@ -573,7 +554,7 @@ public static function populate(
}
$object->find();
- $var = array();
+ $var = [];
while ($object->fetch()) {
$var[$object->$key] = $object->$retrieve;
}
@@ -585,7 +566,6 @@ public static function populate(
* Flush given pseudoconstant so it can be reread from db.
* nex time it's requested.
*
- *
* @param bool|string $name pseudoconstant to be flushed
*/
public static function flush($name = 'cache') {
@@ -594,6 +574,9 @@ public static function flush($name = 'cache') {
}
if ($name == 'cache') {
CRM_Core_OptionGroup::flushAll();
+ if (isset(\Civi::$statics[__CLASS__])) {
+ unset(\Civi::$statics[__CLASS__]);
+ }
}
}
@@ -621,7 +604,7 @@ public static function &activityType() {
$index .= '_' . (int) $onlyComponentActivities;
if (NULL === self::$activityType) {
- self::$activityType = array();
+ self::$activityType = [];
}
if (!isset(self::$activityType[$index]) || $reset) {
@@ -634,7 +617,7 @@ public static function &activityType() {
$componentClause = " v.component_id IS NOT NULL";
}
- $componentIds = array();
+ $componentIds = [];
$compInfo = CRM_Core_Component::getEnabledComponents();
// build filter for listing activity types only if their
@@ -692,7 +675,7 @@ public static function &stateProvince($id = FALSE, $limit = TRUE) {
if ($limit) {
$countryIsoCodes = self::countryIsoCode();
$limitCodes = CRM_Core_BAO_Country::provinceLimit();
- $limitIds = array();
+ $limitIds = [];
foreach ($limitCodes as $code) {
$limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
}
@@ -709,9 +692,9 @@ public static function &stateProvince($id = FALSE, $limit = TRUE) {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray(self::$stateProvince, array(
+ $i18n->localizeArray(self::$stateProvince, [
'context' => 'province',
- ));
+ ]);
self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
}
}
@@ -746,12 +729,12 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
$query = "SELECT abbreviation
FROM civicrm_state_province
WHERE id = %1";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$id,
'Integer',
- ),
- );
+ ],
+ ];
self::$stateProvinceAbbreviation[$id] = CRM_Core_DAO::singleValueQuery($query, $params);
}
return self::$stateProvinceAbbreviation[$id];
@@ -762,7 +745,7 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
if ($limit) {
$countryIsoCodes = self::countryIsoCode();
$limitCodes = CRM_Core_BAO_Country::provinceLimit();
- $limitIds = array();
+ $limitIds = [];
foreach ($limitCodes as $code) {
$tmpArray = array_keys($countryIsoCodes, $code);
@@ -780,6 +763,32 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
return self::$stateProvinceAbbreviation;
}
+ /**
+ * Get all the State/Province abbreviations from the database for the specified country.
+ *
+ * @param int $countryID
+ *
+ * @return array
+ * array of all State/Province abbreviations for the given country.
+ */
+ public static function stateProvinceAbbreviationForCountry($countryID) {
+ if (!isset(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID])) {
+ \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID] = [];
+ }
+ self::populate(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
+ return \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID];
+ }
+
+ /**
+ * Get all the State/Province abbreviations from the database for the default country.
+ *
+ * @return array
+ * array of all State/Province abbreviations for the given country.
+ */
+ public static function stateProvinceAbbreviationForDefaultCountry() {
+ return CRM_Core_PseudoConstant::stateProvinceAbbreviationForCountry(Civi::settings()->get('defaultContactCountry'));
+ }
+
/**
* Get all the countries from database.
*
@@ -801,7 +810,7 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
$config = CRM_Core_Config::singleton();
- $limitCodes = array();
+ $limitCodes = [];
if ($applyLimit) {
// limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
@@ -809,9 +818,9 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
// K/P: We need to fix this, i dont think it works with new setting files
$limitCodes = CRM_Core_BAO_Country::countryLimit();
if (!is_array($limitCodes)) {
- $limitCodes = array(
+ $limitCodes = [
$config->countryLimit => 1,
- );
+ ];
}
$limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
@@ -827,9 +836,9 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
// if default country is set, percolate it to the top
- if ($config->defaultContactCountry()) {
+ if (CRM_Core_BAO_Country::defaultContactCountry()) {
$countryIsoCodes = self::countryIsoCode();
- $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
+ $defaultID = array_search(CRM_Core_BAO_Country::defaultContactCountry(), $countryIsoCodes);
if ($defaultID !== FALSE) {
$default[$defaultID] = CRM_Utils_Array::value($defaultID, self::$country);
self::$country = $default + self::$country;
@@ -840,9 +849,9 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray(self::$country, array(
+ $i18n->localizeArray(self::$country, [
'context' => 'country',
- ));
+ ]);
self::$country = CRM_Utils_Array::asort(self::$country);
}
}
@@ -908,6 +917,11 @@ public static function &countryIsoCode($id = FALSE) {
* array reference of all groups.
*/
public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
+ if ($groupType === 'validate') {
+ // validate gets passed through from getoptions. Handle in the deprecated
+ // fn rather than change the new pattern.
+ $groupType = NULL;
+ }
$condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
$groupKey = ($groupType ? $groupType : 'null') . !empty($excludeHidden);
@@ -1011,7 +1025,7 @@ public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $exc
public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
$cacheKey = $valueColumnName . '::' . $isActive;
if (!CRM_Utils_Array::value($cacheKey, self::$relationshipType) || $reset) {
- self::$relationshipType[$cacheKey] = array();
+ self::$relationshipType[$cacheKey] = [];
//now we have name/label columns CRM-3336
$column_a_b = "{$valueColumnName}_a_b";
@@ -1026,7 +1040,7 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
$relationshipTypeDAO->find();
while ($relationshipTypeDAO->fetch()) {
- self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = array(
+ self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = [
'id' => $relationshipTypeDAO->id,
$column_a_b => $relationshipTypeDAO->$column_a_b,
$column_b_a => $relationshipTypeDAO->$column_b_a,
@@ -1034,7 +1048,7 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
- );
+ ];
}
}
@@ -1052,275 +1066,13 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
*/
public static function ¤cyCode() {
if (!self::$currencyCode) {
- self::$currencyCode = array(
- 'AFN',
- 'ALL',
- 'DZD',
- 'USD',
- 'EUR',
- 'AOA',
- 'XCD',
- 'XCD',
- 'ARS',
- 'AMD',
- 'AWG',
- 'AUD',
- 'EUR',
- 'AZM',
- 'BSD',
- 'BHD',
- 'BDT',
- 'BBD',
- 'BYR',
- 'EUR',
- 'BZD',
- 'XOF',
- 'BMD',
- 'INR',
- 'BTN',
- 'BOB',
- 'BOV',
- 'BAM',
- 'BWP',
- 'NOK',
- 'BRL',
- 'USD',
- 'BND',
- 'BGN',
- 'XOF',
- 'BIF',
- 'KHR',
- 'XAF',
- 'CAD',
- 'CVE',
- 'KYD',
- 'XAF',
- 'XAF',
- 'CLP',
- 'CLF',
- 'CNY',
- 'AUD',
- 'AUD',
- 'COP',
- 'COU',
- 'KMF',
- 'XAF',
- 'CDF',
- 'NZD',
- 'CRC',
- 'XOF',
- 'HRK',
- 'CUP',
- 'CYP',
- 'CZK',
- 'DKK',
- 'DJF',
- 'XCD',
- 'DOP',
- 'USD',
- 'EGP',
- 'SVC',
- 'USD',
- 'XAF',
- 'ERN',
- 'EEK',
- 'ETB',
- 'FKP',
- 'DKK',
- 'FJD',
- 'EUR',
- 'EUR',
- 'EUR',
- 'XPF',
- 'EUR',
- 'XAF',
- 'GMD',
- 'GEL',
- 'EUR',
- 'GHC',
- 'GIP',
- 'EUR',
- 'DKK',
- 'XCD',
- 'EUR',
- 'USD',
- 'GTQ',
- 'GNF',
- 'GWP',
- 'XOF',
- 'GYD',
- 'HTG',
- 'USD',
- 'AUD',
- 'EUR',
- 'HNL',
- 'HKD',
- 'HUF',
- 'ISK',
- 'INR',
- 'IDR',
- 'XDR',
- 'IRR',
- 'IQD',
- 'EUR',
- 'ILS',
- 'EUR',
- 'JMD',
- 'JPY',
- 'JOD',
- 'KZT',
- 'KES',
- 'AUD',
- 'KPW',
- 'KRW',
- 'KWD',
- 'KGS',
- 'LAK',
- 'LVL',
- 'LBP',
- 'ZAR',
- 'LSL',
- 'LRD',
- 'LYD',
- 'CHF',
- 'LTL',
- 'EUR',
- 'MOP',
- 'MKD',
- 'MGA',
- 'MWK',
- 'MYR',
- 'MVR',
- 'XOF',
- 'MTL',
- 'USD',
- 'EUR',
- 'MRO',
- 'MUR',
- 'EUR',
- 'MXN',
- 'MXV',
- 'USD',
- 'MDL',
- 'EUR',
- 'MNT',
- 'XCD',
- 'MAD',
- 'MZM',
- 'MMK',
- 'ZAR',
- 'NAD',
- 'AUD',
- 'NPR',
- 'EUR',
- 'ANG',
- 'XPF',
- 'NZD',
- 'NIO',
- 'XOF',
- 'NGN',
- 'NZD',
- 'AUD',
- 'USD',
- 'NOK',
- 'OMR',
- 'PKR',
- 'USD',
- 'PAB',
- 'USD',
- 'PGK',
- 'PYG',
- 'PEN',
- 'PHP',
- 'NZD',
- 'PLN',
- 'EUR',
- 'USD',
- 'QAR',
- 'EUR',
- 'ROL',
- 'RON',
- 'RUB',
- 'RWF',
- 'SHP',
- 'XCD',
- 'XCD',
- 'EUR',
- 'XCD',
- 'WST',
- 'EUR',
- 'STD',
- 'SAR',
- 'XOF',
- 'CSD',
- 'EUR',
- 'SCR',
- 'SLL',
- 'SGD',
- 'SKK',
- 'SIT',
- 'SBD',
- 'SOS',
- 'ZAR',
- 'EUR',
- 'LKR',
- 'SDD',
- 'SRD',
- 'NOK',
- 'SZL',
- 'SEK',
- 'CHF',
- 'CHW',
- 'CHE',
- 'SYP',
- 'TWD',
- 'TJS',
- 'TZS',
- 'THB',
- 'USD',
- 'XOF',
- 'NZD',
- 'TOP',
- 'TTD',
- 'TND',
- 'TRY',
- 'TRL',
- 'TMM',
- 'USD',
- 'AUD',
- 'UGX',
- 'UAH',
- 'AED',
- 'GBP',
- 'USD',
- 'USS',
- 'USN',
- 'USD',
- 'UYU',
- 'UZS',
- 'VUV',
- 'VEB',
- 'VND',
- 'USD',
- 'USD',
- 'XPF',
- 'MAD',
- 'YER',
- 'ZMK',
- 'ZWD',
- 'XAU',
- 'XBA',
- 'XBB',
- 'XBC',
- 'XBD',
- 'XPD',
- 'XPT',
- 'XAG',
- 'XFU',
- 'XFO',
- 'XTS',
- 'XXX',
- );
+
+ $query = "SELECT name FROM civicrm_currency";
+ $dao = CRM_Core_DAO::executeQuery($query);
+ $currencyCode = [];
+ while ($dao->fetch()) {
+ self::$currencyCode[] = $dao->name;
+ }
}
return self::$currencyCode;
}
@@ -1462,10 +1214,10 @@ public static function &worldRegion($id = FALSE) {
*/
public static function &activityStatus($column = 'label') {
if (NULL === self::$activityStatus) {
- self::$activityStatus = array();
+ self::$activityStatus = [];
}
if (!array_key_exists($column, self::$activityStatus)) {
- self::$activityStatus[$column] = array();
+ self::$activityStatus[$column] = [];
self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
}
@@ -1488,7 +1240,7 @@ public static function &activityStatus($column = 'label') {
*/
public static function &visibility($column = 'label') {
if (!isset(self::$visibility)) {
- self::$visibility = array();
+ self::$visibility = [];
}
if (!isset(self::$visibility[$column])) {
@@ -1509,7 +1261,7 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
$cacheKey = "{$countryID}_{$field}";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1521,16 +1273,16 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
FROM civicrm_state_province
WHERE country_id = %1
ORDER BY name";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$countryID,
'Integer',
- ),
- );
+ ],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->name;
}
@@ -1540,9 +1292,9 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray($result, array(
+ $i18n->localizeArray($result, [
'context' => 'province',
- ));
+ ]);
$result = CRM_Utils_Array::asort($result);
}
@@ -1570,7 +1322,7 @@ public static function &countyForState($stateID) {
$dao = CRM_Core_DAO::executeQuery($query);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
}
@@ -1581,7 +1333,7 @@ public static function &countyForState($stateID) {
$cacheKey = "{$stateID}_name";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1593,16 +1345,16 @@ public static function &countyForState($stateID) {
FROM civicrm_county
WHERE state_province_id = %1
ORDER BY name";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$stateID,
'Integer',
- ),
- );
+ ],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->name;
}
@@ -1630,7 +1382,7 @@ public static function countryIDForStateID($stateID) {
FROM civicrm_state_province
WHERE id = %1
";
- $params = array(1 => array($stateID, 'Integer'));
+ $params = [1 => [$stateID, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -1650,6 +1402,10 @@ public static function countryIDForStateID($stateID) {
* array reference of all greetings.
*/
public static function greeting($filter, $columnName = 'label') {
+ if (!isset(Civi::$statics[__CLASS__]['greeting'])) {
+ Civi::$statics[__CLASS__]['greeting'] = [];
+ }
+
$index = $filter['greeting_type'] . '_' . $columnName;
// also add contactType to the array
@@ -1658,11 +1414,7 @@ public static function greeting($filter, $columnName = 'label') {
$index .= '_' . $contactType;
}
- if (NULL === self::$greeting) {
- self::$greeting = array();
- }
-
- if (!CRM_Utils_Array::value($index, self::$greeting)) {
+ if (!CRM_Utils_Array::value($index, Civi::$statics[__CLASS__]['greeting'])) {
$filterCondition = NULL;
if ($contactType) {
$filterVal = 'v.filter =';
@@ -1682,40 +1434,10 @@ public static function greeting($filter, $columnName = 'label') {
$filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
}
- self::$greeting[$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
- }
-
- return self::$greeting[$index];
- }
-
- /**
- * Construct array of default greeting values for contact type.
- *
- *
- * @return array
- * array reference of default greetings.
- */
- public static function &greetingDefaults() {
- if (!self::$greetingDefaults) {
- $defaultGreetings = array();
- $contactTypes = self::get('CRM_Contact_DAO_Contact', 'contact_type', array(
- 'keyColumn' => 'id',
- 'labelColumn' => 'name',
- ));
-
- foreach ($contactTypes as $filter => $contactType) {
- $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
-
- foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
- $tokenVal = CRM_Core_OptionGroup::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
- $defaultGreetings[$contactType][$greeting] = $tokenVal;
- }
- }
-
- self::$greetingDefaults = $defaultGreetings;
+ Civi::$statics[__CLASS__]['greeting'][$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
}
- return self::$greetingDefaults;
+ return Civi::$statics[__CLASS__]['greeting'][$index];
}
/**
@@ -1732,7 +1454,8 @@ public static function &greetingDefaults() {
*/
public static function &getExtensions() {
if (!self::$extensions) {
- self::$extensions = array();
+ $compat = CRM_Extension_System::getCompatibilityInfo();
+ self::$extensions = [];
$sql = '
SELECT full_name, label
FROM civicrm_extension
@@ -1740,6 +1463,9 @@ public static function &getExtensions() {
';
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
+ if (!empty($compat[$dao->full_name]['force-uninstall'])) {
+ continue;
+ }
self::$extensions[$dao->full_name] = $dao->label;
}
}
@@ -1787,7 +1513,6 @@ public static function getModuleExtensions($fresh = FALSE) {
return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
}
-
/**
* Get all tax rates.
*
@@ -1798,13 +1523,13 @@ public static function getModuleExtensions($fresh = FALSE) {
*/
public static function getTaxRates() {
if (!isset(Civi::$statics[__CLASS__]['taxRates'])) {
- Civi::$statics[__CLASS__]['taxRates'] = array();
- $option = civicrm_api3('option_value', 'get', array(
+ Civi::$statics[__CLASS__]['taxRates'] = [];
+ $option = civicrm_api3('option_value', 'get', [
'sequential' => 1,
'option_group_id' => 'account_relationship',
'name' => 'Sales Tax Account is',
- ));
- $value = array();
+ ]);
+ $value = [];
if ($option['count'] !== 0) {
if ($option['count'] > 1) {
foreach ($option['values'] as $opt) {
@@ -1814,7 +1539,7 @@ public static function getTaxRates() {
else {
$value[] = $option['values'][0]['value'];
}
- $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
+ $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
}
else {
$where = '';
@@ -1835,4 +1560,17 @@ public static function getTaxRates() {
return Civi::$statics[__CLASS__]['taxRates'];
}
+ /**
+ * Get participant status class options.
+ *
+ * @return array
+ */
+ public static function emailOnHoldOptions() {
+ return [
+ '0' => ts('No'),
+ '1' => ts('On Hold Bounce'),
+ '2' => ts('On Hold Opt Out'),
+ ];
+ }
+
}
diff --git a/CRM/Core/QuickForm/Action.php b/CRM/Core/QuickForm/Action.php
index e8b88b0f587a..c36855e66717 100644
--- a/CRM/Core/QuickForm/Action.php
+++ b/CRM/Core/QuickForm/Action.php
@@ -1,9 +1,9 @@
_QFResponseType == 'json') {
- $response = array('content' => $html);
+ $response = ['content' => $html];
if (!empty($page->ajaxResponse)) {
$response += $page->ajaxResponse;
}
@@ -169,7 +169,7 @@ public function renderForm(&$page) {
$content,
"{$page->_name}.pdf",
FALSE,
- array('paper_size' => 'a3', 'orientation' => 'landscape')
+ ['paper_size' => 'a3', 'orientation' => 'landscape']
);
}
else {
diff --git a/CRM/Core/QuickForm/Action/Done.php b/CRM/Core/QuickForm/Action/Done.php
index 234b25379b69..9e7fdae42577 100644
--- a/CRM/Core/QuickForm/Action/Done.php
+++ b/CRM/Core/QuickForm/Action/Done.php
@@ -1,9 +1,9 @@
getAttribute('action');
+ // prevent URLs that end in ? from causing redirects
+ $action = rtrim($action, '?');
+ // FIXME: this should be passed through CRM_Utils_System::url()
$url = $action . (FALSE === strpos($action, '?') ? '?' : '&') . $current->getButtonName('display') . '=true' . '&qfKey=' . $page->get('qfKey');
CRM_Utils_System::redirect($url);
diff --git a/CRM/Core/QuickForm/Action/Next.php b/CRM/Core/QuickForm/Action/Next.php
index 90767f9f4e87..e44698ec82cd 100644
--- a/CRM/Core/QuickForm/Action/Next.php
+++ b/CRM/Core/QuickForm/Action/Next.php
@@ -1,9 +1,9 @@
moveUploadedFile($this->_uploadDir, $newName);
if (!$status) {
- CRM_Core_Error::statusBounce(ts('We could not move the uploaded file %1 to the upload directory %2. Please verify that the \'Temporary Files\' setting points to a valid path which is writable by your web server.', array(
- 1 => $value['name'],
- 2 => $this->_uploadDir,
- )));
+ CRM_Core_Error::statusBounce(ts('We could not move the uploaded file %1 to the upload directory %2. Please verify that the \'Temporary Files\' setting points to a valid path which is writable by your web server.', [
+ 1 => $value['name'],
+ 2 => $this->_uploadDir,
+ ]));
}
if (!empty($data['values'][$pageName][$uploadName]['name'])) {
@unlink($this->_uploadDir . $data['values'][$pageName][$uploadName]);
}
- $value = array(
+ $value = [
'name' => $this->_uploadDir . $newName,
'type' => $value['type'],
- );
+ ];
//CRM-19460 handle brackets if present in $uploadName, similar things we do it for all other inputs.
$value = $element->_prepareValue($value, TRUE);
$data['values'][$pageName] = HTML_QuickForm::arrayMerge($data['values'][$pageName], $value);
diff --git a/CRM/Core/QuickForm/GroupMultiSelect.php b/CRM/Core/QuickForm/GroupMultiSelect.php
index 8da81e66cf78..35a959ad942b 100644
--- a/CRM/Core/QuickForm/GroupMultiSelect.php
+++ b/CRM/Core/QuickForm/GroupMultiSelect.php
@@ -1,7 +1,7 @@
_options as $option) {
- $_labelAttributes = array('style', 'class', 'onmouseover', 'onmouseout');
- $labelAttributes = array();
+ $_labelAttributes = ['style', 'class', 'onmouseover', 'onmouseout'];
+ $labelAttributes = [];
foreach ($_labelAttributes as $attr) {
if (isset($option['attr'][$attr])) {
$labelAttributes[$attr] = $option['attr'][$attr];
@@ -92,19 +93,19 @@ public function toHtml() {
$strHtmlRemove = '';
// build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 1);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 1);"];
$this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "" . PHP_EOL;
// build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 0);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 0);"];
$this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "" . PHP_EOL;
// build the toggle selection button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 2);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 2);"];
$this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
$attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
$strHtmlToggle = "" . PHP_EOL;
@@ -116,26 +117,26 @@ public function toHtml() {
// ... or a dual multi-select
// set name of Select From Box
- $this->_attributesUnselected = array(
+ $this->_attributesUnselected = [
'name' => '__' . $selectName,
'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add')",
- );
+ ];
$this->_attributesUnselected = array_merge($this->_attributes, $this->_attributesUnselected);
$attrUnselected = $this->_getAttrString($this->_attributesUnselected);
// set name of Select To Box
- $this->_attributesSelected = array(
+ $this->_attributesSelected = [
'name' => '_' . $selectName,
'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove')",
- );
+ ];
$this->_attributesSelected = array_merge($this->_attributes, $this->_attributesSelected);
$attrSelected = $this->_getAttrString($this->_attributesSelected);
// set name of Select hidden Box
- $this->_attributesHidden = array(
+ $this->_attributesHidden = [
'name' => $selectName,
'style' => 'overflow: hidden; visibility: hidden; width: 1px; height: 0;',
- );
+ ];
$this->_attributesHidden = array_merge($this->_attributes, $this->_attributesHidden);
$attrHidden = $this->_getAttrString($this->_attributesHidden);
@@ -145,11 +146,11 @@ public function toHtml() {
$arrHtmlSelected = array_fill(0, $append, ' ');
}
else {
- $arrHtmlSelected = array();
+ $arrHtmlSelected = [];
}
$options = count($this->_options);
- $arrHtmlUnselected = array();
+ $arrHtmlUnselected = [];
if ($options > 0) {
$arrHtmlHidden = array_fill(0, $options, ' ');
@@ -176,7 +177,7 @@ public function toHtml() {
}
}
else {
- $arrHtmlHidden = array();
+ $arrHtmlHidden = [];
}
// The 'unselected' multi-select which appears on the left
@@ -207,43 +208,43 @@ public function toHtml() {
$strHtmlHidden .= '';
// build the remove button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove'); return false;"];
$this->_removeButtonAttributes = array_merge($this->_removeButtonAttributes, $attributes);
$attrStrRemove = $this->_getAttrString($this->_removeButtonAttributes);
$strHtmlRemove = "" . PHP_EOL;
// build the add button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add'); return false;"];
$this->_addButtonAttributes = array_merge($this->_addButtonAttributes, $attributes);
$attrStrAdd = $this->_getAttrString($this->_addButtonAttributes);
$strHtmlAdd = "" . PHP_EOL;
// build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'all'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'all'); return false;"];
$this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "" . PHP_EOL;
// build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'none'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'none'); return false;"];
$this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "" . PHP_EOL;
// build the toggle button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'toggle'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'toggle'); return false;"];
$this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
$attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
$strHtmlToggle = "" . PHP_EOL;
// build the move up button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}moveUp(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}moveUp(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;"];
$this->_upButtonAttributes = array_merge($this->_upButtonAttributes, $attributes);
$attrStrUp = $this->_getAttrString($this->_upButtonAttributes);
$strHtmlMoveUp = "" . PHP_EOL;
// build the move down button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}moveDown(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}moveDown(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;"];
$this->_downButtonAttributes = array_merge($this->_downButtonAttributes, $attributes);
$attrStrDown = $this->_getAttrString($this->_downButtonAttributes);
$strHtmlMoveDown = "" . PHP_EOL;
@@ -271,7 +272,7 @@ public function toHtml() {
$strHtml = preg_replace('/\s*.*\s*/i', '', $strHtml);
}
- $placeHolders = array(
+ $placeHolders = [
'{stylesheet}',
'{javascript}',
'{class}',
@@ -284,8 +285,8 @@ public function toHtml() {
'{toggle}',
'{moveup}',
'{movedown}',
- );
- $htmlElements = array(
+ ];
+ $htmlElements = [
$this->getElementCss(FALSE),
$this->getElementJs(FALSE),
$this->_tableAttributes,
@@ -298,7 +299,7 @@ public function toHtml() {
$strHtmlToggle,
$strHtmlMoveUp,
$strHtmlMoveDown,
- );
+ ];
$strHtml = str_replace($placeHolders, $htmlElements, $strHtml);
diff --git a/CRM/Core/QuickForm/NestedAdvMultiSelect.php b/CRM/Core/QuickForm/NestedAdvMultiSelect.php
index fb691c339469..791ef9ef2477 100644
--- a/CRM/Core/QuickForm/NestedAdvMultiSelect.php
+++ b/CRM/Core/QuickForm/NestedAdvMultiSelect.php
@@ -1,7 +1,7 @@
$val) {
$arr[$key] = $val;
}
diff --git a/CRM/Core/Reference/Basic.php b/CRM/Core/Reference/Basic.php
index 797d5832ab9d..a3e1fe73f8a7 100644
--- a/CRM/Core/Reference/Basic.php
+++ b/CRM/Core/Reference/Basic.php
@@ -83,9 +83,9 @@ public function findReferences($targetDao) {
if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists($this->getReferenceTable(), 'id')) {
$select = '*';
}
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
- );
+ $params = [
+ 1 => [$targetDao->$targetColumn, 'String'],
+ ];
$sql = << ' . ts("Custom field '%1' has been saved.", array(1 => $customField->label)) . ' ' . ts("Custom field '%1' has been saved.", [1 => $customField->label]) . ' ' . ts('One contact merged.', [
+ 'count' => $stats['merged'],
+ 'plural' => '%count contacts merged.',
+ ]) . ' ' . ts('One contact was skipped.', [
+ 'count' => $stats['skipped'],
+ 'plural' => '%count contacts were skipped.',
+ ]) . ' " : '') . $event->description;
- $session_options[$radio->getAttribute('id')] = array(
+ $session_options[$radio->getAttribute('id')] = [
'session_title' => $event->title,
'session_description' => $event_description,
'session_full' => $event_is_full,
'event_id' => $event->id,
- );
+ ];
foreach ($previous_event_choices as $choice) {
if ($choice->event_id == $event->id) {
$defaults[$group_name] = $event->id;
@@ -95,18 +95,18 @@ public function buildQuickForm() {
$this->assign('slot_fields', $slot_fields);
$this->assign('session_options', json_encode($session_options));
- $buttons = array();
- $buttons[] = array(
+ $buttons = [];
+ $buttons[] = [
'name' => ts('Go Back'),
'spacing' => '  ',
'type' => 'back',
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'isDefault' => TRUE,
'name' => ts('Continue'),
'spacing' => ' ',
'type' => 'next',
- );
+ ];
$this->addButtons($buttons);
}
@@ -134,7 +134,7 @@ public function postProcess() {
}
$event_in_cart = $this->cart->add_event($session_event_id);
- $values = array();
+ $values = [];
CRM_Core_DAO::storeValues($this->main_participant, $values);
$values['id'] = NULL;
$values['event_id'] = $event_in_cart->event_id;
diff --git a/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php b/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
index c47306a84049..72bcc8f921a0 100644
--- a/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
+++ b/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
@@ -24,7 +24,7 @@ public function preProcess() {
* Build quick form.
*/
public function buildQuickForm() {
- $this->price_fields_for_event = array();
+ $this->price_fields_for_event = [];
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = new CRM_Event_Cart_Form_MerParticipant($participant);
$form->appendQuickForm($this);
@@ -37,20 +37,20 @@ public function buildQuickForm() {
$this->assign('events_in_carts', $this->cart->get_main_events_in_carts());
$this->assign('price_fields_for_event', $this->price_fields_for_event);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
if ($this->cid) {
- $params = array('id' => $this->cid);
+ $params = ['id' => $this->cid];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
- $contact_values = array();
+ $contact_values = [];
CRM_Core_DAO::storeValues($contact, $contact_values);
$this->assign('contact', $contact_values);
}
@@ -81,7 +81,7 @@ public static function primary_email_from_contact($contact) {
* @return array
*/
public function build_price_options($event) {
- $price_fields_for_event = array();
+ $price_fields_for_event = [];
$base_field_name = "event_{$event->id}_amount";
$price_set_id = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $event->id);
//CRM-14492 display admin fields only if user is admin
@@ -128,7 +128,7 @@ public function validate() {
$priceField->price_set_id = $price_set_id;
$priceField->find();
- $check = array();
+ $check = [];
while ($priceField->fetch()) {
if (!empty($fields["event_{$event_in_cart->event_id}_price_{$priceField->id}"])) {
@@ -141,7 +141,7 @@ public function validate() {
$this->_errors['_qf_default'] = ts("Select at least one option from Price Levels.");
}
- $lineItem = array();
+ $lineItem = [];
if (is_array($this->_values['fee']['fields'])) {
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee']['fields'], $fields, $lineItem);
//XXX total...
@@ -151,6 +151,11 @@ public function validate() {
}
}
+ // Validate if participant is already registered
+ if ($event_in_cart->event->allow_same_participant_emails) {
+ continue;
+ }
+
foreach ($event_in_cart->participants as $mer_participant) {
$participant_fields = $fields['event'][$event_in_cart->event_id]['participant'][$mer_participant->id];
//TODO what to do when profile responses differ for the same contact?
@@ -165,11 +170,11 @@ public function validate() {
while ($participant->fetch()) {
if (array_key_exists($participant->status_id, $statusTypes)) {
$form = $mer_participant->get_form();
- $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", array(
- 1 => $participant_fields['email'],
- 2 => $event_in_cart->event->title,
- 3 => $event_in_cart->event->start_date,
- ));
+ $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", [
+ 1 => $participant_fields['email'],
+ 2 => $event_in_cart->event->title,
+ 3 => $event_in_cart->event->start_date,
+ ]);
}
}
}
@@ -186,7 +191,7 @@ public function validate() {
public function setDefaultValues() {
$this->loadCart();
- $defaults = array();
+ $defaults = [];
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = $participant->get_form();
if (empty($participant->email)
@@ -194,8 +199,8 @@ public function setDefaultValues() {
&& ($participant->get_participant_index() == 1)
&& ($this->cid != 0)
) {
- $defaults = array();
- $params = array('id' => $this->cid);
+ $defaults = [];
+ $params = ['id' => $this->cid];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
$participant->contact_id = $this->cid;
$participant->save();
@@ -246,7 +251,7 @@ public function postProcess() {
return;
}
// XXX de facto primary key
- $email_to_contact_id = array();
+ $email_to_contact_id = [];
foreach ($this->_submitValues['event'] as $event_id => $participants) {
foreach ($participants['participant'] as $participant_id => $fields) {
if (array_key_exists($fields['email'], $email_to_contact_id)) {
@@ -259,8 +264,8 @@ public function postProcess() {
$participant = $this->cart->get_event_in_cart_by_event_id($event_id)->get_participant_by_id($participant_id);
if ($participant->contact_id && $contact_id != $participant->contact_id) {
- $defaults = array();
- $params = array('id' => $participant->contact_id);
+ $defaults = [];
+ $params = ['id' => $participant->contact_id];
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($this->cart->get_subparticipants($participant) as $subparticipant) {
@@ -280,14 +285,14 @@ public function postProcess() {
}
//TODO security check that participant ids are already in this cart
- $participant_params = array(
+ $participant_params = [
'id' => $participant_id,
'cart_id' => $this->cart->id,
'event_id' => $event_id,
'contact_id' => $contact_id,
//'registered_by_id' => $this->cart->user_id,
'email' => $fields['email'],
- );
+ ];
$participant = new CRM_Event_Cart_BAO_MerParticipant($participant_params);
$participant->save();
$this->cart->add_participant_to_cart($participant);
@@ -296,6 +301,12 @@ public function postProcess() {
$custom_fields = array_merge($participant->get_form()->get_participant_custom_data_fields());
CRM_Contact_BAO_Contact::createProfileContact($this->_submitValues['field'][$participant_id], $custom_fields, $contact_id);
+
+ CRM_Core_BAO_CustomValueTable::postProcess($this->_submitValues['field'][$participant_id],
+ 'civicrm_participant',
+ $participant_id,
+ 'Participant'
+ );
}
}
}
diff --git a/CRM/Event/Cart/Form/Checkout/Payment.php b/CRM/Event/Cart/Form/Checkout/Payment.php
index 59f843ad461e..cf67ad1be400 100644
--- a/CRM/Event/Cart/Form/Checkout/Payment.php
+++ b/CRM/Event/Cart/Form/Checkout/Payment.php
@@ -8,7 +8,7 @@ class CRM_Event_Cart_Form_Checkout_Payment extends CRM_Event_Cart_Form_Cart {
public $financial_type_id;
public $description;
public $line_items;
- public $_fields = array();
+ public $_fields = [];
public $_paymentProcessor;
public $total;
public $sub_total;
@@ -31,7 +31,7 @@ public function registerParticipant($params, &$participant, $event) {
// handle register date CRM-4320
$registerDate = date('YmdHis');
- $participantParams = array(
+ $participantParams = [
'id' => $participant->id,
'event_id' => $event->id,
'register_date' => $registerDate,
@@ -42,12 +42,12 @@ public function registerParticipant($params, &$participant, $event) {
//XXX why is this a ref to participant and not contact?:
//'registered_by_id' => $this->payer_contact_id,
'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
- );
+ ];
if ($participant->must_wait) {
$participant_status = 'On waitlist';
}
- elseif (CRM_Utils_Array::value('is_pay_later', $params, FALSE)) {
+ elseif (!empty($params['is_pay_later'])) {
$participant_status = 'Pending from pay later';
}
else {
@@ -69,11 +69,11 @@ public function registerParticipant($params, &$participant, $event) {
if (self::is_administrator()) {
if (!empty($params['note'])) {
- $note_params = array(
+ $note_params = [
'participant_id' => $participant->id,
'contact_id' => self::getContactID(),
'note' => $params['note'],
- );
+ ];
CRM_Event_BAO_Participant::update_note($note_params);
}
}
@@ -82,49 +82,48 @@ public function registerParticipant($params, &$participant, $event) {
$participant->save();
if (!empty($params['contributionID'])) {
- $payment_params = array(
+ $participantPaymentParams = [
'participant_id' => $participant->id,
'contribution_id' => $params['contributionID'],
- );
- $ids = array();
- CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
+ ];
+ civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
}
$transaction->commit();
- $event_values = array();
+ $event_values = [];
CRM_Core_DAO::storeValues($event, $event_values);
- $location = array();
+ $location = [];
if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
CRM_Core_BAO_Address::fixAddress($location['address'][1]);
}
list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
- $payer_values = array(
+ $payer_values = [
'email' => '',
'name' => '',
- );
+ ];
if ($this->payer_contact_id) {
$payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
- $payer_values = array(
+ $payer_values = [
'email' => $payer_contact_details[1],
'name' => $payer_contact_details[0],
- );
+ ];
}
- $values = array(
- 'params' => array($participant->id => $participantParams),
+ $values = [
+ 'params' => [$participant->id => $participantParams],
'event' => $event_values,
'location' => $location,
'custom_pre_id' => $pre_id,
'custom_post_id' => $post_id,
'payer' => $payer_values,
- );
+ ];
CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
return $participant;
@@ -176,6 +175,10 @@ public function buildPaymentFields() {
);
$this->assign('pay_later_instructions', $this->pay_later_receipt);
}
+
+ // Event Cart does not support multiple payment processors
+ // so we cannot call $this->preProcessPaymentOptions();
+ CRM_Financial_Form_Payment::addCreditCardJs($this->_paymentProcessor['id']);
}
/**
@@ -183,7 +186,7 @@ public function buildPaymentFields() {
*/
public function buildQuickForm() {
- $this->line_items = array();
+ $this->line_items = [];
$this->sub_total = 0;
$this->_price_values = $this->getValuesForPage('ParticipantsAndPrices');
@@ -201,18 +204,18 @@ public function buildQuickForm() {
$this->assign('line_items', $this->line_items);
$this->assign('sub_total', $this->sub_total);
$this->assign('total', $this->total);
- $buttons = array();
- $buttons[] = array(
+ $buttons = [];
+ $buttons[] = [
'name' => ts('Go Back'),
'spacing' => '  ',
'type' => 'back',
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'isDefault' => TRUE,
'name' => ts('Complete Transaction'),
'spacing' => ' ',
'type' => 'next',
- );
+ ];
if ($this->total) {
$this->add('text', 'billing_contact_email', 'Billing Email', '', TRUE);
@@ -220,22 +223,22 @@ public function buildQuickForm() {
}
if (self::is_administrator()) {
$this->add('textarea', 'note', 'Note');
- $this->add('text', 'source', 'Source', array('size' => 80));
- $instruments = array();
+ $this->add('text', 'source', 'Source', ['size' => 80]);
+ $instruments = [];
CRM_Core_OptionGroup::getAssoc('payment_instrument', $instruments, TRUE);
- $options = array();
+ $options = [];
foreach ($instruments as $type) {
$options[] = $this->createElement('radio', NULL, '', $type['label'], $type['value']);
}
$this->addGroup($options, 'payment_type', ts("Alternative Payment Type"));
- $this->add('text', 'check_number', ts('Check No.'), array('size' => 20));
+ $this->add('text', 'check_number', ts('Check No.'), ['size' => 20]);
$this->addElement('checkbox', 'is_pending', ts('Create a pending registration'));
$this->assign('administrator', TRUE);
}
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Cart_Form_Checkout_Payment', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Cart_Form_Checkout_Payment', 'formRule'], $this);
if ($this->payment_required) {
$this->buildPaymentFields();
@@ -253,7 +256,7 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
$price_set_id = CRM_Price_BAO_PriceSet::getFor("civicrm_event", $event_in_cart->event_id);
$amount_level = NULL;
if ($price_set_id) {
- $event_price_values = array();
+ $event_price_values = [];
foreach ($this->_price_values as $key => $value) {
if (preg_match("/event_{$event_in_cart->event_id}_(price.*)/", $key, $matches)) {
$event_price_values[$matches[1]] = $value;
@@ -261,7 +264,7 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
}
$price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE);
$price_set = $price_sets[$price_set_id];
- $price_set_amount = array();
+ $price_set_amount = [];
CRM_Price_BAO_PriceSet::processAmount($price_set['fields'], $event_price_values, $price_set_amount);
$discountCode = $this->_price_values['discountcode'];
if (!empty($discountCode)) {
@@ -300,21 +303,21 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
public function add_line_item($event_in_cart, $class = NULL) {
$amount = 0;
$cost = 0;
- $not_waiting_participants = array();
+ $not_waiting_participants = [];
foreach ($event_in_cart->not_waiting_participants() as $participant) {
$amount += $participant->cost;
$cost = max($cost, $participant->cost);
- $not_waiting_participants[] = array(
+ $not_waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $waiting_participants = array();
+ $waiting_participants = [];
foreach ($event_in_cart->waiting_participants() as $participant) {
- $waiting_participants[] = array(
+ $waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $this->line_items[] = array(
+ $this->line_items[] = [
'amount' => $amount,
'cost' => $cost,
'event' => $event_in_cart->event,
@@ -323,21 +326,11 @@ public function add_line_item($event_in_cart, $class = NULL) {
'num_waiting_participants' => count($waiting_participants),
'waiting_participants' => $waiting_participants,
'class' => $class,
- );
+ ];
$this->sub_total += $amount;
}
- /**
- * Get default from address.
- *
- * @return mixed
- */
- public function getDefaultFrom() {
- $values = CRM_Core_OptionGroup::values('from_email_address');
- return $values[1];
- }
-
/**
* Send email receipt.
*
@@ -355,19 +348,19 @@ public function emailReceipt($events_in_cart, $params) {
$country->find();
$country->fetch();
foreach ($this->line_items as & $line_item) {
- $location_params = array('entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event');
+ $location_params = ['entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event'];
$line_item['location'] = CRM_Core_BAO_Location::getValues($location_params, TRUE);
CRM_Core_BAO_Address::fixAddress($line_item['location']['address'][1]);
}
- $send_template_params = array(
+ $send_template_params = [
'table' => 'civicrm_msg_template',
'contactId' => $this->payer_contact_id,
- 'from' => $this->getDefaultFrom(),
+ 'from' => current(CRM_Core_BAO_Domain::getNameAndEmail(TRUE, TRUE)),
'groupName' => 'msg_tpl_workflow_event',
'isTest' => FALSE,
'toEmail' => $contact_details[1],
'toName' => $contact_details[0],
- 'tplParams' => array(
+ 'tplParams' => [
'billing_name' => "{$params['billing_first_name']} {$params['billing_last_name']}",
'billing_city' => $params["billing_city-{$this->_bltID}"],
'billing_country' => $country->name,
@@ -387,11 +380,11 @@ public function emailReceipt($events_in_cart, $params) {
'transaction_date' => $params['trxn_date'],
'is_pay_later' => $this->is_pay_later,
'pay_later_receipt' => $this->pay_later_receipt,
- ),
+ ],
'valueName' => 'event_registration_receipt',
'PDFFilename' => ts('confirmation') . '.pdf',
- );
- $template_params_to_copy = array(
+ ];
+ $template_params_to_copy = [
'billing_name',
'billing_city',
'billing_country',
@@ -401,7 +394,7 @@ public function emailReceipt($events_in_cart, $params) {
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
- );
+ ];
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->set($template_param_to_copy, $send_template_params['tplParams'][$template_param_to_copy]);
}
@@ -419,7 +412,7 @@ public function emailReceipt($events_in_cart, $params) {
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($self->payment_required && empty($self->_submitValues['is_pay_later'])) {
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
@@ -468,8 +461,8 @@ public function postProcess() {
$main_participants = $this->cart->get_main_event_participants();
foreach ($main_participants as $participant) {
- $defaults = array();
- $ids = array('contact_id' => $participant->contact_id);
+ $defaults = [];
+ $ids = ['contact_id' => $participant->contact_id];
$contact = CRM_Contact_BAO_Contact::retrieve($ids, $defaults);
$contact->is_deleted = 0;
$contact->save();
@@ -477,18 +470,18 @@ public function postProcess() {
$trxn_prefix = 'VR';
if (array_key_exists('billing_contact_email', $params)) {
- $this->payer_contact_id = self::find_or_create_contact($this->getContactID(), array(
+ $this->payer_contact_id = self::find_or_create_contact($this->getContactID(), [
'email' => $params['billing_contact_email'],
'first_name' => $params['billing_first_name'],
'last_name' => $params['billing_last_name'],
'is_deleted' => FALSE,
- ));
+ ]);
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$this->payer_contact_id,
'contact_type'
);
- $billing_fields = array(
+ $billing_fields = [
"billing_first_name" => 1,
"billing_middle_name" => 1,
"billing_last_name" => 1,
@@ -499,7 +492,7 @@ public function postProcess() {
"billing_country_id-{$this->_bltID}" => 1,
"address_name-{$this->_bltID}" => 1,
"email-{$this->_bltID}" => 1,
- );
+ ];
$params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
@@ -513,6 +506,8 @@ public function postProcess() {
$ctype,
TRUE
);
+
+ $params['contact_id'] = $this->payer_contact_id;
}
$params['now'] = date('YmdHis');
@@ -532,11 +527,11 @@ public function postProcess() {
$contribution_statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$params['payment_instrument_id'] = NULL;
if (!empty($params['is_pay_later'])) {
- $params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name');
+ $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check');
$trxn_prefix = 'CK';
}
else {
- $params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Credit Card', 'name');
+ $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Credit Card');
}
if ($this->is_pay_later && empty($params['payment_completed'])) {
$params['contribution_status_id'] = array_search('Pending', $contribution_statuses);
@@ -558,7 +553,7 @@ public function postProcess() {
// n.b. we need to process the subparticipants before main event
// participants so that session attendance can be included in the email
$main_participants = $this->cart->get_main_event_participants();
- $this->all_participants = array();
+ $this->all_participants = [];
foreach ($main_participants as $main_participant) {
$this->all_participants = array_merge($this->all_participants, $this->cart->get_subparticipants($main_participant));
}
@@ -602,21 +597,12 @@ public function postProcess() {
* @throws Exception
*/
public function make_payment(&$params) {
- $config = CRM_Core_Config::singleton();
- if (isset($params["billing_state_province_id-{$this->_bltID}"]) && $params["billing_state_province_id-{$this->_bltID}"]) {
- $params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
- }
-
- if (isset($params["billing_country_id-{$this->_bltID}"]) && $params["billing_country_id-{$this->_bltID}"]) {
- $params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
- }
- $params['ip_address'] = CRM_Utils_System::ipAddress();
- $params['currencyID'] = $config->defaultCurrency;
+ $params = $this->prepareParamsForPaymentProcessor($params);
+ $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
$payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, TRUE);
- $params['month'] = $params['credit_card_exp_date']['M'];
- $params['year'] = $params['credit_card_exp_date']['Y'];
+
try {
$result = $payment->doPayment($params);
}
@@ -625,11 +611,11 @@ public function make_payment(&$params) {
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
}
- $trxnDetails = array(
+ $trxnDetails = [
'trxn_id' => $result['trxn_id'],
'trxn_date' => $result['now'],
'currency' => CRM_Utils_Array::value('currencyID', $result),
- );
+ ];
return $trxnDetails;
}
@@ -658,7 +644,7 @@ public function record_contribution(&$mer_participant, &$params, $event) {
$payer = $params['participant_contact_id'];
}
- $contribParams = array(
+ $contribParams = [
'contact_id' => $payer,
'financial_type_id' => $params['financial_type_id'],
'receive_date' => $params['now'],
@@ -674,16 +660,13 @@ public function record_contribution(&$mer_participant, &$params, $event) {
'payment_instrument_id' => $params['payment_instrument_id'],
'check_number' => CRM_Utils_Array::value('check_number', $params),
'skipLineItem' => 1,
- );
+ ];
if (is_array($this->_paymentProcessor)) {
$contribParams['payment_processor'] = $this->_paymentProcessor['id'];
}
- $contribution = &CRM_Contribute_BAO_Contribution::add($contribParams);
- if (is_a($contribution, 'CRM_Core_Error')) {
- CRM_Core_Error::fatal(ts("There was an error creating a contribution record for your event. Please report this error to the webmaster. Details: %1", array(1 => $contribution->getMessages($contribution))));
- }
+ $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
$mer_participant->contribution_id = $contribution->id;
$params['contributionID'] = $contribution->id;
@@ -694,9 +677,9 @@ public function record_contribution(&$mer_participant, &$params, $event) {
* Save data to session.
*/
public function saveDataToSession() {
- $session_line_items = array();
+ $session_line_items = [];
foreach ($this->line_items as $line_item) {
- $session_line_item = array();
+ $session_line_item = [];
$session_line_item['amount'] = $line_item['amount'];
$session_line_item['cost'] = $line_item['cost'];
$session_line_item['event_id'] = $line_item['event']->id;
@@ -722,12 +705,12 @@ public function setDefaultValues() {
$config = CRM_Core_Config::singleton();
$default_country = new CRM_Core_DAO_Country();
- $default_country->iso_code = $config->defaultContactCountry();
+ $default_country->iso_code = CRM_Core_BAO_Country::defaultContactCountry();
$default_country->find(TRUE);
$defaults["billing_country_id-{$this->_bltID}"] = $default_country->id;
if (self::getContactID() && !self::is_administrator()) {
- $params = array('id' => self::getContactID());
+ $params = ['id' => self::getContactID()];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($contact->email as $email) {
@@ -775,7 +758,7 @@ public function setDefaultValues() {
*/
protected function apply_discount($discountCode, &$price_set_amount, &$cost, $event_id) {
//need better way to determine if cividiscount installed
- $autoDiscount = array();
+ $autoDiscount = [];
$sql = "select is_active from civicrm_extension where name like 'CiviDiscount%'";
$dao = CRM_Core_DAO::executeQuery($sql, '');
while ($dao->fetch()) {
diff --git a/CRM/Event/Cart/Form/Checkout/ThankYou.php b/CRM/Event/Cart/Form/Checkout/ThankYou.php
index 0b1b8d10b42c..991e3724e99e 100644
--- a/CRM/Event/Cart/Form/Checkout/ThankYou.php
+++ b/CRM/Event/Cart/Form/Checkout/ThankYou.php
@@ -15,17 +15,17 @@ public function buildLineItems() {
foreach ($line_items as $line_item) {
$event_in_cart = $this->cart->get_event_in_cart_by_event_id($line_item['event_id']);
- $not_waiting_participants = array();
+ $not_waiting_participants = [];
foreach ($event_in_cart->not_waiting_participants() as $participant) {
- $not_waiting_participants[] = array(
+ $not_waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $waiting_participants = array();
+ $waiting_participants = [];
foreach ($event_in_cart->waiting_participants() as $participant) {
- $waiting_participants[] = array(
+ $waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
$line_item['event'] = $event_in_cart->event;
@@ -43,9 +43,9 @@ public function buildLineItems() {
}
public function buildQuickForm() {
- $defaults = array();
- $ids = array();
- $template_params_to_copy = array(
+ $defaults = [];
+ $ids = [];
+ $template_params_to_copy = [
'billing_name',
'billing_city',
'billing_country',
@@ -55,7 +55,7 @@ public function buildQuickForm() {
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
- );
+ ];
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->assign($template_param_to_copy, $this->get($template_param_to_copy));
}
diff --git a/CRM/Event/Cart/Form/MerParticipant.php b/CRM/Event/Cart/Form/MerParticipant.php
index b618e7886023..ef45df9b54fe 100644
--- a/CRM/Event/Cart/Form/MerParticipant.php
+++ b/CRM/Event/Cart/Form/MerParticipant.php
@@ -19,7 +19,7 @@ public function __construct($participant) {
* @param CRM_Core_Form $form
*/
public function appendQuickForm(&$form) {
- $textarea_size = array('size' => 30, 'maxlength' => 60);
+ $textarea_size = ['size' => 30, 'maxlength' => 60];
$form->add('text', $this->email_field_name(), ts('Email Address'), $textarea_size, TRUE);
list(
@@ -33,12 +33,12 @@ public function appendQuickForm(&$form) {
foreach ($custom_fields_post as $key => $field) {
CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, $this->participant->id);
}
- $custom = CRM_Utils_Array::value('custom', $form->getTemplate()->_tpl_vars, array());
- $form->assign('custom', array_merge($custom, array(
+ $custom = CRM_Utils_Array::value('custom', $form->getTemplate()->_tpl_vars, []);
+ $form->assign('custom', array_merge($custom, [
$this->html_field_name('customPre') => $custom_fields_pre,
$this->html_field_name('customPost') => $custom_fields_post,
$this->html_field_name('number') => $this->name(),
- )));
+ ]));
}
/**
@@ -47,11 +47,11 @@ public function appendQuickForm(&$form) {
* @return array
*/
public static function get_profile_groups($event_id) {
- $ufJoinParams = array(
+ $ufJoinParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent',
'entity_id' => $event_id,
- );
+ ];
$group_ids = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
return $group_ids;
}
@@ -62,7 +62,7 @@ public static function get_profile_groups($event_id) {
public function get_participant_custom_data_fields() {
list($custom_pre_id, $custom_post_id) = self::get_profile_groups($this->participant->event_id);
- $pre_fields = $post_fields = array();
+ $pre_fields = $post_fields = [];
if ($custom_pre_id && CRM_Core_BAO_UFGroup::filterUFGroups($custom_pre_id, $this->participant->contact_id)) {
$pre_fields = CRM_Core_BAO_UFGroup::getFields($custom_pre_id, FALSE, CRM_Core_Action::ADD);
}
@@ -70,7 +70,7 @@ public function get_participant_custom_data_fields() {
$post_fields = CRM_Core_BAO_UFGroup::getFields($custom_post_id, FALSE, CRM_Core_Action::ADD);
}
- return array($pre_fields, $post_fields);
+ return [$pre_fields, $post_fields];
}
/**
@@ -113,7 +113,7 @@ public function name() {
*
* @return CRM_Event_Cart_Form_MerParticipant
*/
- static public function get_form($participant) {
+ public static function get_form($participant) {
return new CRM_Event_Cart_Form_MerParticipant($participant);
}
@@ -121,12 +121,12 @@ static public function get_form($participant) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array(
+ $defaults = [
$this->html_field_name('email') => $this->participant->email,
- );
+ ];
list($custom_fields_pre, $custom_fields_post) = $this->get_participant_custom_data_fields($this->participant->event_id);
$all_fields = $custom_fields_pre + $custom_fields_post;
- $flat = array();
+ $flat = [];
CRM_Core_BAO_UFGroup::setProfileDefaults($this->participant->contact_id, $all_fields, $flat);
foreach ($flat as $name => $field) {
$defaults["field[{$this->participant->id}][{$name}]"] = $field;
diff --git a/CRM/Event/Cart/Page/AddToCart.php b/CRM/Event/Cart/Page/AddToCart.php
index 045d77dbc7ea..494a594e6e6f 100644
--- a/CRM/Event/Cart/Page/AddToCart.php
+++ b/CRM/Event/Cart/Page/AddToCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_AddToCart
*/
class CRM_Event_Cart_Page_AddToCart extends CRM_Core_Page {
+
/**
* This function takes care of all the things common to all pages.
*
@@ -21,10 +22,10 @@ public function run() {
$event_in_cart = $cart->add_event($this->_id);
$url = CRM_Utils_System::url('civicrm/event/view_cart');
- CRM_Utils_System::setUFMessage(ts("%1 has been added to your cart. View your cart.", array(
- 1 => $event_in_cart->event->title,
- 2 => $url,
- )));
+ CRM_Utils_System::setUFMessage(ts("%1 has been added to your cart. View your cart.", [
+ 1 => $event_in_cart->event->title,
+ 2 => $url,
+ ]));
$transaction->commit();
diff --git a/CRM/Event/Cart/Page/CheckoutAJAX.php b/CRM/Event/Cart/Page/CheckoutAJAX.php
index 73f0982923ab..19c7b8559b35 100644
--- a/CRM/Event/Cart/Page/CheckoutAJAX.php
+++ b/CRM/Event/Cart/Page/CheckoutAJAX.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_CheckoutAJAX
*/
class CRM_Event_Cart_Page_CheckoutAJAX {
+
public function add_participant_to_cart() {
$transaction = new CRM_Core_Transaction();
$cart_id = CRM_Utils_Request::retrieve('cart_id', 'Integer');
@@ -11,11 +12,11 @@ public function add_participant_to_cart() {
$cart = CRM_Event_Cart_BAO_Cart::find_by_id($cart_id);
- $params_array = array(
+ $params_array = [
'cart_id' => $cart->id,
'contact_id' => CRM_Event_Cart_Form_Cart::find_or_create_contact(),
'event_id' => $event_id,
- );
+ ];
//XXX security?
$participant = CRM_Event_Cart_BAO_MerParticipant::create($params_array);
diff --git a/CRM/Event/Cart/Page/RemoveFromCart.php b/CRM/Event/Cart/Page/RemoveFromCart.php
index b9d7efbec483..90f6554f902f 100644
--- a/CRM/Event/Cart/Page/RemoveFromCart.php
+++ b/CRM/Event/Cart/Page/RemoveFromCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_RemoveFromCart
*/
class CRM_Event_Cart_Page_RemoveFromCart extends CRM_Core_Page {
+
/**
* This function takes care of all the things common to all pages.
*
@@ -17,7 +18,7 @@ public function run() {
$event_in_cart = $cart->get_event_in_cart_by_event_id($this->_id);
$removed_event = $cart->remove_event_in_cart($event_in_cart->id);
$removed_event_title = $removed_event->event->title;
- CRM_Core_Session::setStatus(ts("%1 has been removed from your cart.", array(1 => $removed_event_title)), '', 'success');
+ CRM_Core_Session::setStatus(ts("%1 has been removed from your cart.", [1 => $removed_event_title]), '', 'success');
$transaction->commit();
return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']);
}
diff --git a/CRM/Event/Cart/Page/ViewCart.php b/CRM/Event/Cart/Page/ViewCart.php
index 84e20dd64e2d..b2a0a7ce0bdb 100644
--- a/CRM/Event/Cart/Page/ViewCart.php
+++ b/CRM/Event/Cart/Page/ViewCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_ViewCart
*/
class CRM_Event_Cart_Page_ViewCart extends CRM_Core_Page {
+
/**
* @return string
*/
diff --git a/CRM/Event/Cart/StateMachine/Checkout.php b/CRM/Event/Cart/StateMachine/Checkout.php
index 337a68a8cb88..3ca22852815a 100644
--- a/CRM/Event/Cart/StateMachine/Checkout.php
+++ b/CRM/Event/Cart/StateMachine/Checkout.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_StateMachine_Checkout
*/
class CRM_Event_Cart_StateMachine_Checkout extends CRM_Core_StateMachine {
+
/**
* @param object $controller
* @param const|int $action
@@ -17,7 +18,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
CRM_Core_Error::statusBounce(ts("You don't have any events in you cart. Please add some events."), CRM_Utils_System::url('civicrm/event'));
}
- $pages = array();
+ $pages = [];
$is_monetary = FALSE;
$is_conference = FALSE;
foreach ($cart->events_in_carts as $event_in_cart) {
@@ -29,10 +30,10 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
foreach ($cart->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_parent_event()) {
foreach ($event_in_cart->participants as $participant) {
- $pages["CRM_Event_Cart_Form_Checkout_ConferenceEvents_{$event_in_cart->event_id}_{$participant->id}"] = array(
+ $pages["CRM_Event_Cart_Form_Checkout_ConferenceEvents_{$event_in_cart->event_id}_{$participant->id}"] = [
'className' => 'CRM_Event_Cart_Form_Checkout_ConferenceEvents',
'title' => "Select {$event_in_cart->event->title} Events For {$participant->email}",
- );
+ ];
}
}
}
diff --git a/CRM/Event/Controller/Registration.php b/CRM/Event/Controller/Registration.php
index 7d0d9cded48d..6a1bf9fabd53 100644
--- a/CRM/Event/Controller/Registration.php
+++ b/CRM/Event/Controller/Registration.php
@@ -1,9 +1,9 @@
__table = 'civicrm_event';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'loc_block_id', 'civicrm_loc_block', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'loc_block_id', 'civicrm_loc_block', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event ID') ,
- 'description' => 'Event',
- 'required' => true,
+ 'title' => ts('Event ID'),
+ 'description' => ts('Event'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event.id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'event_title' => array(
+ ],
+ 'event_title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Title') ,
- 'description' => 'Event Title (e.g. Fall Fundraiser Dinner)',
+ 'title' => ts('Event Title'),
+ 'description' => ts('Event Title (e.g. Fall Fundraiser Dinner)'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.title',
'headerPattern' => '/(event.)?title$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'summary' => array(
+ ],
+ ],
+ 'summary' => [
'name' => 'summary',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Summary') ,
- 'description' => 'Brief summary of event. Text and html allowed. Displayed on Event Registration form and can be used on other CMS pages which need an event summary.',
+ 'title' => ts('Event Summary'),
+ 'description' => ts('Brief summary of event. Text and html allowed. Displayed on Event Registration form and can be used on other CMS pages which need an event summary.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.summary',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'event_description' => array(
+ ],
+ ],
+ 'event_description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Description') ,
- 'description' => 'Full description of event. Text and html allowed. Displayed on built-in Event Information screens.',
+ 'title' => ts('Event Description'),
+ 'description' => ts('Full description of event. Text and html allowed. Displayed on built-in Event Information screens.'),
'rows' => 8,
'cols' => 60,
+ 'where' => 'civicrm_event.description',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'event_type_id' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'event_type_id' => [
'name' => 'event_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event Type') ,
- 'description' => 'Event Type ID.Implicit FK to civicrm_option_value where option_group = event_type.',
+ 'title' => ts('Event Type'),
+ 'description' => ts('Event Type ID.Implicit FK to civicrm_option_value where option_group = event_type.'),
+ 'where' => 'civicrm_event.event_type_id',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'event_type',
'optionEditPath' => 'civicrm/admin/options/event_type',
- )
- ) ,
- 'participant_listing_id' => array(
+ ],
+ ],
+ 'participant_listing_id' => [
'name' => 'participant_listing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Listing') ,
- 'description' => 'Should we expose the participant list? Implicit FK to civicrm_option_value where option_group = participant_listing.',
+ 'title' => ts('Participant Listing'),
+ 'description' => ts('Should we expose the participant list? Implicit FK to civicrm_option_value where option_group = participant_listing.'),
+ 'where' => 'civicrm_event.participant_listing_id',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_listing',
'optionEditPath' => 'civicrm/admin/options/participant_listing',
- )
- ) ,
- 'is_public' => array(
+ ],
+ ],
+ 'is_public' => [
'name' => 'is_public',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Event Public') ,
- 'description' => 'Public events will be included in the iCal feeds. Access to private event information may be limited using ACLs.',
+ 'title' => ts('Is Event Public'),
+ 'description' => ts('Public events will be included in the iCal feeds. Access to private event information may be limited using ACLs.'),
+ 'where' => 'civicrm_event.is_public',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'event_start_date' => array(
+ ],
+ ],
+ 'event_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event Start Date') ,
- 'description' => 'Date and time that event starts.',
- 'import' => true,
+ 'title' => ts('Event Start Date'),
+ 'description' => ts('Date and time that event starts.'),
+ 'import' => TRUE,
'where' => 'civicrm_event.start_date',
'headerPattern' => '/^start|(s(tart\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'event_end_date' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'event_end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event End Date') ,
- 'description' => 'Date and time that event ends. May be NULL if no defined end date/time',
- 'import' => true,
+ 'title' => ts('Event End Date'),
+ 'description' => ts('Date and time that event ends. May be NULL if no defined end date/time'),
+ 'import' => TRUE,
'where' => 'civicrm_event.end_date',
'headerPattern' => '/^end|(e(nd\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'is_online_registration' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'is_online_registration' => [
'name' => 'is_online_registration',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Online Registration') ,
- 'description' => 'If true, include registration link on Event Info page.',
+ 'title' => ts('Is Online Registration'),
+ 'description' => ts('If true, include registration link on Event Info page.'),
+ 'where' => 'civicrm_event.is_online_registration',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'registration_link_text' => array(
+ ],
+ ],
+ 'registration_link_text' => [
'name' => 'registration_link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Registration Link Text') ,
- 'description' => 'Text for link to Event Registration form which is displayed on Event Information screen when is_online_registration is true.',
+ 'title' => ts('Event Registration Link Text'),
+ 'description' => ts('Text for link to Event Registration form which is displayed on Event Information screen when is_online_registration is true.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.registration_link_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'registration_start_date' => array(
+ ],
+ ],
+ 'registration_start_date' => [
'name' => 'registration_start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Registration Start Date') ,
- 'description' => 'Date and time that online registration starts.',
+ 'title' => ts('Registration Start Date'),
+ 'description' => ts('Date and time that online registration starts.'),
+ 'where' => 'civicrm_event.registration_start_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'registration_end_date' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'registration_end_date' => [
'name' => 'registration_end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Registration End Date') ,
- 'description' => 'Date and time that online registration ends.',
+ 'title' => ts('Registration End Date'),
+ 'description' => ts('Date and time that online registration ends.'),
+ 'where' => 'civicrm_event.registration_end_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'max_participants' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'max_participants' => [
'name' => 'max_participants',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Participants') ,
- 'description' => 'Maximum number of registered participants to allow. After max is reached, a custom Event Full message is displayed. If NULL, allow unlimited number of participants.',
+ 'title' => ts('Max Participants'),
+ 'description' => ts('Maximum number of registered participants to allow. After max is reached, a custom Event Full message is displayed. If NULL, allow unlimited number of participants.'),
+ 'where' => 'civicrm_event.max_participants',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'event_full_text' => array(
+ ],
+ ],
+ 'event_full_text' => [
'name' => 'event_full_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Information') ,
- 'description' => 'Message to display on Event Information page and INSTEAD OF Event Registration form if maximum participants are signed up. Can include email address/info about getting on a waiting list, etc. Text and html allowed.',
+ 'title' => ts('Event Information'),
+ 'description' => ts('Message to display on Event Information page and INSTEAD OF Event Registration form if maximum participants are signed up. Can include email address/info about getting on a waiting list, etc. Text and html allowed.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.event_full_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_monetary' => array(
+ ],
+ ],
+ 'is_monetary' => [
'name' => 'is_monetary',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is this a PAID event?') ,
- 'description' => 'If true, one or more fee amounts must be set and a Payment Processor must be configured for Online Event Registration.',
+ 'title' => ts('Is this a PAID event?'),
+ 'description' => ts('If true, one or more fee amounts must be set and a Payment Processor must be configured for Online Event Registration.'),
+ 'where' => 'civicrm_event.is_monetary',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'financial_type_id' => array(
+ ],
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'Financial type assigned to paid event registrations for this event. Required if is_monetary is true.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('Financial type assigned to paid event registrations for this event. Required if is_monetary is true.'),
+ 'where' => 'civicrm_event.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'payment_processor' => array(
+ ],
+ ],
+ 'payment_processor' => [
'name' => 'payment_processor',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processors configured for this Event (if is_monetary is true)',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processors configured for this Event (if is_monetary is true)'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.payment_processor',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_payment_processor',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'is_map' => array(
+ ],
+ ],
+ 'is_map' => [
'name' => 'is_map',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Map Enabled') ,
- 'description' => 'Include a map block on the Event Information page when geocode info is available and a mapping provider has been specified?',
+ 'title' => ts('Map Enabled'),
+ 'description' => ts('Include a map block on the Event Information page when geocode info is available and a mapping provider has been specified?'),
+ 'where' => 'civicrm_event.is_map',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this Event enabled or disabled/cancelled?',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this Event enabled or disabled/cancelled?'),
+ 'where' => 'civicrm_event.is_active',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'fee_label' => array(
+ ],
+ ],
+ 'fee_label' => [
'name' => 'fee_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Fee Label') ,
+ 'title' => ts('Fee Label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.fee_label',
'headerPattern' => '/^fee|(f(ee\s)?label)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_show_location' => array(
+ ],
+ ],
+ 'is_show_location' => [
'name' => 'is_show_location',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('show location') ,
- 'description' => 'If true, show event location.',
+ 'title' => ts('show location'),
+ 'description' => ts('If true, show event location.'),
+ 'where' => 'civicrm_event.is_show_location',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'loc_block_id' => array(
+ ],
+ ],
+ 'loc_block_id' => [
'name' => 'loc_block_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Location Block ID') ,
- 'description' => 'FK to Location Block ID',
+ 'title' => ts('Location Block ID'),
+ 'description' => ts('FK to Location Block ID'),
+ 'where' => 'civicrm_event.loc_block_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_LocBlock',
- ) ,
- 'default_role_id' => array(
+ ],
+ 'default_role_id' => [
'name' => 'default_role_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Role') ,
- 'description' => 'Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.',
- 'import' => true,
+ 'title' => ts('Default Role'),
+ 'description' => ts('Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.'),
+ 'import' => TRUE,
'where' => 'civicrm_event.default_role_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_role',
'optionEditPath' => 'civicrm/admin/options/participant_role',
- )
- ) ,
- 'intro_text' => array(
+ ],
+ ],
+ 'intro_text' => [
'name' => 'intro_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Introductory Message') ,
- 'description' => 'Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.',
+ 'title' => ts('Introductory Message'),
+ 'description' => ts('Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.intro_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'footer_text' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'footer_text' => [
'name' => 'footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Message') ,
- 'description' => 'Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.',
+ 'title' => ts('Footer Message'),
+ 'description' => ts('Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_title' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'confirm_title' => [
'name' => 'confirm_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirmation Title') ,
- 'description' => 'Title for Confirmation page.',
+ 'title' => ts('Confirmation Title'),
+ 'description' => ts('Title for Confirmation page.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_title',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'confirm_text' => array(
+ ],
+ ],
+ 'confirm_text' => [
'name' => 'confirm_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Confirm Text') ,
- 'description' => 'Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.',
+ 'title' => ts('Confirm Text'),
+ 'description' => ts('Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_footer_text' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'confirm_footer_text' => [
'name' => 'confirm_footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Text') ,
- 'description' => 'Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.',
+ 'title' => ts('Footer Text'),
+ 'description' => ts('Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'is_email_confirm' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'is_email_confirm' => [
'name' => 'is_email_confirm',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is confirm email') ,
- 'description' => 'If true, confirmation is automatically emailed to contact on successful registration.',
+ 'title' => ts('Is confirm email'),
+ 'description' => ts('If true, confirmation is automatically emailed to contact on successful registration.'),
+ 'where' => 'civicrm_event.is_email_confirm',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'confirm_email_text' => array(
+ ],
+ ],
+ 'confirm_email_text' => [
'name' => 'confirm_email_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Confirmation Email Text') ,
- 'description' => 'text to include above standard event info on confirmation email. emails are text-only, so do not allow html for now',
+ 'title' => ts('Confirmation Email Text'),
+ 'description' => ts('text to include above standard event info on confirmation email. emails are text-only, so do not allow html for now'),
'rows' => 4,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_email_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_from_name' => array(
+ ],
+ ],
+ 'confirm_from_name' => [
'name' => 'confirm_from_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirm From Name') ,
- 'description' => 'FROM email name used for confirmation emails.',
+ 'title' => ts('Confirm From Name'),
+ 'description' => ts('FROM email name used for confirmation emails.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_from_name',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'confirm_from_email' => array(
+ ],
+ ],
+ 'confirm_from_email' => [
'name' => 'confirm_from_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirm From Email') ,
- 'description' => 'FROM email address used for confirmation emails.',
+ 'title' => ts('Confirm From Email'),
+ 'description' => ts('FROM email address used for confirmation emails.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_from_email',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'cc_confirm' => array(
+ ],
+ ],
+ 'cc_confirm' => [
'name' => 'cc_confirm',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Cc Confirm') ,
- 'description' => 'comma-separated list of email addresses to cc each time a confirmation is sent',
+ 'title' => ts('Cc Confirm'),
+ 'description' => ts('comma-separated list of email addresses to cc each time a confirmation is sent'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.cc_confirm',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'bcc_confirm' => array(
+ ],
+ ],
+ 'bcc_confirm' => [
'name' => 'bcc_confirm',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Bcc Confirm') ,
- 'description' => 'comma-separated list of email addresses to bcc each time a confirmation is sent',
+ 'title' => ts('Bcc Confirm'),
+ 'description' => ts('comma-separated list of email addresses to bcc each time a confirmation is sent'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.bcc_confirm',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'default_fee_id' => array(
+ ],
+ ],
+ 'default_fee_id' => [
'name' => 'default_fee_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Fee ID') ,
- 'description' => 'FK to civicrm_option_value.',
+ 'title' => ts('Default Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'where' => 'civicrm_event.default_fee_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'default_discount_fee_id' => array(
+ ],
+ 'default_discount_fee_id' => [
'name' => 'default_discount_fee_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Discount Fee ID') ,
- 'description' => 'FK to civicrm_option_value.',
+ 'title' => ts('Default Discount Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'where' => 'civicrm_event.default_discount_fee_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'thankyou_title' => array(
+ ],
+ 'thankyou_title' => [
'name' => 'thankyou_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('ThankYou Title') ,
- 'description' => 'Title for ThankYou page.',
+ 'title' => ts('ThankYou Title'),
+ 'description' => ts('Title for ThankYou page.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.thankyou_title',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_text' => array(
+ ],
+ ],
+ 'thankyou_text' => [
'name' => 'thankyou_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('ThankYou Text') ,
- 'description' => 'ThankYou Text.',
+ 'title' => ts('ThankYou Text'),
+ 'description' => ts('ThankYou Text.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.thankyou_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'thankyou_footer_text' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'thankyou_footer_text' => [
'name' => 'thankyou_footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Text') ,
- 'description' => 'Footer message.',
+ 'title' => ts('Footer Text'),
+ 'description' => ts('Footer message.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.thankyou_footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'is_pay_later' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Pay Later Allowed') ,
- 'description' => 'if true - allows the user to send payment directly to the org later',
+ 'title' => ts('Pay Later Allowed'),
+ 'description' => ts('if true - allows the user to send payment directly to the org later'),
+ 'where' => 'civicrm_event.is_pay_later',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'pay_later_text' => array(
+ ],
+ ],
+ 'pay_later_text' => [
'name' => 'pay_later_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Pay Later Text') ,
- 'description' => 'The text displayed to the user in the main form',
+ 'title' => ts('Pay Later Text'),
+ 'description' => ts('The text displayed to the user in the main form'),
+ 'where' => 'civicrm_event.pay_later_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
- 'type' => 'Text',
- ) ,
- ) ,
- 'pay_later_receipt' => array(
+ 'html' => [
+ 'type' => 'RichTextEditor',
+ ],
+ ],
+ 'pay_later_receipt' => [
'name' => 'pay_later_receipt',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Pay Later Receipt Text') ,
- 'description' => 'The receipt sent to the user instead of the normal receipt text',
+ 'title' => ts('Pay Later Receipt Text'),
+ 'description' => ts('The receipt sent to the user instead of the normal receipt text'),
+ 'where' => 'civicrm_event.pay_later_receipt',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_partial_payment' => array(
+ ],
+ ],
+ 'is_partial_payment' => [
'name' => 'is_partial_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Partial Payments Enabled') ,
- 'description' => 'is partial payment enabled for this event',
+ 'title' => ts('Partial Payments Enabled'),
+ 'description' => ts('is partial payment enabled for this event'),
+ 'where' => 'civicrm_event.is_partial_payment',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'initial_amount_label' => array(
+ ],
+ ],
+ 'initial_amount_label' => [
'name' => 'initial_amount_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Initial Amount Label') ,
- 'description' => 'Initial amount label for partial payment',
+ 'title' => ts('Initial Amount Label'),
+ 'description' => ts('Initial amount label for partial payment'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.initial_amount_label',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'initial_amount_help_text' => array(
+ ],
+ ],
+ 'initial_amount_help_text' => [
'name' => 'initial_amount_help_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Initial Amount Help Text') ,
- 'description' => 'Initial amount help text for partial payment',
+ 'title' => ts('Initial Amount Help Text'),
+ 'description' => ts('Initial amount help text for partial payment'),
+ 'where' => 'civicrm_event.initial_amount_help_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'min_initial_amount' => array(
+ ],
+ ],
+ 'min_initial_amount' => [
'name' => 'min_initial_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Minimum Initial Amount') ,
- 'description' => 'Minimum initial amount for partial payment',
- 'precision' => array(
+ 'title' => ts('Minimum Initial Amount'),
+ 'description' => ts('Minimum initial amount for partial payment'),
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_event.min_initial_amount',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_multiple_registrations' => array(
+ ],
+ ],
+ 'is_multiple_registrations' => [
'name' => 'is_multiple_registrations',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Multiple Registrations') ,
- 'description' => 'if true - allows the user to register multiple participants for event',
+ 'title' => ts('Allow Multiple Registrations'),
+ 'description' => ts('if true - allows the user to register multiple participants for event'),
+ 'where' => 'civicrm_event.is_multiple_registrations',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'max_additional_participants' => array(
+ ],
+ ],
+ 'max_additional_participants' => [
'name' => 'max_additional_participants',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum number of additional participants per registration') ,
- 'description' => 'Maximum number of additional participants that can be registered on a single booking',
+ 'title' => ts('Maximum number of additional participants per registration'),
+ 'description' => ts('Maximum number of additional participants that can be registered on a single booking'),
+ 'where' => 'civicrm_event.max_additional_participants',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'allow_same_participant_emails' => array(
+ ],
+ 'allow_same_participant_emails' => [
'name' => 'allow_same_participant_emails',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Does Event allow multiple registrations from same email address?') ,
- 'description' => 'if true - allows the user to register multiple registrations from same email address.',
+ 'title' => ts('Does Event allow multiple registrations from same email address?'),
+ 'description' => ts('if true - allows the user to register multiple registrations from same email address.'),
+ 'where' => 'civicrm_event.allow_same_participant_emails',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'has_waitlist' => array(
+ ],
+ ],
+ 'has_waitlist' => [
'name' => 'has_waitlist',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Waitlist Enabled') ,
- 'description' => 'Whether the event has waitlist support.',
+ 'title' => ts('Waitlist Enabled'),
+ 'description' => ts('Whether the event has waitlist support.'),
+ 'where' => 'civicrm_event.has_waitlist',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'requires_approval' => array(
+ ],
+ ],
+ 'requires_approval' => [
'name' => 'requires_approval',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Requires Approval') ,
- 'description' => 'Whether participants require approval before they can finish registering.',
+ 'title' => ts('Requires Approval'),
+ 'description' => ts('Whether participants require approval before they can finish registering.'),
+ 'where' => 'civicrm_event.requires_approval',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'expiration_time' => array(
+ ],
+ ],
+ 'expiration_time' => [
'name' => 'expiration_time',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Expiration Time') ,
- 'description' => 'Expire pending but unconfirmed registrations after this many hours.',
+ 'title' => ts('Expiration Time'),
+ 'description' => ts('Expire pending but unconfirmed registrations after this many hours.'),
+ 'where' => 'civicrm_event.expiration_time',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'allow_selfcancelxfer' => array(
+ ],
+ ],
+ 'allow_selfcancelxfer' => [
'name' => 'allow_selfcancelxfer',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Self-service Cancellation or Transfer') ,
- 'description' => 'Allow self service cancellation or transfer for event?',
+ 'title' => ts('Allow Self-service Cancellation or Transfer'),
+ 'description' => ts('Allow self service cancellation or transfer for event?'),
+ 'where' => 'civicrm_event.allow_selfcancelxfer',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'selfcancelxfer_time' => array(
+ ],
+ ],
+ 'selfcancelxfer_time' => [
'name' => 'selfcancelxfer_time',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Self-service Cancellation or Transfer Time') ,
- 'description' => 'Number of hours prior to event start date to allow self-service cancellation or transfer.',
+ 'title' => ts('Self-service Cancellation or Transfer Time'),
+ 'description' => ts('Number of hours prior to event start date to allow self-service cancellation or transfer.'),
+ 'where' => 'civicrm_event.selfcancelxfer_time',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'waitlist_text' => array(
+ ],
+ ],
+ 'waitlist_text' => [
'name' => 'waitlist_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Waitlist Text') ,
- 'description' => 'Text to display when the event is full, but participants can signup for a waitlist.',
+ 'title' => ts('Waitlist Text'),
+ 'description' => ts('Text to display when the event is full, but participants can signup for a waitlist.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.waitlist_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'approval_req_text' => array(
+ ],
+ ],
+ 'approval_req_text' => [
'name' => 'approval_req_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Approval Req Text') ,
- 'description' => 'Text to display when the approval is required to complete registration for an event.',
+ 'title' => ts('Approval Req Text'),
+ 'description' => ts('Text to display when the approval is required to complete registration for an event.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.approval_req_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_template' => array(
+ ],
+ ],
+ 'is_template' => [
'name' => 'is_template',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is an Event Template') ,
- 'description' => 'whether the event has template',
- 'required' => true,
+ 'title' => ts('Is an Event Template'),
+ 'description' => ts('whether the event has template'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event.is_template',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'template_title' => array(
+ ],
+ ],
+ 'template_title' => [
'name' => 'template_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Template Title') ,
- 'description' => 'Event Template Title',
+ 'title' => ts('Event Template Title'),
+ 'description' => ts('Event Template Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.template_title',
'headerPattern' => '/(template.)?title$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'created_id' => array(
+ ],
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created By Contact ID') ,
- 'description' => 'FK to civicrm_contact, who created this event',
+ 'title' => ts('Created By Contact ID'),
+ 'description' => ts('FK to civicrm_contact, who created this event'),
+ 'where' => 'civicrm_event.created_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event Created Date') ,
- 'description' => 'Date and time that event was created.',
+ 'title' => ts('Event Created Date'),
+ 'description' => ts('Date and time that event was created.'),
+ 'where' => 'civicrm_event.created_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.currency',
'headerPattern' => '/cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'campaign_id' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this event has been created.',
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this event has been created.'),
+ 'where' => 'civicrm_event.campaign_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'is_share' => array(
+ ],
+ ],
+ 'is_share' => [
'name' => 'is_share',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is shared through social media') ,
- 'description' => 'Can people share the event through social media?',
+ 'title' => ts('Is shared through social media'),
+ 'description' => ts('Can people share the event through social media?'),
+ 'where' => 'civicrm_event.is_share',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_confirm_enabled' => array(
+ ],
+ ],
+ 'is_confirm_enabled' => [
'name' => 'is_confirm_enabled',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is the booking confirmation screen enabled?') ,
- 'description' => 'If false, the event booking confirmation screen gets skipped',
+ 'title' => ts('Is the booking confirmation screen enabled?'),
+ 'description' => ts('If false, the event booking confirmation screen gets skipped'),
+ 'where' => 'civicrm_event.is_confirm_enabled',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'parent_event_id' => array(
+ ],
+ ],
+ 'parent_event_id' => [
'name' => 'parent_event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Parent Event ID') ,
- 'description' => 'Implicit FK to civicrm_event: parent event',
+ 'title' => ts('Parent Event ID'),
+ 'description' => ts('Implicit FK to civicrm_event: parent event'),
+ 'where' => 'civicrm_event.parent_event_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'slot_label_id' => array(
+ ],
+ ],
+ 'slot_label_id' => [
'name' => 'slot_label_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Subevent Slot Label ID') ,
- 'description' => 'Subevent slot label. Implicit FK to civicrm_option_value where option_group = conference_slot.',
+ 'title' => ts('Subevent Slot Label ID'),
+ 'description' => ts('Subevent slot label. Implicit FK to civicrm_option_value where option_group = conference_slot.'),
+ 'where' => 'civicrm_event.slot_label_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'dedupe_rule_group_id' => array(
+ ],
+ ],
+ 'dedupe_rule_group_id' => [
'name' => 'dedupe_rule_group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dedupe Rule') ,
- 'description' => 'Rule to use when matching registrations for this event',
+ 'title' => ts('Dedupe Rule'),
+ 'description' => ts('Rule to use when matching registrations for this event'),
+ 'where' => 'civicrm_event.dedupe_rule_group_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Dedupe_DAO_RuleGroup',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_dedupe_rule_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
'nameColumn' => 'name',
- )
- ) ,
- 'is_billing_required' => array(
+ ],
+ ],
+ 'is_billing_required' => [
'name' => 'is_billing_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is billing block required') ,
- 'description' => 'if true than billing block is required this event',
+ 'title' => ts('Is billing block required'),
+ 'description' => ts('if true than billing block is required this event'),
+ 'where' => 'civicrm_event.is_billing_required',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -1556,10 +1684,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -1567,40 +1696,46 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_event_type_id' => array(
+ $indices = [
+ 'index_event_type_id' => [
'name' => 'index_event_type_id',
- 'field' => array(
+ 'field' => [
0 => 'event_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::event_type_id',
- ) ,
- 'index_participant_listing_id' => array(
+ ],
+ 'index_participant_listing_id' => [
'name' => 'index_participant_listing_id',
- 'field' => array(
+ 'field' => [
0 => 'participant_listing_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::participant_listing_id',
- ) ,
- 'index_parent_event_id' => array(
+ ],
+ 'index_parent_event_id' => [
'name' => 'index_parent_event_id',
- 'field' => array(
+ 'field' => [
0 => 'parent_event_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::parent_event_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/Participant.php b/CRM/Event/DAO/Participant.php
index 9142d60ba405..02f804617033 100644
--- a/CRM/Event/DAO/Participant.php
+++ b/CRM/Event/DAO/Participant.php
@@ -1,563 +1,559 @@
__table = 'civicrm_participant';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_participant_status_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'registered_by_id', 'civicrm_participant', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'discount_id', 'civicrm_discount', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'cart_id', 'civicrm_event_carts', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'transferred_to_contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_id', 'civicrm_event', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_participant_status_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'registered_by_id', 'civicrm_participant', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'discount_id', 'civicrm_discount', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'cart_id', 'civicrm_event_carts', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'transferred_to_contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'participant_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'participant_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant ID') ,
- 'description' => 'Participant Id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Participant ID'),
+ 'description' => ts('Participant Id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.id',
'headerPattern' => '/(^(participant(.)?)?id$)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_contact_id' => array(
+ ],
+ 'participant_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.contact_id',
'headerPattern' => '/contact(.?id)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'event_id' => array(
+ ],
+ 'event_id' => [
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event') ,
- 'description' => 'FK to Event ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Event'),
+ 'description' => ts('FK to Event ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.event_id',
'headerPattern' => '/event id$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
- ) ,
- 'participant_status_id' => array(
+ ],
+ 'participant_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status') ,
- 'description' => 'Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Participant Status'),
+ 'description' => ts('Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.status_id',
'headerPattern' => '/(participant.)?(status)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_ParticipantStatusType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_participant_status_type',
'keyColumn' => 'id',
'labelColumn' => 'label',
- )
- ) ,
- 'participant_role_id' => array(
+ ],
+ ],
+ 'participant_role_id' => [
'name' => 'role_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Role') ,
- 'description' => 'Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.',
+ 'title' => ts('Participant Role'),
+ 'description' => ts('Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.role_id',
'headerPattern' => '/(participant.)?(role)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_role',
'optionEditPath' => 'civicrm/admin/options/participant_role',
- )
- ) ,
- 'participant_register_date' => array(
+ ],
+ ],
+ 'participant_register_date' => [
'name' => 'register_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Register date') ,
- 'description' => 'When did contact register for event?',
- 'import' => true,
+ 'title' => ts('Register date'),
+ 'description' => ts('When did contact register for event?'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.register_date',
'headerPattern' => '/^(r(egister\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'participant_source' => array(
+ ],
+ ],
+ 'participant_source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Source') ,
- 'description' => 'Source of this event registration.',
+ 'title' => ts('Participant Source'),
+ 'description' => ts('Source of this event registration.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.source',
'headerPattern' => '/(participant.)?(source)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_fee_level' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'participant_fee_level' => [
'name' => 'fee_level',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Fee level') ,
- 'description' => 'Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
- we store the label value and not the key
- ',
- 'import' => true,
+ 'title' => ts('Fee level'),
+ 'description' => ts('Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
+ we store the label value and not the key'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_level',
'headerPattern' => '/^(f(ee\s)?level)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_is_test' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND,
+ ],
+ 'participant_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.is_test',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_is_pay_later' => array(
+ ],
+ 'participant_is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Pay Later') ,
- 'import' => true,
+ 'title' => ts('Is Pay Later'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.is_pay_later',
'headerPattern' => '/(is.)?(pay(.)?later)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_fee_amount' => array(
+ ],
+ 'participant_fee_amount' => [
'name' => 'fee_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Fee Amount') ,
- 'description' => 'actual processor fee if known - may be 0.',
- 'precision' => array(
+ 'title' => ts('Fee Amount'),
+ 'description' => ts('actual processor fee if known - may be 0.'),
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_amount',
'headerPattern' => '/fee(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_registered_by_id' => array(
+ ],
+ 'participant_registered_by_id' => [
'name' => 'registered_by_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Registered By ID') ,
- 'description' => 'FK to Participant ID',
- 'import' => true,
+ 'title' => ts('Registered By ID'),
+ 'description' => ts('FK to Participant ID'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.registered_by_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
- ) ,
- 'participant_discount_id' => array(
+ ],
+ 'participant_discount_id' => [
'name' => 'discount_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Discount ID') ,
- 'description' => 'FK to Discount ID',
+ 'title' => ts('Discount ID'),
+ 'description' => ts('FK to Discount ID'),
+ 'where' => 'civicrm_participant.discount_id',
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Discount',
- ) ,
- 'participant_fee_currency' => array(
+ ],
+ 'participant_fee_currency' => [
'name' => 'fee_currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Fee Currency') ,
- 'description' => '3 character string, value derived from config setting.',
+ 'title' => ts('Fee Currency'),
+ 'description' => ts('3 character string, value derived from config setting.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_currency',
'headerPattern' => '/(fee)?.?cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'participant_campaign_id' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'participant_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this participant has been registered.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this participant has been registered.'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'discount_amount' => array(
+ ],
+ ],
+ 'discount_amount' => [
'name' => 'discount_amount',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Discount Amount') ,
- 'description' => 'Discount Amount',
+ 'title' => ts('Discount Amount'),
+ 'description' => ts('Discount Amount'),
+ 'where' => 'civicrm_participant.discount_amount',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'cart_id' => array(
+ ],
+ 'cart_id' => [
'name' => 'cart_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event Cart ID') ,
- 'description' => 'FK to civicrm_event_carts',
+ 'title' => ts('Event Cart ID'),
+ 'description' => ts('FK to civicrm_event_carts'),
+ 'where' => 'civicrm_participant.cart_id',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
- ) ,
- 'must_wait' => array(
+ ],
+ 'must_wait' => [
'name' => 'must_wait',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Must Wait on List') ,
- 'description' => 'On Waiting List',
+ 'title' => ts('Must Wait on List'),
+ 'description' => ts('On Waiting List'),
+ 'where' => 'civicrm_participant.must_wait',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'transferred_to_contact_id' => array(
+ ],
+ 'transferred_to_contact_id' => [
'name' => 'transferred_to_contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Transferred to Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'import' => true,
+ 'title' => ts('Transferred to Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.transferred_to_contact_id',
'headerPattern' => '/transfer(.?id)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -565,10 +561,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -576,32 +573,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_status_id' => array(
+ $indices = [
+ 'index_status_id' => [
'name' => 'index_status_id',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_participant::0::status_id',
- ) ,
- 'index_role_id' => array(
+ ],
+ 'index_role_id' => [
'name' => 'index_role_id',
- 'field' => array(
+ 'field' => [
0 => 'role_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_participant::0::role_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/ParticipantPayment.php b/CRM/Event/DAO/ParticipantPayment.php
index ca92fc99c0f9..509fff0ee81b 100644
--- a/CRM/Event/DAO/ParticipantPayment.php
+++ b/CRM/Event/DAO/ParticipantPayment.php
@@ -1,171 +1,161 @@
__table = 'civicrm_participant_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'participant_id', 'civicrm_participant', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'participant_id', 'civicrm_participant', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment ID') ,
- 'description' => 'Participant Payment Id',
- 'required' => true,
+ 'title' => ts('Payment ID'),
+ 'description' => ts('Participant Payment Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
- ) ,
- 'participant_id' => array(
+ ],
+ 'participant_id' => [
'name' => 'participant_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant ID') ,
- 'description' => 'Participant Id (FK)',
- 'required' => true,
+ 'title' => ts('Participant ID'),
+ 'description' => ts('Participant Id (FK)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.participant_id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
- 'required' => true,
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.contribution_id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -173,10 +163,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -184,26 +175,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contribution_participant' => array(
+ $indices = [
+ 'UI_contribution_participant' => [
'name' => 'UI_contribution_participant',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'participant_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_participant_payment::1::contribution_id::participant_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/ParticipantStatusType.php b/CRM/Event/DAO/ParticipantStatusType.php
index a902d4432f76..05cf5eccbc7b 100644
--- a/CRM/Event/DAO/ParticipantStatusType.php
+++ b/CRM/Event/DAO/ParticipantStatusType.php
@@ -1,274 +1,272 @@
__table = 'civicrm_participant_status_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status Type ID') ,
- 'description' => 'unique participant status type id',
- 'required' => true,
+ 'title' => ts('Participant Status Type ID'),
+ 'description' => ts('unique participant status type id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_status_type.id',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'participant_status' => array(
+ ],
+ 'participant_status' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status') ,
- 'description' => 'non-localized name of the status type',
+ 'title' => ts('Participant Status'),
+ 'description' => ts('non-localized name of the status type'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant_status_type.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status Label') ,
- 'description' => 'localized label for display of this status type',
+ 'title' => ts('Participant Status Label'),
+ 'description' => ts('localized label for display of this status type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_participant_status_type.label',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 1,
- ) ,
- 'class' => array(
+ ],
+ 'class' => [
'name' => 'class',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status Class') ,
- 'description' => 'the general group of status type this one belongs to',
+ 'title' => ts('Participant Status Class'),
+ 'description' => ts('the general group of status type this one belongs to'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_participant_status_type.class',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Event_PseudoConstant::participantStatusClassOptions',
- )
- ) ,
- 'is_reserved' => array(
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status Is Reserved?>') ,
- 'description' => 'whether this is a status type required by the system',
+ 'title' => ts('Participant Status Is Reserved?>'),
+ 'description' => ts('whether this is a status type required by the system'),
+ 'where' => 'civicrm_participant_status_type.is_reserved',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status is Active') ,
- 'description' => 'whether this status type is active',
+ 'title' => ts('Participant Status is Active'),
+ 'description' => ts('whether this status type is active'),
+ 'where' => 'civicrm_participant_status_type.is_active',
'default' => '1',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'is_counted' => array(
+ ],
+ 'is_counted' => [
'name' => 'is_counted',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status Counts?') ,
- 'description' => 'whether this status type is counted against event size limit',
+ 'title' => ts('Participant Status Counts?'),
+ 'description' => ts('whether this status type is counted against event size limit'),
+ 'where' => 'civicrm_participant_status_type.is_counted',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'weight' => array(
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'controls sort order',
- 'required' => true,
+ 'title' => ts('Order'),
+ 'description' => ts('controls sort order'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_status_type.weight',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'visibility_id' => array(
+ ],
+ 'visibility_id' => [
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status Visibility') ,
- 'description' => 'whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group',
+ 'title' => ts('Participant Status Visibility'),
+ 'description' => ts('whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group'),
+ 'where' => 'civicrm_participant_status_type.visibility_id',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -276,10 +274,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_status_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_status_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -287,15 +286,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_status_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_status_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Form/EventFees.php b/CRM/Event/Form/EventFees.php
index ba7aa9ccd818..dec7b6fd3c00 100644
--- a/CRM/Event/Form/EventFees.php
+++ b/CRM/Event/Form/EventFees.php
@@ -1,9 +1,9 @@
_eventId) {
//get receipt text and financial type
- $returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
- $details = array();
+ $returnProperities = ['confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date'];
+ $details = [];
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
if (!empty($details[$form->_eventId]['financial_type_id'])) {
$defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
@@ -84,12 +84,12 @@ public static function setDefaultValues(&$form) {
}
if ($form->_pId) {
- $ids = array();
- $params = array('id' => $form->_pId);
+ $ids = [];
+ $params = ['id' => $form->_pId];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
if ($form->_action == CRM_Core_Action::UPDATE) {
- $discounts = array();
+ $discounts = [];
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
@@ -113,7 +113,7 @@ public static function setDefaultValues(&$form) {
$defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
}
- list($defaults[$form->_pId]['receive_date'], $defaults[$form->_pId]['receive_date_time']) = CRM_Utils_Date::setDateDefaults();
+ $defaults[$form->_pId]['receive_date'] = date('Y-m-d H:i:s');
}
//CRM-11601 we should keep the record contribution
@@ -139,12 +139,6 @@ public static function setDefaultValues(&$form) {
$billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
$defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
-
- // // hack to simplify credit card entry for testing
- // $defaults[$form->_pId]['credit_card_type'] = 'Visa';
- // $defaults[$form->_pId]['credit_card_number'] = '4807731747657838';
- // $defaults[$form->_pId]['cvv2'] = '000';
- // $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
}
// if user has selected discount use that to set default
@@ -179,11 +173,11 @@ public static function setDefaultValues(&$form) {
if ($priceSetId) {
// get price set default values, CRM-4090
if (in_array(get_class($form),
- array(
+ [
'CRM_Event_Form_Participant',
'CRM_Event_Form_Registration_Register',
'CRM_Event_Form_Registration_AdditionalParticipant',
- )
+ ]
)) {
$priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
if (!empty($priceSetValues)) {
@@ -226,22 +220,18 @@ public static function setDefaultValues(&$form) {
// CRM-4395
if ($contriId = $form->get('onlinePendingContributionId')) {
+ $defaults[$form->_pId]['record_contribution'] = 1;
$contribution = new CRM_Contribute_DAO_Contribution();
$contribution->id = $contriId;
$contribution->find(TRUE);
- foreach (array(
- 'financial_type_id',
- 'payment_instrument_id',
- 'contribution_status_id',
- 'receive_date',
- 'total_amount',
- ) as $f) {
- if ($f == 'receive_date') {
- list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->$f);
- }
- else {
- $defaults[$form->_pId][$f] = $contribution->$f;
- }
+ foreach ([
+ 'financial_type_id',
+ 'payment_instrument_id',
+ 'contribution_status_id',
+ 'receive_date',
+ 'total_amount',
+ ] as $f) {
+ $defaults[$form->_pId][$f] = $contribution->$f;
}
}
return $defaults[$form->_pId];
@@ -257,7 +247,7 @@ public static function setDefaultValues(&$form) {
* @return array
*/
public static function setDefaultPriceSet($participantID, $eventID = NULL, $includeQtyZero = TRUE) {
- $defaults = array();
+ $defaults = [];
if (!$eventID && $participantID) {
$eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
}
@@ -278,7 +268,7 @@ public static function setDefaultPriceSet($participantID, $eventID = NULL, $incl
!CRM_Utils_System::isNull($lineItems[$participantID])
) {
- $priceFields = $htmlTypes = $optionValues = array();
+ $priceFields = $htmlTypes = $optionValues = [];
foreach ($lineItems[$participantID] as $lineId => $items) {
$priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
$priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
@@ -348,7 +338,7 @@ public static function buildQuickForm(&$form) {
// make sure this is for backoffice registration.
if ($form->getName() == 'Participant') {
$eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
- $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
+ $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, ['id' => 'hidden_eventFullMsg']);
}
}
@@ -357,19 +347,19 @@ public static function buildQuickForm(&$form) {
$form->_pId, 'contribution_id', 'participant_id'
)
) {
- $form->_online = TRUE;
+ $form->_online = !$form->isBackOffice;
}
}
if ($form->_isPaidEvent) {
- $params = array('id' => $form->_eventId);
+ $params = ['id' => $form->_eventId];
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
- $form->_values = array();
+ $form->_values = [];
CRM_Event_Form_Registration::initEventFee($form, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
- $lineItem = array();
+ $lineItem = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
@@ -383,7 +373,7 @@ public static function buildQuickForm(&$form) {
$form->assign('totalTaxAmount', $totalTaxAmount);
}
$form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
- $discounts = array();
+ $discounts = [];
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
@@ -392,11 +382,11 @@ public static function buildQuickForm(&$form) {
$element = $form->add('select', 'discount_id',
ts('Discount Set'),
- array(
+ [
0 => ts('- select -'),
- ) + $discounts,
+ ] + $discounts,
FALSE,
- array('class' => "crm-select2")
+ ['class' => "crm-select2"]
);
if ($form->_online) {
@@ -414,7 +404,7 @@ public static function buildQuickForm(&$form) {
CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
if (!$form->_mode) {
$form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
- array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);")
+ ['onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);"]
);
// Check permissions for financial type first
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
@@ -426,15 +416,15 @@ public static function buildQuickForm(&$form) {
$form->add('select', 'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialTypes
+ ['' => ts('- select -')] + $financialTypes
);
- $form->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
+ $form->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
$form->add('select', 'payment_instrument_id',
ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
- FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
// don't show transaction id in batch update mode
$path = CRM_Utils_System::currentPath();
@@ -442,28 +432,13 @@ public static function buildQuickForm(&$form) {
if ($path != 'civicrm/contact/search/basic') {
$form->add('text', 'trxn_id', ts('Transaction ID'));
$form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
- 'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id')
+ 'objectExists', ['CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id']
);
$form->assign('showTransactionId', TRUE);
}
- $status = CRM_Contribute_PseudoConstant::contributionStatus();
-
- // CRM-14417 suppressing contribution statuses that are NOT relevant to new participant registrations
- $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
- foreach (array(
- 'Cancelled',
- 'Failed',
- 'In Progress',
- 'Overdue',
- 'Refunded',
- 'Pending refund',
- ) as $suppress) {
- unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
- }
-
$form->add('select', 'contribution_status_id',
- ts('Payment Status'), $status
+ ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('participant')
);
$form->add('text', 'check_number', ts('Check Number'),
@@ -485,7 +460,7 @@ public static function buildQuickForm(&$form) {
$form->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
- array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
+ ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
);
$form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
diff --git a/CRM/Event/Form/ManageEvent.php b/CRM/Event/Form/ManageEvent.php
index d285a74cc704..e1d6b8c255ae 100644
--- a/CRM/Event/Form/ManageEvent.php
+++ b/CRM/Event/Form/ManageEvent.php
@@ -1,9 +1,9 @@
set('selectedChild', $selectedChild);
+ $this->assign('selectedChild', $selectedChild);
+ }
+ }
+
/**
* Set variables up before form is built.
*/
@@ -120,7 +138,7 @@ public function preProcess() {
}
$this->_single = TRUE;
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $eventInfo);
// its an update mode, do a permission check
@@ -153,33 +171,21 @@ public function preProcess() {
$this->assign('isTemplate', $this->_isTemplate);
+ // Set "Manage Event" Title
+ $title = NULL;
if ($this->_id) {
if ($this->_isTemplate) {
- $title = CRM_Utils_Array::value('template_title', $eventInfo);
- CRM_Utils_System::setTitle(ts('Edit Event Template') . " - $title");
+ $title = ts('Edit Event Template') . ' - ' . CRM_Utils_Array::value('template_title', $eventInfo);
}
else {
- $configureText = ts('Configure Event');
- $title = CRM_Utils_Array::value('title', $eventInfo);
- //If it is a repeating event change title
- if ($this->_isRepeatingEvent) {
- $configureText = 'Configure Repeating Event';
- }
- CRM_Utils_System::setTitle($configureText . " - $title");
+ $configureText = $this->_isRepeatingEvent ? ts('Configure Repeating Event') : ts('Configure Event');
+ $title = $configureText . ' - ' . CRM_Utils_Array::value('title', $eventInfo);
}
- $this->assign('title', $title);
}
elseif ($this->_action & CRM_Core_Action::ADD) {
- if ($this->_isTemplate) {
- $title = ts('New Event Template');
- CRM_Utils_System::setTitle($title);
- }
- else {
- $title = ts('New Event');
- CRM_Utils_System::setTitle($title);
- }
- $this->assign('title', $title);
+ $title = $this->_isTemplate ? ts('New Event Template') : ts('New Event');
}
+ $this->setTitle($title);
if (CRM_Core_Permission::check('view event participants') &&
CRM_Core_Permission::check('view all contacts')
@@ -203,12 +209,12 @@ public function preProcess() {
$ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
$ufCreate = CRM_ACL_API::group(CRM_Core_Permission::CREATE, NULL, 'civicrm_uf_group', $ufGroups);
$ufEdit = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_uf_group', $ufGroups);
- $checkPermission = array(
- array(
+ $checkPermission = [
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- );
+ ],
+ ];
if (CRM_Core_Permission::check($checkPermission) || !empty($ufCreate) || !empty($ufEdit)) {
$this->assign('perm', TRUE);
}
@@ -218,7 +224,7 @@ public function preProcess() {
// Set Done button URL and breadcrumb. Templates go back to Manage Templates,
// otherwise go to Manage Event for new event or ManageEventEdit if event if exists.
- $breadCrumb = array();
+ $breadCrumb = [];
if (!$this->_isTemplate) {
if ($this->_id) {
$this->_doneUrl = CRM_Utils_System::url(CRM_Utils_System::currentPath(),
@@ -229,22 +235,22 @@ public function preProcess() {
$this->_doneUrl = CRM_Utils_System::url('civicrm/event/manage',
'reset=1'
);
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Events'),
'url' => $this->_doneUrl,
- ),
- );
+ ],
+ ];
}
}
else {
$this->_doneUrl = CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Event Templates'),
'url' => $this->_doneUrl,
- ),
- );
+ ],
+ ];
}
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -255,19 +261,21 @@ public function preProcess() {
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$this->_campaignID = CRM_Utils_Array::value('campaign_id', $defaults);
}
elseif ($this->_templateId) {
- $params = array('id' => $this->_templateId);
+ $params = ['id' => $this->_templateId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$defaults['is_template'] = $this->_isTemplate;
$defaults['template_id'] = $defaults['id'];
unset($defaults['id']);
+ unset($defaults['start_date']);
+ unset($defaults['end_date']);
}
else {
$defaults['is_active'] = 1;
@@ -303,44 +311,44 @@ public function buildQuickForm() {
}
if ($this->_single) {
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and Done'),
'spacing' => ' ',
'subName' => 'done',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
else {
- $buttons = array();
+ $buttons = [];
if (!$this->_first) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'back',
'name' => ts('Previous'),
'spacing' => ' ',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
}
@@ -357,7 +365,7 @@ public function endPostProcess() {
switch ($className) {
case 'Event':
$attributes = $this->getVar('_attributes');
- $subPage = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
+ $subPage = CRM_Utils_Request::retrieveComponent($attributes);
break;
case 'EventInfo':
@@ -374,8 +382,8 @@ public function endPostProcess() {
}
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
- array(1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className))
- ), ts('Saved'), 'success');
+ [1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className)]
+ ), $this->getTitle(), 'success');
$config = CRM_Core_Config::singleton();
if (in_array('CiviCampaign', $config->enableComponents)) {
@@ -423,7 +431,7 @@ public function getTemplateFileName() {
*/
public static function addProfileEditScripts() {
CRM_UF_Page_ProfileEditor::registerProfileScripts();
- CRM_UF_Page_ProfileEditor::registerSchemas(array('IndividualModel', 'ParticipantModel'));
+ CRM_UF_Page_ProfileEditor::registerSchemas(['IndividualModel', 'ParticipantModel']);
}
}
diff --git a/CRM/Event/Form/ManageEvent/Conference.php b/CRM/Event/Form/ManageEvent/Conference.php
index f15b66cb4b4e..2a47fa85c904 100644
--- a/CRM/Event/Form/ManageEvent/Conference.php
+++ b/CRM/Event/Form/ManageEvent/Conference.php
@@ -1,9 +1,9 @@
add('select',
'slot_label_id',
ts('Conference Slot'),
- array(
+ [
'' => ts('- select -'),
- ) + $slots,
+ ] + $slots,
FALSE
);
- $this->addEntityRef('parent_event_id', ts('Parent Event'), array(
- 'entity' => 'event',
- 'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- )
- );
+ $this->addEntityRef('parent_event_id', ts('Parent Event'), [
+ 'entity' => 'Event',
+ 'placeholder' => ts('- any -'),
+ 'select' => ['minimumInputLength' => 0],
+ ]);
parent::buildQuickForm();
}
diff --git a/CRM/Event/Form/ManageEvent/Delete.php b/CRM/Event/Form/ManageEvent/Delete.php
index e74c31f70ffe..9259d1d7b4fb 100644
--- a/CRM/Event/Form/ManageEvent/Delete.php
+++ b/CRM/Event/Form/ManageEvent/Delete.php
@@ -1,9 +1,9 @@
assign('title', $this->_title);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => $this->_isTemplate ? ts('Delete Event Template') : ts('Delete Event'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -91,17 +91,17 @@ public function postProcess() {
if ($participant->find()) {
$searchURL = CRM_Utils_System::url('civicrm/event/search', 'reset=1');
CRM_Core_Session::setStatus(ts('This event cannot be deleted because there are participant records linked to it. If you want to delete this event, you must first find the participants linked to this event and delete them. You can use use CiviEvent >> Find Participants page .',
- array(1 => $searchURL)
+ [1 => $searchURL]
), ts('Deletion Error'), 'error');
return;
}
CRM_Event_BAO_Event::del($this->_id);
if ($this->_isTemplate) {
- CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Template Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' has been deleted.", [1 => $this->_title]), ts('Template Deleted'), 'success');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1'));
}
else {
- CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Event Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' has been deleted.", [1 => $this->_title]), ts('Event Deleted'), 'success');
}
}
diff --git a/CRM/Event/Form/ManageEvent/EventInfo.php b/CRM/Event/Form/ManageEvent/EventInfo.php
index 4c665a3d2972..b11e8d50f3b4 100644
--- a/CRM/Event/Form/ManageEvent/EventInfo.php
+++ b/CRM/Event/Form/ManageEvent/EventInfo.php
@@ -1,9 +1,9 @@
setSelectedChild('settings');
- if ($this->_id) {
- $this->assign('entityID', $this->_id);
+ $entityID = $this->_id ?: $this->_templateId;
+ if ($entityID) {
+ $this->assign('entityID', $entityID);
$eventType = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
- $this->_id,
+ $entityID,
'event_type_id'
);
}
@@ -63,9 +66,9 @@ public function preProcess() {
$this->set('type', 'Event');
$this->set('subType', CRM_Utils_Array::value('event_type_id', $_POST));
$this->assign('customDataSubType', CRM_Utils_Array::value('event_type_id', $_POST));
- $this->set('entityId', $this->_id);
+ $this->set('entityId', $entityID);
- CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_eventType, 1, 'Event', $this->_id);
+ CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_eventType, 1, 'Event', $entityID);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
}
@@ -112,11 +115,7 @@ public function setDefaultValues() {
$defaults['event_full_text'] = CRM_Utils_Array::value('event_full_text', $defaults, ts('This event is currently full.'));
$defaults['waitlist_text'] = CRM_Utils_Array::value('waitlist_text', $defaults, ts('This event is currently full. However you can register now and get added to a waiting list. You will be notified if spaces become available.'));
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('start_date', $defaults), 'activityDateTime');
-
- if (!empty($defaults['end_date'])) {
- list($defaults['end_date'], $defaults['end_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['end_date'], 'activityDateTime');
- }
+ $defaults['template_id'] = $this->_templateId;
return $defaults;
}
@@ -129,7 +128,6 @@ public function buildQuickForm() {
if ($this->_eventType) {
$this->assign('customDataSubType', $this->_eventType);
}
- $this->assign('entityId', $this->_id);
$this->_first = TRUE;
$this->applyFilter('__ALL__', 'trim');
@@ -142,11 +140,11 @@ public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::ADD) {
$eventTemplates = CRM_Event_PseudoConstant::eventTemplates();
if (CRM_Utils_System::isNull($eventTemplates) && !$this->_isTemplate) {
- $url = CRM_Utils_System::url('civicrm/admin/eventTemplate', array('reset' => 1));
- CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the Event Templates feature to streamline your workflow.', array(1 => $url)), ts('Tip'), 'info');
+ $url = CRM_Utils_System::url('civicrm/admin/eventTemplate', ['reset' => 1]);
+ CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the Event Templates feature to streamline your workflow.', [1 => $url]), ts('Tip'), 'info');
}
if (!CRM_Utils_System::isNull($eventTemplates)) {
- $this->add('select', 'template_id', ts('From Template'), array('' => ts('- select -')) + $eventTemplates, FALSE, array('class' => 'crm-select2 huge'));
+ $this->add('select', 'template_id', ts('From Template'), ['' => ts('- select -')] + $eventTemplates, FALSE, ['class' => 'crm-select2 huge']);
}
// Make sure this form redirects properly
$this->preventAjaxSubmit();
@@ -156,7 +154,7 @@ public function buildQuickForm() {
$this->add('text', 'title', ts('Event Title'), $attributes['event_title'], !$this->_isTemplate);
$this->addSelect('event_type_id',
- array('onChange' => "CRM.buildCustomData( 'Event', this.value );"),
+ ['onChange' => "CRM.buildCustomData( 'Event', this.value );"],
TRUE
);
@@ -167,28 +165,28 @@ public function buildQuickForm() {
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
- $this->addSelect('default_role_id', array(), TRUE);
+ $this->addSelect('default_role_id', [], TRUE);
- $this->addSelect('participant_listing_id', array('placeholder' => ts('Disabled'), 'option_url' => NULL));
+ $this->addSelect('participant_listing_id', ['placeholder' => ts('Disabled'), 'option_url' => NULL]);
$this->add('textarea', 'summary', ts('Event Summary'), $attributes['summary']);
- $this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description'] + array('preset' => 'civievent'));
+ $this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description'] + ['preset' => 'civievent']);
$this->addElement('checkbox', 'is_public', ts('Public Event'));
$this->addElement('checkbox', 'is_share', ts('Allow sharing through social media?'));
$this->addElement('checkbox', 'is_map', ts('Include Map to Event Location'));
- $this->addDateTime('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDateTime'));
- $this->addDateTime('end_date', ts('End Date / Time'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'start_date', ts('Start'), [], !$this->_isTemplate, ['time' => TRUE]);
+ $this->add('datepicker', 'end_date', ts('End'), [], FALSE, ['time' => TRUE]);
- $this->add('text', 'max_participants', ts('Max Number of Participants'),
- array('onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}")
+ $this->add('number', 'max_participants', ts('Max Number of Participants'),
+ ['onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}"]
);
$this->addRule('max_participants', ts('Max participants should be a positive number'), 'positiveInteger');
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
$waitlist = 0;
if (in_array('On waitlist', $participantStatuses) and in_array('Pending from waitlist', $participantStatuses)) {
- $this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, array('onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"));
+ $this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, ['onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"]);
$this->add('textarea', 'waitlist_text', ts('Waitlist Message'), $attributes['waitlist_text']);
$waitlist = 1;
}
@@ -198,7 +196,7 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_active', ts('Is this Event Active?'));
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_EventInfo', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_EventInfo', 'formRule']);
parent::buildQuickForm();
}
@@ -212,19 +210,10 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
- if (!$values['is_template']) {
- if (CRM_Utils_System::isNull($values['start_date'])) {
- $errors['start_date'] = ts('Start Date and Time are required fields');
- }
- else {
- $start = CRM_Utils_Date::processDate($values['start_date']);
- $end = CRM_Utils_Date::processDate($values['end_date']);
- if (($end < $start) && ($end != 0)) {
- $errors['end_date'] = ts('End date should be after Start date.');
- }
- }
+ if (!empty($values['end_date']) && ($values['end_date'] < $values['start_date'])) {
+ $errors['end_date'] = ts('End date should be after Start date.');
}
//CRM-4286
@@ -239,14 +228,11 @@ public static function formRule($values) {
* Process the form submission.
*/
public function postProcess() {
- $params = $this->controller->exportValues($this->_name);
+ $params = array_merge($this->controller->exportValues($this->_name), $this->_submitValues);
//format params
- $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
- $params['end_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $params),
- CRM_Utils_Array::value('end_date_time', $params),
- TRUE
- );
+ $params['start_date'] = CRM_Utils_Array::value('start_date', $params);
+ $params['end_date'] = CRM_Utils_Array::value('end_date', $params);
$params['has_waitlist'] = CRM_Utils_Array::value('has_waitlist', $params, FALSE);
$params['is_map'] = CRM_Utils_Array::value('is_map', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
@@ -255,24 +241,29 @@ public function postProcess() {
$params['default_role_id'] = CRM_Utils_Array::value('default_role_id', $params, FALSE);
$params['id'] = $this->_id;
- $customFields = CRM_Core_BAO_CustomField::getFields('Event', FALSE, FALSE,
- CRM_Utils_Array::value('event_type_id', $params)
- );
- $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
- $this->_id,
- 'Event'
- );
-
//merge params with defaults from templates
if (!empty($params['template_id'])) {
$params = array_merge(CRM_Event_BAO_Event::getTemplateDefaultValues($params['template_id']), $params);
+ foreach ($params as $key => $value) {
+ $customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
+ if (!empty($customFieldInfo[1])) {
+ $params[str_replace($customFieldInfo[1], '-' . $customFieldInfo[1], $key)] = $value;
+ unset($params[$key]);
+ }
+ }
}
- $event = CRM_Event_BAO_Event::create($params);
+ $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
+ $this->_id,
+ 'Event'
+ );
// now that we have the event’s id, do some more template-based stuff
if (!empty($params['template_id'])) {
- CRM_Event_BAO_Event::copy($params['template_id'], $event, TRUE);
+ $event = CRM_Event_BAO_Event::copy($params['template_id'], $params);
+ }
+ else {
+ $event = CRM_Event_BAO_Event::create($params);
}
$this->set('id', $event->id);
@@ -287,7 +278,7 @@ public function postProcess() {
$url = 'civicrm/event/manage';
$urlParams = 'reset=1';
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
- array(1 => $this->getTitle())
+ [1 => $this->getTitle()]
), ts('Saved'), 'success');
}
diff --git a/CRM/Event/Form/ManageEvent/Fee.php b/CRM/Event/Form/ManageEvent/Fee.php
index beaeb885bfaa..16572e178d7b 100644
--- a/CRM/Event/Form/ManageEvent/Fee.php
+++ b/CRM/Event/Form/ManageEvent/Fee.php
@@ -1,9 +1,9 @@
setSelectedChild('fee');
}
/**
@@ -68,13 +71,13 @@ public function preProcess() {
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
- $parentDefaults = parent::setDefaultValues();
+ parent::setDefaultValues();
$eventId = $this->_id;
- $params = array();
- $defaults = array();
+ $params = [];
+ $defaults = [];
if (isset($eventId)) {
- $params = array('id' => $eventId);
+ $params = ['id' => $eventId];
}
CRM_Event_BAO_Event::retrieve($params, $defaults);
@@ -91,7 +94,7 @@ public function setDefaultValues() {
if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
$this->assign('isQuick', $isQuick);
$priceField = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id');
- $options = array();
+ $options = [];
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField, $options, 'weight', TRUE);
$defaults['price_field_id'] = $priceField;
$countRow = 0;
@@ -115,17 +118,15 @@ public function setDefaultValues() {
$discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($this->_id, 'civicrm_event');
if (!empty($discountedEvent)) {
$defaults['is_discount'] = $i = 1;
- $totalLables = $maxSize = $defaultDiscounts = array();
+ $totalLables = $maxSize = $defaultDiscounts = [];
foreach ($discountedEvent as $optionGroupId) {
$defaults['discount_price_set'][] = $optionGroupId;
- $name = $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
-
- list($defaults["discount_start_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
- 'start_date', 'price_set_id'
- ));
- list($defaults["discount_end_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
- 'end_date', 'price_set_id'
- ));
+ $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
+
+ $defaults["discount_start_date[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
+ 'start_date', 'price_set_id');
+ $defaults["discount_end_date[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
+ 'end_date', 'price_set_id');
$defaultDiscounts[] = CRM_Price_BAO_PriceSet::getSetDetail($optionGroupId);
$i++;
}
@@ -228,12 +229,12 @@ public function setDefaultValues() {
}
$this->_showHide->addToTemplate();
$this->assign('inDate', $this->_inDate);
-
if (!empty($defaults['payment_processor'])) {
- $defaults['payment_processor'] = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',',
+ $defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$defaults['payment_processor']
- );
+ ), '1');
}
+
return $defaults;
}
@@ -241,12 +242,11 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
-
$this->addYesNo('is_monetary',
ts('Paid Event'),
NULL,
NULL,
- array('onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);")
+ ['onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);"]
);
//add currency element.
@@ -255,15 +255,11 @@ public function buildQuickForm() {
$paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor();
$this->assign('paymentProcessor', $paymentProcessor);
-
- $this->addEntityRef('payment_processor', ts('Payment Processor'), array(
- 'entity' => 'PaymentProcessor',
- 'multiple' => TRUE,
- 'api' => array(
- 'params' => array('domain_id' => CRM_Core_Config::domainID()),
- ),
- 'select' => array('minimumInputLength' => 0),
- ));
+ $this->addCheckBox('payment_processor', ts('Payment Processor'),
+ array_flip($paymentProcessor),
+ NULL, NULL, NULL, NULL,
+ [' ', ' ', ' ', ' ' . ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:')
diff --git a/CRM/Event/Form/Task/Email.php b/CRM/Event/Form/Task/Email.php
index 712a88aa7680..406a3a74ba05 100644
--- a/CRM/Event/Form/Task/Email.php
+++ b/CRM/Event/Form/Task/Email.php
@@ -1,9 +1,9 @@
add('select', 'status_change', ts('Change All Statuses'),
- array(
+ [
'' => ts('- select status -'),
- ) + $statuses
+ ] + $statuses
);
$this->assign('context', 'statusChange');
- # CRM-4321: display info on users being notified if any of the below statuses is enabled
+ // CRM-4321: display info on users being notified if any of the below statuses is enabled
parent::assignToTemplate();
parent::buildQuickForm();
}
diff --git a/CRM/Event/Form/Task/PickProfile.php b/CRM/Event/Form/Task/PickProfile.php
index a9bef04f9cd0..8d916b2275a8 100644
--- a/CRM/Event/Form/Task/PickProfile.php
+++ b/CRM/Event/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -112,7 +114,7 @@ public function buildQuickForm() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Event/Form/Task/Print.php b/CRM/Event/Form/Task/Print.php
index da18e47b9741..828e572ded71 100644
--- a/CRM/Event/Form/Task/Print.php
+++ b/CRM/Event/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Participant List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Participant List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Event/Form/Task/Result.php b/CRM/Event/Form/Task/Result.php
index 0c9c8734b1d5..f91778e69329 100644
--- a/CRM/Event/Form/Task/Result.php
+++ b/CRM/Event/Form/Task/Result.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('saved_search_id' => $this->_id);
+ $params = ['saved_search_id' => $this->_id];
CRM_Contact_BAO_Group::retrieve($params, $values);
$groupId = $values['id'];
@@ -101,7 +101,7 @@ public function buildQuickForm() {
}
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $groupId, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $groupId, 'title']
);
}
@@ -123,10 +123,10 @@ public function postProcess() {
$savedSearch->form_values = serialize($this->get('formValues'));
$savedSearch->save();
$this->set('ssID', $savedSearch->id);
- CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", array(1 => $formValues['title'])), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", [1 => $formValues['title']]), ts('Saved'), 'success');
// also create a group that is associated with this saved search only if new saved search
- $params = array();
+ $params = [];
$params['title'] = $formValues['title'];
$params['description'] = $formValues['description'];
$params['visibility'] = 'User and User Admin Only';
diff --git a/CRM/Event/Form/Task/SaveSearch/Update.php b/CRM/Event/Form/Task/SaveSearch/Update.php
index 1687c84798b0..a57171606987 100644
--- a/CRM/Event/Form/Task/SaveSearch/Update.php
+++ b/CRM/Event/Form/Task/SaveSearch/Update.php
@@ -1,9 +1,9 @@
$this->_id);
+ $params = ['saved_search_id' => $this->_id];
CRM_Contact_BAO_Group::retrieve($params, $defaults);
return $defaults;
diff --git a/CRM/Event/Form/Task/SearchTaskHookSample.php b/CRM/Event/Form/Task/SearchTaskHookSample.php
index e18c84f08929..3e143e115471 100644
--- a/CRM/Event/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Event/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_participantIds);
@@ -61,12 +61,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'register_date' => CRM_Utils_Date::customFormat($dao->register_date),
'source' => $dao->source,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -77,14 +77,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Import/Controller.php b/CRM/Event/Import/Controller.php
index 43b355623698..e916a4b0e214 100644
--- a/CRM/Event/Import/Controller.php
+++ b/CRM/Event/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Event/Import/Field.php b/CRM/Event/Import/Field.php
index a4ef9799669a..773a066c63b9 100644
--- a/CRM/Event/Import/Field.php
+++ b/CRM/Event/Import/Field.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -64,7 +64,7 @@ public function buildQuickForm() {
ts('On Duplicate Entries')
);
- $this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
+ $this->setDefaults(['onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP]);
$this->addContactTypeSelector();
}
@@ -75,12 +75,12 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Event_Import_Parser_Participant');
}
diff --git a/CRM/Event/Import/Form/MapField.php b/CRM/Event/Import/Form/MapField.php
index 2f6342027063..161ee1f843af 100644
--- a/CRM/Event/Import/Form/MapField.php
+++ b/CRM/Event/Import/Form/MapField.php
@@ -1,9 +1,9 @@
setDefaults($defaults);
$this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Previous'),
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ array(
+ 'type' => 'back',
+ 'name' => ts('Previous'),
+ ),
+ array(
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ),
+ array(
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ),
+ ));
}
/**
@@ -343,8 +341,8 @@ public static function formRule($fields, $files, $self) {
}
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
- 1 => $threshold,
- )) . ' ' . ts('Or Provide Contact ID or External ID.') . ' '
+ . ts("Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.")
+ . ' '
+ . ts("Click 'Delete' if you want to continue.") . '
'
+ ], '
'
);
+ // if empty option group freeze the option type.
+ if ($emptyOptGroup) {
+ $element->freeze();
+ }
$contactGroups = CRM_Core_PseudoConstant::group();
asort($contactGroups);
@@ -358,7 +377,7 @@ public function buildQuickForm() {
ts('Limit List to Group'),
$contactGroups,
FALSE,
- array('multiple' => 'multiple')
+ ['multiple' => 'multiple', 'class' => 'crm-select2']
);
$this->add('text',
@@ -367,15 +386,10 @@ public function buildQuickForm() {
$attributes['filter']
);
- $this->add('hidden', 'filter_selected', 'Group', array('id' => 'filter_selected'));
-
- //if empty option group freeze the option type.
- if ($emptyOptGroup) {
- $element->freeze();
- }
+ $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
// form fields of Custom Option rows
- $defaultOption = array();
+ $defaultOption = [];
$_showHide = new CRM_Core_ShowHideBlocks('', '');
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
@@ -403,7 +417,7 @@ public function buildQuickForm() {
);
// weight
- $this->add('text', "option_weight[$i]", ts('Order'),
+ $this->add('number', "option_weight[$i]", ts('Order'),
$optionAttributes['weight']
);
@@ -425,7 +439,7 @@ public function buildQuickForm() {
$this->add('number',
'text_length',
ts('Database field length'),
- $attributes['text_length'] + array('min' => 1),
+ $attributes['text_length'] + ['min' => 1],
FALSE
);
$this->addRule('text_length', ts('Value should be a positive number'), 'integer');
@@ -447,11 +461,11 @@ public function buildQuickForm() {
$this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
$this->add('select', 'date_format', ts('Date Format'),
- array('' => ts('- select -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
+ ['' => ts('- select -')] + CRM_Core_SelectValues::getDatePluginInputFormats()
);
$this->add('select', 'time_format', ts('Time'),
- array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
+ ['' => ts('- none -')] + CRM_Core_SelectValues::getTimeFormats()
);
// for Note field
@@ -470,7 +484,8 @@ public function buildQuickForm() {
$this->add('number',
'note_length',
ts('Maximum length') . ' ',
- $attributes['text_length'], // note_length is an alias for the text-length field
+ // note_length is an alias for the text-length field
+ $attributes['text_length'],
FALSE
);
@@ -489,7 +504,7 @@ public function buildQuickForm() {
$this->add('advcheckbox', 'is_required', ts('Required?'));
// checkbox / radio options per line
- $this->add('number', 'options_per_line', ts('Options Per Line'), array('min' => 0));
+ $this->add('number', 'options_per_line', ts('Options Per Line'), ['min' => 0]);
$this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
// default value, help pre, help post, mask, attributes, javascript ?
@@ -515,38 +530,36 @@ public function buildQuickForm() {
// is searchable ?
$this->addElement('advcheckbox',
'is_searchable',
- ts('Is this Field Searchable?'),
- NULL, array('onclick' => "showSearchRange(this)")
+ ts('Is this Field Searchable?')
);
// is searchable by range?
- $searchRange = array();
+ $searchRange = [];
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
$this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
// add buttons
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
// add a form rule to check default value
- $this->addFormRule(array('CRM_Custom_Form_Field', 'formRule'), $this);
+ $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
@@ -555,7 +568,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'")
+ ['onclick' => "location.href='$url'"]
);
}
}
@@ -576,23 +589,24 @@ public function buildQuickForm() {
public static function formRule($fields, $files, $self) {
$default = CRM_Utils_Array::value('default_value', $fields);
- $errors = array();
+ $errors = [];
self::clearEmptyOptions($fields);
//validate field label as well as name.
$title = $fields['label'];
$name = CRM_Utils_String::munge($title, '_', 64);
- $gId = $self->_gid; // CRM-7564
+ // CRM-7564
+ $gId = $self->_gid;
$query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
- $fldCnt = CRM_Core_DAO::singleValueQuery($query, array(
- 1 => array($name, 'String'),
- 2 => array($title, 'String'),
- 3 => array((int) $self->_id, 'Integer'),
- 4 => array($gId, 'Integer'),
- ));
+ $fldCnt = CRM_Core_DAO::singleValueQuery($query, [
+ 1 => [$name, 'String'],
+ 2 => [$title, 'String'],
+ 3 => [(int) $self->_id, 'Integer'],
+ 4 => [$gId, 'Integer'],
+ ]);
if ($fldCnt) {
- $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
+ $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
}
//checks the given custom field name doesnot start with digit
@@ -656,7 +670,7 @@ public static function formRule($fields, $files, $self) {
case 'Country':
if (!empty($default)) {
$query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
- $params = array(1 => array($fields['default_value'], 'String'));
+ $params = [1 => [$fields['default_value'], 'String']];
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['default_value'] = ts('Invalid default value for country.');
}
@@ -670,7 +684,7 @@ public static function formRule($fields, $files, $self) {
FROM civicrm_state_province
WHERE name = %1
OR abbreviation = %1";
- $params = array(1 => array($fields['default_value'], 'String'));
+ $params = [1 => [$fields['default_value'], 'String']];
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['default_value'] = ts('The invalid default value for State/Province data type');
}
@@ -686,7 +700,7 @@ public static function formRule($fields, $files, $self) {
$errors['filter'] = ts("Only 'get' action is supported.");
}
}
- $self->setDefaults(array('filter_selected', $fields['filter_selected']));
+ $self->setDefaults(['filter_selected', $fields['filter_selected']]);
break;
}
}
@@ -707,7 +721,7 @@ public static function formRule($fields, $files, $self) {
if (isset($fields['data_type'][1])) {
$dataField = $fields['data_type'][1];
}
- $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
+ $optionFields = ['Select', 'Multi-Select', 'CheckBox', 'Radio'];
if (isset($fields['option_type']) && $fields['option_type'] == 1) {
//capture duplicate Custom option values
@@ -821,7 +835,7 @@ public static function formRule($fields, $files, $self) {
}
elseif (isset($dataField) &&
in_array($dataField, $optionFields) &&
- !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))
+ !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
) {
if (!$fields['option_group_id']) {
$errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
@@ -832,13 +846,13 @@ public static function formRule($fields, $files, $self) {
FROM civicrm_custom_field
WHERE data_type != %1
AND option_group_id = %2";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
self::$_dataTypeKeys[$fields['data_type'][0]],
'String',
- ),
- 2 => array($fields['option_group_id'], 'Integer'),
- );
+ ],
+ 2 => [$fields['option_group_id'], 'Integer'],
+ ];
$count = CRM_Core_DAO::singleValueQuery($query, $params);
if ($count > 0) {
$errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
@@ -916,12 +930,12 @@ public function postProcess() {
}
//fix for 'is_search_range' field.
- if (in_array($dataTypeKey, array(
+ if (in_array($dataTypeKey, [
1,
2,
3,
5,
- ))) {
+ ])) {
if (empty($params['is_searchable'])) {
$params['is_search_range'] = 0;
}
@@ -945,7 +959,7 @@ public function postProcess() {
// fix for CRM-316
$oldWeight = NULL;
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $fieldValues = array('custom_group_id' => $this->_gid);
+ $fieldValues = ['custom_group_id' => $this->_gid];
if ($this->_id) {
$oldWeight = $this->_values['weight'];
}
@@ -1005,9 +1019,9 @@ public function postProcess() {
$this->_id = $customField->id;
// reset the cache
- CRM_Core_BAO_Cache::deleteGroup('contact fields');
+ Civi::cache('fields')->flush();
- $msg = '
' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
- array(
+ [
1 => $allStatuses[$statusChangeTo],
2 => $results['mailedParticipants'][$processedId],
- )
+ ]
);
}
}
@@ -1669,9 +1669,9 @@ public static function eventFullMessage($eventId, $participantId = NULL) {
$emptySeats = self::eventFull($eventId, FALSE, FALSE);
if (is_string($emptySeats) && $emptySeats !== NULL) {
$maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
- $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", array(
- 1 => $maxParticipants,
- )) . '
';
+ $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", [
+ 1 => $maxParticipants,
+ ]) . '
';
}
$hasWaiting = FALSE;
@@ -1693,10 +1693,10 @@ public static function eventFullMessage($eventId, $participantId = NULL) {
);
$eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can view waitlisted registrations here, or you can continue and register additional participants using this form.",
- array(
+ [
1 => $viewWaitListUrl,
2 => $waitListedCount,
- )
+ ]
);
}
@@ -1737,9 +1737,9 @@ public static function isPrimaryParticipant($participantId) {
*/
public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
- $additionalParticipantIds = array();
+ $additionalParticipantIds = [];
- static $participantStatuses = array();
+ static $participantStatuses = [];
if (empty($participantStatuses)) {
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
@@ -1782,22 +1782,26 @@ public static function getContactParticipantCount($contactID) {
*/
public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
- $ids = array();
+ $ids = [];
if (!$contributionId) {
return $ids;
}
// get primary participant id
- $query = "SELECT participant_id FROM civicrm_participant_payment WHERE contribution_id = {$contributionId}";
- $participantId = CRM_Core_DAO::singleValueQuery($query);
+ $query = "SELECT participant_id
+ FROM civicrm_participant cp
+ LEFT JOIN civicrm_participant_payment cpp ON cp.id = cpp.participant_id
+ WHERE cpp.contribution_id = {$contributionId}
+ AND cp.registered_by_id IS NULL";
+ $participantPayment = CRM_Core_DAO::executeQuery($query);
// get additional participant ids (including cancelled)
- if ($participantId) {
- $ids = array_merge(array(
- $participantId,
- ), self::getAdditionalParticipantIds($participantId,
+ while ($participantPayment->fetch()) {
+ $ids = array_merge($ids, array_merge([
+ $participantPayment->participant_id,
+ ], self::getAdditionalParticipantIds($participantPayment->participant_id,
$excludeCancelled
- ));
+ )));
}
return $ids;
@@ -1814,7 +1818,7 @@ public static function getParticipantIds($contributionId, $excludeCancelled = FA
*/
public static function getAdditionalParticipantUrl($participantIds) {
foreach ($participantIds as $value) {
- $links = array();
+ $links = [];
$details = self::participantDetails($value);
$viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=view&reset=1&id={$value}&cid={$details['cid']}"
@@ -1840,7 +1844,7 @@ public static function getAdditionalParticipantUrl($participantIds) {
* @param int $discountedPriceFieldOptionID
* ID of the civicrm_price_field_value field for the discount id.
*/
- public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID) {
+ public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
$financialTypeID = $contributionParams['contribution']->financial_type_id;
$total_amount = $contributionParams['total_amount'];
@@ -1880,322 +1884,6 @@ public static function deleteContactParticipant($contactId) {
}
}
- /**
- * @param array $params
- * @param int $participantId
- * @param int $contributionId
- * @param $feeBlock
- * @param array $lineItems
- * @param $paidAmount
- * @param int $priceSetId
- */
- public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId) {
- $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
- $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
- $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
- $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
- CRM_Price_BAO_PriceSet::processAmount($feeBlock,
- $params, $lineItems
- );
-
- // get the submitted
- foreach ($feeBlock as $id => $values) {
- CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
- $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
- }
- if (!empty($submittedLineItems)) {
- $insertLines = $submittedLineItems;
-
- $submittedFieldValueIds = array_keys($submittedLineItems);
- $updateLines = array();
- foreach ($previousLineItems as $id => $previousLineItem) {
- // check through the submitted items if the previousItem exists,
- // if found in submitted items, do not use it for new item creations
- if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
- // if submitted line items are existing don't fire INSERT query
- if ($previousLineItem['line_total'] != 0) {
- unset($insertLines[$previousLineItem['price_field_value_id']]);
- }
- else {
- $insertLines[$previousLineItem['price_field_value_id']]['skip'] = TRUE;
- }
- // for updating the line items i.e. use-case - once deselect-option selecting again
- if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
- ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1) ||
- ($previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'])
- ) {
- $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
- $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
- }
- }
- }
-
- $submittedFields = implode(', ', $submittedFieldId);
- $submittedFieldValues = implode(', ', $submittedFieldValueIds);
- }
- $financialItemsArray = array();
- if (!empty($submittedFields) && !empty($submittedFieldValues)) {
- $updateLineItem = "UPDATE civicrm_line_item li
-INNER JOIN civicrm_financial_item fi
- ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
-SET li.qty = 0,
- li.line_total = 0.00,
- li.tax_amount = NULL
-WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
- (price_field_value_id NOT IN ({$submittedFieldValues}))
-";
- CRM_Core_DAO::executeQuery($updateLineItem);
-
- // gathering necessary info to record negative (deselected) financial_item
- $updateFinancialItem = "
- SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
- FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
-WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
-GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
-";
- $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
- $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
- $trxnId['id'] = $trxn['financialTrxnId'];
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
- $updateFinancialItemInfoValues = array();
- while ($updateFinancialItemInfoDAO->fetch()) {
- $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
- $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
- // the below params are not needed
- unset($updateFinancialItemInfoValues['id']);
- unset($updateFinancialItemInfoValues['created_date']);
- // if not submitted and difference is not 0 make it negative
- if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
- // INSERT negative financial_items
- $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
- if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
- $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
- $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
- if ($updateFinancialItemInfoValues['financial_type_id']) {
- $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
- }
- }
- // INSERT negative financial_items for tax amount
- $financialItemsArray[] = $updateFinancialItemInfoValues;
- }
- // if submitted and difference is 0 add a positive entry again
- elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
- $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
- // INSERT financial_items for tax amount
- if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
- isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
- ) {
- $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
- $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
- if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
- $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
- }
- }
- $financialItemsArray[] = $updateFinancialItemInfoValues;
- }
- }
- }
- elseif (empty($submittedFields) && empty($submittedFieldValues)) {
- $updateLineItem = "UPDATE civicrm_line_item li
- INNER JOIN civicrm_financial_item fi
- ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
- SET li.qty = 0,
- li.line_total = 0.00,
- li.tax_amount = NULL
- WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
- CRM_Core_DAO::executeQuery($updateLineItem);
- }
- $amountLevel = array();
- $totalParticipant = $participantCount = 0;
- if (!empty($updateLines)) {
- foreach ($updateLines as $valueId => $vals) {
- $taxAmount = "NULL";
- if (isset($vals['tax_amount'])) {
- $taxAmount = $vals['tax_amount'];
- }
- $amountLevel[] = $vals['label'] . ' - ' . (float) $vals['qty'];
- if (isset($vals['participant_count'])) {
- $participantCount = $vals['participant_count'];
- $totalParticipant += $vals['participant_count'];
- }
- $updateLineItem = "
-UPDATE civicrm_line_item li
-SET li.qty = {$vals['qty']},
- li.line_total = {$vals['line_total']},
- li.tax_amount = {$taxAmount},
- li.unit_price = {$vals['unit_price']},
- li.participant_count = {$participantCount},
- li.label = %1
-WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
- (price_field_value_id = {$valueId})
-";
- CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
- }
- }
- // insert new 'adjusted amount' transaction entry and update contribution entry.
- // ensure entity_financial_trxn table has a linking of it.
- // insert new line items
- if (!empty($insertLines)) {
- foreach ($insertLines as $valueId => $lineParams) {
- if (!array_key_exists('skip', $lineParams)) {
- $lineParams['entity_table'] = 'civicrm_participant';
- $lineParams['entity_id'] = $participantId;
- $lineParams['contribution_id'] = $contributionId;
- $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
- }
- }
- }
-
- // the recordAdjustedAmt code would execute over here
- $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
- if (count($ids) > 1) {
- $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
- }
- else {
- $updatedAmount = $params['amount'];
- }
- if (strlen($params['tax_amount']) != 0) {
- $taxAmount = $params['tax_amount'];
- }
- else {
- $taxAmount = "NULL";
- }
- $displayParticipantCount = '';
- if ($totalParticipant > 0) {
- $displayParticipantCount = ' Participant Count -' . $totalParticipant;
- }
- $updateAmountLevel = NULL;
- if (!empty($amountLevel)) {
- $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
- }
- $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
- $trxnId = array();
- if ($trxn) {
- $trxnId['id'] = $trxn->id;
- foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
- CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
- if (!empty($updateFinancialItemInfoValues['tax'])) {
- $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
- $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
- if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
- $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
- }
- CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
- }
- }
- }
- $fetchCon = array('id' => $contributionId);
- $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
- // insert financial items
- if (!empty($insertLines)) {
- foreach ($insertLines as $valueId => $lineParams) {
- $lineParams['entity_table'] = 'civicrm_participant';
- $lineParams['entity_id'] = $participantId;
- $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
- // insert financial items
- // ensure entity_financial_trxn table has a linking of it.
- $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
- if (isset($lineObj->tax_amount)) {
- CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
- }
- }
- }
-
- // update participant fee_amount column
- $partUpdateFeeAmt['id'] = $participantId;
- $getUpdatedLineItems = "SELECT *
-FROM civicrm_line_item
-WHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
- $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
- $line = array();
- while ($getUpdatedLineItemsDAO->fetch()) {
- $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
- }
-
- $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
- $partUpdateFeeAmt['fee_amount'] = $params['amount'];
- self::add($partUpdateFeeAmt);
-
- //activity creation
- self::addActivityForSelection($participantId, 'Change Registration');
- }
-
- /**
- * Record adjusted amount.
- *
- * @param int $updatedAmount
- * @param int $paidAmount
- * @param int $contributionId
- *
- * @param int $taxAmount
- * @param bool $updateAmountLevel
- *
- * @return bool|\CRM_Core_BAO_FinancialTrxn
- */
- public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
- $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
- $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
- $balanceAmt = $updatedAmount - $paidAmount;
- if ($paidAmount != $pendingAmount) {
- $balanceAmt -= $pendingAmount;
- }
-
- $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
- $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
- $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
- $completedStatusId = array_search('Completed', $contributionStatuses);
-
- $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
- $adjustedTrxn = $skip = FALSE;
- if ($balanceAmt) {
- if ($balanceAmt > 0 && $paidAmount != 0) {
- $contributionStatusVal = $partiallyPaidStatusId;
- }
- elseif ($balanceAmt < 0 && $paidAmount != 0) {
- $contributionStatusVal = $pendingRefundStatusId;
- }
- elseif ($paidAmount == 0) {
- //skip updating the contribution status if no payment is made
- $skip = TRUE;
- $updatedContributionDAO->cancel_date = 'null';
- $updatedContributionDAO->cancel_reason = NULL;
- }
- // update contribution status and total amount without trigger financial code
- // as this is handled in current BAO function used for change selection
- $updatedContributionDAO->id = $contributionId;
- if (!$skip) {
- $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
- }
- $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
- $updatedContributionDAO->fee_amount = 0;
- $updatedContributionDAO->tax_amount = $taxAmount;
- if (!empty($updateAmountLevel)) {
- $updatedContributionDAO->amount_level = $updateAmountLevel;
- }
- $updatedContributionDAO->save();
- // adjusted amount financial_trxn creation
- $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
- array('id' => $contributionId),
- CRM_Core_DAO::$_nullArray,
- CRM_Core_DAO::$_nullArray
- );
- $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
- $adjustedTrxnValues = array(
- 'from_financial_account_id' => NULL,
- 'to_financial_account_id' => $toFinancialAccount,
- 'total_amount' => $balanceAmt,
- 'status_id' => $completedStatusId,
- 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
- 'contribution_id' => $updatedContribution->id,
- 'trxn_date' => date('YmdHis'),
- 'currency' => $updatedContribution->currency,
- );
- $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
- }
- return $adjustedTrxn;
- }
-
/**
* @param int $participantId
* @param $activityType
@@ -2208,28 +1896,24 @@ public static function addActivityForSelection($participantId, $activityType) {
$date = CRM_Utils_Date::currentDBDate();
$event = CRM_Event_BAO_Event::getEvents(0, $eventId);
- $eventTitle = $event[$eventId];
- $subject = "Registration selections changed for $eventTitle";
- $targetCid = $contactId;
- $srcRecId = $participantId;
+ $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
// activity params
- $activityParams = array(
- 'source_contact_id' => $targetCid,
- 'source_record_id' => $srcRecId,
+ $activityParams = [
+ 'source_contact_id' => $contactId,
+ 'source_record_id' => $participantId,
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
'subject' => $subject,
'activity_date_time' => $date,
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
'skipRecentView' => TRUE,
- );
+ ];
// create activity with target contacts
- $session = CRM_Core_Session::singleton();
- $id = $session->get('userID');
+ $id = CRM_Core_Session::singleton()->getLoggedInContactID();;
if ($id) {
$activityParams['source_contact_id'] = $id;
- $activityParams['target_contact_id'][] = $targetCid;
+ $activityParams['target_contact_id'][] = $contactId;
}
// @todo use api & also look at duplication of similar methods.
CRM_Activity_BAO_Activity::create($activityParams);
@@ -2247,8 +1931,8 @@ public static function addActivityForSelection($participantId, $activityType) {
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array('condition' => array());
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
+ $params = ['condition' => []];
if ($fieldName == 'status_id' && $context != 'validate') {
// Get rid of cart-related option if disabled
@@ -2270,9 +1954,9 @@ public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
if (!$contactId) {
return;
}
- $fields = array();
+ $fields = [];
if (!empty($form->_fields)) {
- $removeCustomFieldTypes = array('Participant');
+ $removeCustomFieldTypes = ['Participant'];
foreach ($form->_fields as $name => $dontCare) {
if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
diff --git a/CRM/Event/BAO/ParticipantPayment.php b/CRM/Event/BAO/ParticipantPayment.php
index 40cba7d8a4c8..cb12a2ddc1d6 100644
--- a/CRM/Event/BAO/ParticipantPayment.php
+++ b/CRM/Event/BAO/ParticipantPayment.php
@@ -1,9 +1,9 @@
copyValues($params);
- if (isset($ids['id'])) {
- $participantPayment->id = CRM_Utils_Array::value('id', $ids);
+ if ($id) {
+ $participantPayment->id = $id;
}
else {
$participantPayment->find(TRUE);
}
$participantPayment->save();
- if (isset($ids['id'])) {
- CRM_Utils_Hook::post('edit', 'ParticipantPayment', $ids['id'], $participantPayment);
+ if (empty($participantPayment->contribution_id)) {
+ // For an id update contribution_id may be unknown. We want it
+ // further down so perhaps get it before the hooks.
+ $participantPayment->find(TRUE);
+ }
+ if ($id) {
+ CRM_Utils_Hook::post('edit', 'ParticipantPayment', $participantPayment->id, $participantPayment);
}
else {
- CRM_Utils_Hook::post('create', 'ParticipantPayment', NULL, $participantPayment);
+ CRM_Utils_Hook::post('create', 'ParticipantPayment', $participantPayment->id, $participantPayment);
}
//generally if people are creating participant_payments via the api they won't be setting the line item correctly - we can't help them if they are doing complex transactions
// but if they have a single line item for the contribution we can assume it should refer to the participant line
- $lineItemCount = CRM_Core_DAO::singleValueQuery("select count(*) FROM civicrm_line_item WHERE contribution_id = %1", array(
- 1 => array(
- $participantPayment->contribution_id,
- 'Integer',
- ),
- ));
+ $lineItemCount = CRM_Core_DAO::singleValueQuery("select count(*) FROM civicrm_line_item WHERE contribution_id = %1", [
+ 1 => [
+ $participantPayment->contribution_id,
+ 'Integer',
+ ],
+ ]);
if ($lineItemCount == 1) {
$sql = "UPDATE civicrm_line_item li
SET entity_table = 'civicrm_participant', entity_id = %1
WHERE contribution_id = %2 AND entity_table = 'civicrm_contribution'";
- CRM_Core_DAO::executeQuery($sql, array(
- 1 => array($participantPayment->participant_id, 'Integer'),
- 2 => array($participantPayment->contribution_id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery($sql, [
+ 1 => [$participantPayment->participant_id, 'Integer'],
+ 2 => [$participantPayment->contribution_id, 'Integer'],
+ ]);
}
return $participantPayment;
diff --git a/CRM/Event/BAO/ParticipantStatusType.php b/CRM/Event/BAO/ParticipantStatusType.php
index 434e02762dfe..a897d21cc34f 100644
--- a/CRM/Event/BAO/ParticipantStatusType.php
+++ b/CRM/Event/BAO/ParticipantStatusType.php
@@ -1,9 +1,9 @@
fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
@@ -174,7 +172,7 @@ public static function process($params) {
'end_date' => $dao->end_date,
'expiration_time' => $dao->expiration_time,
'requires_approval' => $dao->requires_approval,
- );
+ ];
}
if (!empty($participantDetails)) {
@@ -199,7 +197,7 @@ public static function process($params) {
//lets get the transaction mechanism.
$transaction = new CRM_Core_Transaction();
- $ids = array($participantId);
+ $ids = [$participantId];
$expiredId = array_search('Expired', $expiredStatuses);
$results = CRM_Event_BAO_Participant::transitionParticipants($ids, $expiredId, $values['status_id'], TRUE, TRUE);
$transaction->commit();
@@ -249,7 +247,7 @@ public static function process($params) {
//get the additional participant if any.
$additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
- $allIds = array($participantId);
+ $allIds = [$participantId];
if (!empty($additionalIds)) {
$allIds = array_merge($allIds, $additionalIds);
}
@@ -260,7 +258,7 @@ public static function process($params) {
if (($requiredSpaces <= $eventOpenSpaces) || ($eventOpenSpaces === NULL)) {
$transaction = new CRM_Core_Transaction();
- $ids = array($participantId);
+ $ids = [$participantId];
$updateStatusId = array_search('Pending from waitlist', $pendingStatuses);
//lets take a call to make pending or need approval
@@ -321,7 +319,7 @@ public static function process($params) {
}
}
- return array('is_error' => 0, 'messages' => $returnMessages);
+ return ['is_error' => 0, 'messages' => $returnMessages];
}
}
diff --git a/CRM/Event/BAO/Query.php b/CRM/Event/BAO/Query.php
index 09c32b959dcf..03d83044cb10 100644
--- a/CRM/Event/BAO/Query.php
+++ b/CRM/Event/BAO/Query.php
@@ -1,9 +1,9 @@
_returnProperties['event_type_id'])) {
- $query->_select['event_type_id'] = "event_type.id as event_type_id";
+ $query->_select['event_type_id'] = "civicrm_event.event_type_id as event_type_id";
$query->_element['event_type_id'] = 1;
- $query->_tables['event_type'] = 1;
- $query->_whereTables['event_type'] = 1;
+ $query->_tables['civicrm_event'] = 1;
+ $query->_whereTables['civicrm_event'] = 1;
}
//add status_id
@@ -154,10 +154,10 @@ public static function select(&$query) {
$query->_element['participant_role_id'] = 1;
$query->_tables['civicrm_participant'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
- $query->_pseudoConstantsSelect['participant_role_id'] = array(
+ $query->_pseudoConstantsSelect['participant_role_id'] = [
'pseudoField' => 'participant_role_id',
'idCol' => 'participant_role_id',
- );
+ ];
}
//add participant_role
@@ -166,10 +166,10 @@ public static function select(&$query) {
$query->_element['participant_role'] = 1;
$query->_tables['participant_role'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
- $query->_pseudoConstantsSelect['participant_role'] = array(
+ $query->_pseudoConstantsSelect['participant_role'] = [
'pseudoField' => 'participant_role',
'idCol' => 'participant_role',
- );
+ ];
}
//add register date
@@ -187,10 +187,10 @@ public static function select(&$query) {
//participant note
if (!empty($query->_returnProperties['participant_note'])) {
- $query->_select['participant_note'] = "civicrm_note.note as participant_note";
+ $query->_select['participant_note'] = "participant_note.note as participant_note";
$query->_element['participant_note'] = 1;
$query->_tables['participant_note'] = 1;
- $query->_whereTables['civicrm_note'] = 1;
+ $query->_whereTables['participant_note'] = 1;
}
if (!empty($query->_returnProperties['participant_is_pay_later'])) {
@@ -226,7 +226,6 @@ public static function select(&$query) {
}
}
-
/**
* @param $query
*/
@@ -239,7 +238,7 @@ public static function where(&$query) {
if (substr($query->_params[$id][0], 0, 6) == 'event_' ||
substr($query->_params[$id][0], 0, 12) == 'participant_'
) {
- if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
+ if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$grouping = $query->_params[$id][3];
@@ -253,6 +252,7 @@ public static function where(&$query) {
* @param $query
*/
public static function whereClauseSingle(&$values, &$query) {
+ $checkPermission = empty($query->_skipPermission);
list($name, $op, $value, $grouping, $wildcard) = $values;
$fields = array_merge(CRM_Event_BAO_Event::fields(), CRM_Event_BAO_Participant::exportableFields());
@@ -304,7 +304,7 @@ public static function whereClauseSingle(&$values, &$query) {
$thisEventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($value, 'civicrm_event');
if ($thisEventHasParent) {
$getAllConnections = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($thisEventHasParent, 'civicrm_event');
- $allEventIds = array();
+ $allEventIds = [];
foreach ($getAllConnections as $key => $val) {
$allEventIds[] = $val['id'];
}
@@ -333,20 +333,19 @@ public static function whereClauseSingle(&$values, &$query) {
);
$isTest = $value ? 'a Test' : 'not a Test';
- $query->_qill[$grouping][] = ts("Participant is %1", array(1 => $isTest));
+ $query->_qill[$grouping][] = ts("Participant is %1", [1 => $isTest]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
}
return;
case 'participant_fee_id':
- foreach ($value as $k => &$val) {
- $val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
- $val = CRM_Core_DAO::escapeString(trim($val));
+ $labels = [];
+ foreach ($value as $val) {
+ $labels[] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
}
- $feeLabel = implode('|', $value);
- $query->_where[$grouping][] = "civicrm_participant.fee_level REGEXP '{$feeLabel}'";
- $query->_qill[$grouping][] = ts("Fee level") . " IN " . implode(', ', $value);
- $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
+ $query->_where[$grouping][] = "civicrm_line_item.price_field_value_id IN (" . implode(', ', $value) . ")";
+ $query->_qill[$grouping][] = ts("Fee level") . " IN " . implode(', ', $labels);
+ $query->_tables['civicrm_participant'] = $query->_tables['civicrm_line_item'] = $query->_whereTables['civicrm_line_item'] = 1;
return;
case 'participant_fee_amount_high':
@@ -371,7 +370,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'participant_registered_by_id':
$qillName = $name;
- if (in_array($name, array(
+ if (in_array($name, [
'participant_status_id',
'participant_source',
'participant_id',
@@ -381,8 +380,7 @@ public static function whereClauseSingle(&$values, &$query) {
'participant_is_pay_later',
'participant_campaign_id',
'participant_registered_by_id',
- ))
- ) {
+ ])) {
$name = str_replace('participant_', '', $name);
if ($name == 'is_pay_later') {
$qillName = $name;
@@ -401,7 +399,7 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
@@ -426,7 +424,7 @@ public static function whereClauseSingle(&$values, &$query) {
}
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
@@ -445,13 +443,11 @@ public static function whereClauseSingle(&$values, &$query) {
case 'event_type_id':
case 'event_title':
$qillName = $name;
- if (in_array($name, array(
- 'event_id',
- 'event_title',
- 'event_is_public',
- )
- )
- ) {
+ if (in_array($name, [
+ 'event_id',
+ 'event_title',
+ 'event_is_public',
+ ])) {
$name = str_replace('event_', '', $name);
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
@@ -461,9 +457,16 @@ public static function whereClauseSingle(&$values, &$query) {
if (!array_key_exists($qillName, $fields)) {
break;
}
- list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op, ['check_permission' => $checkPermission]);
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
return;
+
+ case 'participant_note':
+ $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
+ $query->_tables['participant_note'] = $query->_whereTables['participant_note'] = 1;
+ $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('participant_note.note', $op, $value, 'String');
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
+ break;
}
}
@@ -492,8 +495,8 @@ public static function from($name, $mode, $side) {
break;
case 'participant_note':
- $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_participant' AND
- civicrm_participant.id = civicrm_note.entity_id )";
+ $from .= " $side JOIN civicrm_note participant_note ON ( participant_note.entity_table = 'civicrm_participant' AND
+ civicrm_participant.id = participant_note.entity_id )";
break;
case 'participant_status':
@@ -510,6 +513,10 @@ public static function from($name, $mode, $side) {
$from = " $side JOIN civicrm_discount discount ON ( civicrm_participant.discount_id = discount.id )";
$from .= " $side JOIN civicrm_option_group discount_name ON ( discount_name.id = discount.price_set_id ) ";
break;
+
+ case 'civicrm_line_item':
+ $from .= " $side JOIN civicrm_line_item ON civicrm_line_item.entity_id = civicrm_participant.id AND civicrm_line_item.entity_table = 'civicrm_participant'";
+ break;
}
return $from;
}
@@ -526,7 +533,7 @@ public static function defaultReturnProperties(
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_EVENT) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -552,7 +559,7 @@ public static function defaultReturnProperties(
'participant_fee_currency' => 1,
'participant_registered_by_id' => 1,
'participant_campaign_id' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom participant properties
@@ -569,9 +576,30 @@ public static function defaultReturnProperties(
}
/**
- * @param CRM_Core_Form $form
+ * Get the metadata for fields to be included on the grant search form.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getSearchFieldMetadata() {
+ $fields = [
+ 'participant_status_id',
+ 'participant_register_date',
+ ];
+ $metadata = civicrm_api3('Participant', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
+ /**
+ * Build the event search form.
+ *
+ * @param \CRM_Event_Form_Search $form
+ *
+ * @throws \CiviCRM_API3_Exception
+ * @throws \CRM_Core_Exception
*/
public static function buildSearchForm(&$form) {
+ $form->addSearchFieldMetadata(['Participant' => self::getSearchFieldMetadata()]);
+ $form->addFormFieldsFromMetadata();
$dataURLEventFee = CRM_Utils_System::url('civicrm/ajax/eventFee',
"reset=1",
FALSE, NULL, FALSE
@@ -579,73 +607,58 @@ public static function buildSearchForm(&$form) {
$form->assign('dataURLEventFee', $dataURLEventFee);
- $form->addEntityRef('event_id', ts('Event Name'), array(
- 'entity' => 'event',
- 'placeholder' => ts('- any -'),
- 'multiple' => 1,
- 'select' => array('minimumInputLength' => 0),
- )
- );
- $form->addEntityRef('event_type_id', ts('Event Type'), array(
- 'entity' => 'option_value',
- 'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- 'api' => array(
- 'params' => array('option_group_id' => 'event_type'),
- ),
- )
- );
+ $form->addEntityRef('event_id', ts('Event Name'), [
+ 'entity' => 'Event',
+ 'placeholder' => ts('- any -'),
+ 'multiple' => 1,
+ 'select' => ['minimumInputLength' => 0],
+ ]);
+ $form->addEntityRef('event_type_id', ts('Event Type'), [
+ 'entity' => 'OptionValue',
+ 'placeholder' => ts('- any -'),
+ 'select' => ['minimumInputLength' => 0],
+ 'api' => [
+ 'params' => ['option_group_id' => 'event_type'],
+ ],
+ ]);
$obj = new CRM_Report_Form_Event_ParticipantListing();
$form->add('select', 'participant_fee_id',
ts('Fee Level'),
$obj->getPriceLevels(),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
);
CRM_Core_Form_Date::buildDateRange($form, 'event', 1, '_start_date_low', '_end_date_high', ts('From'), FALSE);
- CRM_Core_Form_Date::buildDateRange($form, 'participant', 1, '_register_date_low', '_register_date_high', ts('From'), FALSE);
-
$form->addElement('hidden', 'event_date_range_error');
- $form->addElement('hidden', 'participant_date_range_error');
- $form->addFormRule(array('CRM_Event_BAO_Query', 'formRule'), $form);
+ $form->addFormRule(['CRM_Event_BAO_Query', 'formRule'], $form);
- $form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', array(1 => '%1')));
-
- $form->addSelect('participant_status_id',
- array(
- 'entity' => 'participant',
- 'label' => ts('Participant Status'),
- 'multiple' => 'multiple',
- 'option_url' => NULL,
- 'placeholder' => ts('- any -'),
- )
- );
+ $form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', [1 => '%1']));
$form->addSelect('participant_role_id',
- array(
+ [
'entity' => 'participant',
'label' => ts('Participant Role'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
- )
+ ]
);
$form->addYesNo('participant_test', ts('Participant is a Test?'), TRUE);
$form->addYesNo('participant_is_pay_later', ts('Participant is Pay Later?'), TRUE);
- $form->addElement('text', 'participant_fee_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
- $form->addElement('text', 'participant_fee_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
+ $form->addElement('text', 'participant_fee_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
+ $form->addElement('text', 'participant_fee_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('participant_fee_amount_low', ts('Please enter a valid money value.'), 'money');
$form->addRule('participant_fee_amount_high', ts('Please enter a valid money value.'), 'money');
- self::addCustomFormFields($form, array('Participant', 'Event'));
+ self::addCustomFormFields($form, ['Participant', 'Event']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'participant_campaign_id');
$form->assign('validCiviEvent', TRUE);
- $form->setDefaults(array('participant_test' => 0));
+ $form->setDefaults(['participant_test' => 0]);
}
/**
@@ -654,7 +667,7 @@ public static function buildSearchForm(&$form) {
public static function tableNames(&$tables) {
//add participant table
if (!empty($tables['civicrm_event'])) {
- $tables = array_merge(array('civicrm_participant' => 1), $tables);
+ $tables = array_merge(['civicrm_participant' => 1], $tables);
}
}
@@ -670,9 +683,9 @@ public static function tableNames(&$tables) {
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
- if ((empty($fields['event_start_date_low']) || empty($fields['event_end_date_high'])) && (empty($fields['participant_register_date_low']) || empty($fields['participant_register_date_high']))) {
+ if ((empty($fields['event_start_date_low']) || empty($fields['event_end_date_high']))) {
return TRUE;
}
$lowDate = strtotime($fields['event_start_date_low']);
@@ -682,12 +695,6 @@ public static function formRule($fields, $files, $form) {
$errors['event_date_range_error'] = ts('Please check that your Event Date Range is in correct chronological order.');
}
- $lowDate1 = strtotime($fields['participant_register_date_low']);
- $highDate1 = strtotime($fields['participant_register_date_high']);
-
- if ($lowDate1 > $highDate1) {
- $errors['participant_date_range_error'] = ts('Please check that your Registration Date Range is in correct chronological order.');
- }
return empty($errors) ? TRUE : $errors;
}
diff --git a/CRM/Event/Badge.php b/CRM/Event/Badge.php
index 5791e72e392e..953c61b5fdb8 100644
--- a/CRM/Event/Badge.php
+++ b/CRM/Event/Badge.php
@@ -1,7 +1,7 @@
style = array(
+ $this->style = [
'width' => 0.1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,2',
- 'color' => array(0, 0, 200),
- );
+ 'color' => [0, 0, 200],
+ ];
$this->format = '5160';
$this->imgExtension = 'png';
$this->imgRes = 300;
@@ -88,7 +89,7 @@ public function run(&$participants) {
$this->event = self::retrieveEvent($eventID);
//call function to create labels
self::createLabels($participants);
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
@@ -123,9 +124,9 @@ public function getImageFileName($eventID, $img = FALSE) {
// CRM-13235 - leverage the Smarty path to get all templates directories
$template = CRM_Core_Smarty::singleton();
if (isset($template->template_dir) && $template->template_dir) {
- $dirs = is_array($template->template_dir) ? $template->template_dir : array($template->template_dir);
+ $dirs = is_array($template->template_dir) ? $template->template_dir : [$template->template_dir];
foreach ($dirs as $dir) {
- foreach (array("$dir/$path/$eventID/$img", "$dir/$path/$img") as $imgFile) {
+ foreach (["$dir/$path/$eventID/$img", "$dir/$path/$img"] as $imgFile) {
if (file_exists($imgFile)) {
return $imgFile;
}
@@ -147,15 +148,15 @@ public function printBackground($img = FALSE) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
if ($this->debug) {
- $this->pdf->Rect($x, $y, $this->pdf->width, $this->pdf->height, 'D', array(
- 'all' => array(
- 'width' => 1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,10',
- 'color' => array(255, 0, 0),
- ),
- ));
+ $this->pdf->Rect($x, $y, $this->pdf->width, $this->pdf->height, 'D', [
+ 'all' => [
+ 'width' => 1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,10',
+ 'color' => [255, 0, 0],
+ ],
+ ]);
}
$img = $this->getImageFileName($this->event->id, $img);
if ($img) {
diff --git a/CRM/Event/Badge/Logo.php b/CRM/Event/Badge/Logo.php
index b6ca8b1bf216..4ac357ec2521 100644
--- a/CRM/Event/Badge/Logo.php
+++ b/CRM/Event/Badge/Logo.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Badge_Logo
*/
class CRM_Event_Badge_Logo extends CRM_Event_Badge {
+
/**
*/
public function __construct() {
@@ -13,7 +14,7 @@ public function __construct() {
$ph = 297;
$h = 50;
$w = 75;
- $this->format = array(
+ $this->format = [
'name' => 'Sigel 3C',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -26,7 +27,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 12,
- );
+ ];
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
@@ -39,13 +40,13 @@ public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
- $this->pdf->SetLineStyle(array(
- 'width' => 0.1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,2',
- 'color' => array(0, 0, 200),
- ));
+ $this->pdf->SetLineStyle([
+ 'width' => 0.1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,2',
+ 'color' => [0, 0, 200],
+ ]);
$this->pdf->SetFontSize(8);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
diff --git a/CRM/Event/Badge/Logo5395.php b/CRM/Event/Badge/Logo5395.php
index 411dfc74c59e..2343909174f5 100644
--- a/CRM/Event/Badge/Logo5395.php
+++ b/CRM/Event/Badge/Logo5395.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Badge_Logo5395
*/
class CRM_Event_Badge_Logo5395 extends CRM_Event_Badge {
+
/**
*/
public function __construct() {
@@ -13,7 +14,7 @@ public function __construct() {
$ph = 297;
$h = 59.2;
$w = 85.7;
- $this->format = array(
+ $this->format = [
'name' => 'Avery 5395',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -26,7 +27,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 12,
- );
+ ];
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
@@ -39,13 +40,13 @@ public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
- $this->pdf->SetLineStyle(array(
- 'width' => 0.1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,2',
- 'color' => array(0, 0, 200),
- ));
+ $this->pdf->SetLineStyle([
+ 'width' => 0.1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,2',
+ 'color' => [0, 0, 200],
+ ]);
$this->pdf->SetFontSize(9);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
diff --git a/CRM/Event/Badge/NameTent.php b/CRM/Event/Badge/NameTent.php
index ee38f5848a30..f2d4990bc3ed 100644
--- a/CRM/Event/Badge/NameTent.php
+++ b/CRM/Event/Badge/NameTent.php
@@ -1,9 +1,9 @@
tMargin = 0;
$w = $pw - 2 * $this->lMargin;
$h = $ph - 2 * $this->tMargin;
- $this->format = array(
+ $this->format = [
'name' => 'A4 horiz',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -62,7 +63,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 36,
- );
+ ];
// $this->setDebug ();
}
diff --git a/CRM/Event/Badge/Simple.php b/CRM/Event/Badge/Simple.php
index 8a5825b1a246..a9fcb36ff573 100644
--- a/CRM/Event/Badge/Simple.php
+++ b/CRM/Event/Badge/Simple.php
@@ -1,9 +1,9 @@
$event_in_cart */
- public $events_in_carts = array();
+ /**
+ * event_in_cart_id => $event_in_cart
+ * @var array
+ */
+ public $events_in_carts = [];
/**
* @param array $params
@@ -32,10 +35,10 @@ public function add_event($event_id) {
return $event_in_cart;
}
- $params = array(
+ $params = [
'event_id' => $event_id,
'event_cart_id' => $this->id,
- );
+ ];
$event_in_cart = CRM_Event_Cart_BAO_EventInCart::create($params);
$event_in_cart->load_associations($this);
$this->events_in_carts[$event_in_cart->event_id] = $event_in_cart;
@@ -81,7 +84,7 @@ public static function create($params) {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_by_id($id) {
- return self::find_by_params(array('id' => $id));
+ return self::find_by_params(['id' => $id]);
}
/**
@@ -127,12 +130,12 @@ public static function find_or_create_for_current_session() {
}
if ($cart === FALSE) {
if (is_null($userID)) {
- $cart = self::create(array());
+ $cart = self::create([]);
}
else {
$cart = self::find_uncompleted_by_user_id($userID);
if ($cart === FALSE) {
- $cart = self::create(array('user_id' => $userID));
+ $cart = self::create(['user_id' => $userID]);
}
}
$session->set('event_cart_id', $cart->id);
@@ -146,7 +149,7 @@ public static function find_or_create_for_current_session() {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_id($id) {
- return self::find_by_params(array('id' => $id, 'completed' => 0));
+ return self::find_by_params(['id' => $id, 'completed' => 0]);
}
/**
@@ -155,7 +158,7 @@ public static function find_uncompleted_by_id($id) {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_user_id($user_id) {
- return self::find_by_params(array('user_id' => $user_id, 'completed' => 0));
+ return self::find_by_params(['user_id' => $user_id, 'completed' => 0]);
}
/**
@@ -163,7 +166,7 @@ public static function find_uncompleted_by_user_id($user_id) {
*/
public function get_main_events_in_carts() {
//return CRM_Event_Cart_BAO_EventInCart::find_all_by_params( array('main_conference_event_id'
- $all = array();
+ $all = [];
foreach ($this->events_in_carts as $event_in_cart) {
if (!$event_in_cart->is_child_event()) {
$all[] = $event_in_cart;
@@ -178,7 +181,7 @@ public function get_main_events_in_carts() {
* @return array
*/
public function get_events_in_carts_by_main_event_id($main_conference_event_id) {
- $all = array();
+ $all = [];
if (!$main_conference_event_id) {
return $all;
}
@@ -215,7 +218,7 @@ public static function compare_event_dates($event_in_cart_1, $event_in_cart_2) {
* @return array
*/
public function get_subparticipants($main_participant) {
- $subparticipants = array();
+ $subparticipants = [];
foreach ($this->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_child_event($main_participant->event_id)) {
foreach ($event_in_cart->participants as $participant) {
@@ -256,7 +259,7 @@ public function &get_event_in_cart_by_id($event_in_cart_id) {
* @return array
*/
public function get_main_event_participants() {
- $participants = array();
+ $participants = [];
foreach ($this->get_main_events_in_carts() as $event_in_cart) {
$participants = array_merge($participants, $event_in_cart->participants);
}
@@ -321,21 +324,20 @@ public function get_participant_index_from_id($participant_id) {
public static function retrieve(&$params, &$values) {
$cart = self::find_by_params($params);
if ($cart === FALSE) {
- CRM_Core_Error::fatal(ts('Could not find cart matching %1', array(1 => var_export($params, TRUE))));
+ CRM_Core_Error::fatal(ts('Could not find cart matching %1', [1 => var_export($params, TRUE)]));
}
CRM_Core_DAO::storeValues($cart, $values);
return $values;
}
-
/**
* @param int $from_cart_id
*/
public function adopt_participants($from_cart_id) {
- $params = array(
- 1 => array($this->id, 'Integer'),
- 2 => array($from_cart_id, 'Integer'),
- );
+ $params = [
+ 1 => [$this->id, 'Integer'],
+ 2 => [$from_cart_id, 'Integer'],
+ ];
$sql = "UPDATE civicrm_participant SET cart_id='%1' WHERE cart_id='%2'";
CRM_Core_DAO::executeQuery($sql, $params);
diff --git a/CRM/Event/Cart/BAO/Conference.php b/CRM/Event/Cart/BAO/Conference.php
index d332cfe70633..fd2c3f49dfba 100644
--- a/CRM/Event/Cart/BAO/Conference.php
+++ b/CRM/Event/Cart/BAO/Conference.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_BAO_Conference
*/
class CRM_Event_Cart_BAO_Conference {
+
/**
* XXX assumes we don't allow a contact to register for the same conference more than once
* XXX flattens the object tree for convenient templating
@@ -28,9 +29,9 @@ public static function get_participant_sessions($main_event_participant_id) {
slot.weight,
sub_event.start_date
EOS;
- $sql_args = array(1 => array($main_event_participant_id, 'Integer'));
+ $sql_args = [1 => [$main_event_participant_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $sql_args);
- $smarty_sessions = array();
+ $smarty_sessions = [];
while ($dao->fetch()) {
$smarty_sessions[] = get_object_vars($dao);
}
diff --git a/CRM/Event/Cart/BAO/EventInCart.php b/CRM/Event/Cart/BAO/EventInCart.php
index 457b12dcac28..7dd79ec72523 100644
--- a/CRM/Event/Cart/BAO/EventInCart.php
+++ b/CRM/Event/Cart/BAO/EventInCart.php
@@ -8,7 +8,7 @@ class CRM_Event_Cart_BAO_EventInCart extends CRM_Event_Cart_DAO_EventInCart impl
public $event;
public $event_cart;
public $location = NULL;
- public $participants = array();
+ public $participants = [];
/**
* Class constructor.
@@ -55,10 +55,10 @@ public static function create(&$params) {
*/
public function delete($useWhere = FALSE) {
$this->load_associations();
- $contacts_to_delete = array();
+ $contacts_to_delete = [];
foreach ($this->participants as $participant) {
- $defaults = array();
- $params = array('id' => $participant->contact_id);
+ $defaults = [];
+ $params = ['id' => $participant->contact_id];
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
if ($temporary_contact->is_deleted) {
@@ -78,7 +78,7 @@ public function delete($useWhere = FALSE) {
* @return array
*/
public static function find_all_by_event_cart_id($event_cart_id) {
- return self::find_all_by_params(array('event_cart_id' => $event_cart_id));
+ return self::find_all_by_params(['event_cart_id' => $event_cart_id]);
}
/**
@@ -89,7 +89,7 @@ public static function find_all_by_event_cart_id($event_cart_id) {
public static function find_all_by_params($params) {
$event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
$event_in_cart->copyValues($params);
- $result = array();
+ $result = [];
if ($event_in_cart->find()) {
while ($event_in_cart->fetch()) {
$result[$event_in_cart->event_id] = clone($event_in_cart);
@@ -104,7 +104,7 @@ public static function find_all_by_params($params) {
* @return bool|CRM_Event_Cart_BAO_EventInCart
*/
public static function find_by_id($id) {
- return self::find_by_params(array('id' => $id));
+ return self::find_by_params(['id' => $id]);
}
/**
@@ -127,7 +127,7 @@ public static function find_by_params($params) {
* @param int $contact_id
*/
public function remove_participant_by_contact_id($contact_id) {
- $to_remove = array();
+ $to_remove = [];
foreach ($this->participants as $participant) {
if ($participant->contact_id == $contact_id) {
$to_remove[$participant->id] = 1;
@@ -171,8 +171,8 @@ public function load_associations($event_cart = NULL) {
return;
}
$this->assocations_loaded = TRUE;
- $params = array('id' => $this->event_id);
- $defaults = array();
+ $params = ['id' => $this->event_id];
+ $defaults = [];
$this->event = CRM_Event_BAO_Event::retrieve($params, $defaults);
if ($event_cart != NULL) {
@@ -192,7 +192,7 @@ public function load_associations($event_cart = NULL) {
public function load_location() {
if ($this->location == NULL) {
- $location_params = array('entity_id' => $this->event_id, 'entity_table' => 'civicrm_event');
+ $location_params = ['entity_id' => $this->event_id, 'entity_table' => 'civicrm_event'];
$this->location = CRM_Core_BAO_Location::getValues($location_params, TRUE);
}
}
@@ -201,7 +201,7 @@ public function load_location() {
* @return array
*/
public function not_waiting_participants() {
- $result = array();
+ $result = [];
foreach ($this->participants as $participant) {
if (!$participant->must_wait) {
$result[] = $participant;
@@ -224,14 +224,13 @@ public function num_waiting_participants() {
return count($this->waiting_participants());
}
-
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset) {
- return array_key_exists(array_merge($this->fields(), array('main_conference_event_id')), $offset);
+ return array_key_exists(array_merge($this->fields(), ['main_conference_event_id']), $offset);
}
/**
@@ -270,7 +269,7 @@ public function offsetUnset($offset) {
* @return array
*/
public function waiting_participants() {
- $result = array();
+ $result = [];
foreach ($this->participants as $participant) {
if ($participant->must_wait) {
$result[] = $participant;
@@ -290,18 +289,18 @@ public static function get_registration_link($event_id) {
$event_in_cart = $cart->get_event_in_cart_by_event_id($event_id);
if ($event_in_cart) {
- return array(
- 'label' => "Remove from Cart",
+ return [
+ 'label' => ts("Remove from Cart"),
'path' => 'civicrm/event/remove_from_cart',
'query' => "reset=1&id={$event_id}",
- );
+ ];
}
else {
- return array(
- 'label' => "Add to Cart",
+ return [
+ 'label' => ts("Add to Cart"),
'path' => 'civicrm/event/add_to_cart',
'query' => "reset=1&id={$event_id}",
- );
+ ];
}
}
diff --git a/CRM/Event/Cart/BAO/MerParticipant.php b/CRM/Event/Cart/BAO/MerParticipant.php
index e0385666d9b6..9717dea04b53 100644
--- a/CRM/Event/Cart/BAO/MerParticipant.php
+++ b/CRM/Event/Cart/BAO/MerParticipant.php
@@ -1,9 +1,9 @@
CRM_Utils_Array::value('id', $params),
'role_id' => self::get_attendee_role_id(),
'status_id' => self::get_pending_in_cart_status_id(),
@@ -63,7 +63,7 @@ public static function create(&$params) {
//'registered_by_id' =>
//'discount_amount' =>
//'fee_level' => $params['fee_level'],
- );
+ ];
$participant = CRM_Event_BAO_Participant::create($participantParams);
if (is_a($participant, 'CRM_Core_Error')) {
@@ -102,7 +102,7 @@ public static function find_all_by_cart_id($event_cart_id) {
if ($event_cart_id == NULL) {
return NULL;
}
- return self::find_all_by_params(array('cart_id' => $event_cart_id));
+ return self::find_all_by_params(['cart_id' => $event_cart_id]);
}
/**
@@ -115,7 +115,7 @@ public static function find_all_by_event_and_cart_id($event_id, $event_cart_id)
if ($event_cart_id == NULL) {
return NULL;
}
- return self::find_all_by_params(array('event_id' => $event_id, 'cart_id' => $event_cart_id));
+ return self::find_all_by_params(['event_id' => $event_id, 'cart_id' => $event_cart_id]);
}
/**
@@ -126,7 +126,7 @@ public static function find_all_by_event_and_cart_id($event_id, $event_cart_id)
public static function find_all_by_params($params) {
$participant = new CRM_Event_BAO_Participant();
$participant->copyValues($params);
- $result = array();
+ $result = [];
if ($participant->find()) {
while ($participant->fetch()) {
$result[] = new CRM_Event_Cart_BAO_MerParticipant(clone($participant));
@@ -141,7 +141,7 @@ public static function find_all_by_params($params) {
* @return mixed
*/
public static function get_by_id($id) {
- $results = self::find_all_by_params(array('id' => $id));
+ $results = self::find_all_by_params(['id' => $id]);
return array_pop($results);
}
diff --git a/CRM/Event/Cart/Controller/Checkout.php b/CRM/Event/Cart/Controller/Checkout.php
index 84ed049823b6..a00044bdda63 100644
--- a/CRM/Event/Cart/Controller/Checkout.php
+++ b/CRM/Event/Cart/Controller/Checkout.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Controller_Checkout
*/
class CRM_Event_Cart_Controller_Checkout extends CRM_Core_Controller {
+
/**
* @param null $title
* @param bool|int $action
diff --git a/CRM/Event/Cart/DAO/Cart.php b/CRM/Event/Cart/DAO/Cart.php
index 568bb3f0e1c0..dbd0037e5ef7 100644
--- a/CRM/Event/Cart/DAO/Cart.php
+++ b/CRM/Event/Cart/DAO/Cart.php
@@ -1,165 +1,155 @@
__table = 'civicrm_event_carts';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'user_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'user_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'cart_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'cart_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Cart ID') ,
- 'description' => 'Cart Id',
- 'required' => true,
+ 'title' => ts('Cart ID'),
+ 'description' => ts('Cart Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event_carts.id',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
- ) ,
- 'user_id' => array(
+ ],
+ 'user_id' => [
'name' => 'user_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created By') ,
- 'description' => 'FK to civicrm_contact who created this cart',
+ 'title' => ts('Created By'),
+ 'description' => ts('FK to civicrm_contact who created this cart'),
+ 'where' => 'civicrm_event_carts.user_id',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'completed' => array(
+ ],
+ 'completed' => [
'name' => 'completed',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Complete?') ,
+ 'title' => ts('Complete?'),
+ 'where' => 'civicrm_event_carts.completed',
+ 'default' => '0',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -167,10 +157,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event_carts', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -178,15 +169,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event_carts', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Cart/DAO/EventInCart.php b/CRM/Event/Cart/DAO/EventInCart.php
index 3178c52bdee4..88463d5f162b 100644
--- a/CRM/Event/Cart/DAO/EventInCart.php
+++ b/CRM/Event/Cart/DAO/EventInCart.php
@@ -1,169 +1,159 @@
__table = 'civicrm_events_in_carts';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_cart_id', 'civicrm_event_carts', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_id', 'civicrm_event', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_cart_id', 'civicrm_event_carts', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'event_in_cart_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'event_in_cart_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event In Cart') ,
- 'description' => 'Event In Cart Id',
- 'required' => true,
+ 'title' => ts('Event In Cart'),
+ 'description' => ts('Event In Cart Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_events_in_carts.id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
- ) ,
- 'event_id' => array(
+ ],
+ 'event_id' => [
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event') ,
- 'description' => 'FK to Event ID',
+ 'title' => ts('Event'),
+ 'description' => ts('FK to Event ID'),
+ 'where' => 'civicrm_events_in_carts.event_id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
- ) ,
- 'event_cart_id' => array(
+ ],
+ 'event_cart_id' => [
'name' => 'event_cart_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event In Cart') ,
- 'description' => 'FK to Event Cart ID',
+ 'title' => ts('Event In Cart'),
+ 'description' => ts('FK to Event Cart ID'),
+ 'where' => 'civicrm_events_in_carts.event_cart_id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -171,10 +161,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'events_in_carts', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'events_in_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -182,15 +173,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'events_in_carts', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'events_in_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Cart/Form/Cart.php b/CRM/Event/Cart/Form/Cart.php
index 3f4f23a31930..6e16ac7a31a6 100644
--- a/CRM/Event/Cart/Form/Cart.php
+++ b/CRM/Event/Cart/Form/Cart.php
@@ -21,13 +21,13 @@ public function preProcess() {
$this->assignBillingType();
- $event_titles = array();
+ $event_titles = [];
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$event_titles[] = $event_in_cart->event->title;
}
- $this->description = ts("Online Registration for %1", array(1 => implode(", ", $event_titles)));
+ $this->description = ts("Online Registration for %1", [1 => implode(", ", $event_titles)]);
if (!isset($this->discounts)) {
- $this->discounts = array();
+ $this->discounts = [];
}
}
@@ -47,11 +47,11 @@ public function stub_out_and_inherit() {
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
if (empty($event_in_cart->participants)) {
- $participant_params = array(
+ $participant_params = [
'cart_id' => $this->cart->id,
'event_id' => $event_in_cart->event_id,
'contact_id' => self::find_or_create_contact($this->getContactID()),
- );
+ ];
$participant = CRM_Event_Cart_BAO_MerParticipant::create($participant_params);
$participant->save();
$event_in_cart->add_participant($participant);
@@ -128,7 +128,7 @@ public function getContactID() {
* @return mixed|null
*/
public static function find_contact($fields) {
- return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE);
+ return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
}
/**
@@ -137,22 +137,22 @@ public static function find_contact($fields) {
*
* @return int|mixed|null
*/
- public static function find_or_create_contact($registeringContactID = NULL, $fields = array()) {
+ public static function find_or_create_contact($registeringContactID = NULL, $fields = []) {
$contact_id = self::find_contact($fields);
if ($contact_id) {
return $contact_id;
}
- $contact_params = array(
+ $contact_params = [
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, TRUE),
- );
- $no_fields = array();
+ ];
+ $no_fields = [];
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($contact_params, $no_fields, NULL);
if (!$contact_id) {
- CRM_Core_Error::displaySessionError("Could not create or match a contact with that email address. Please contact the webmaster.");
+ CRM_Core_Session::setStatus(ts("Could not create or match a contact with that email address. Please contact the webmaster."), '', 'error');
}
return $contact_id;
}
diff --git a/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php b/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
index f1299e3553cc..57e28b704550 100644
--- a/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
+++ b/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
@@ -5,13 +5,13 @@
*/
class CRM_Event_Cart_Form_Checkout_ConferenceEvents extends CRM_Event_Cart_Form_Cart {
public $conference_event = NULL;
- public $events_by_slot = array();
+ public $events_by_slot = [];
public $main_participant = NULL;
public $contact_id = NULL;
public function preProcess() {
parent::preProcess();
- $matches = array();
+ $matches = [];
preg_match("/.*_(\d+)_(\d+)/", $this->getAttribute('name'), $matches);
$event_id = $matches[1];
$participant_id = $matches[2];
@@ -43,7 +43,7 @@ public function preProcess() {
$events->query($query);
while ($events->fetch()) {
if (!array_key_exists($events->slot_label, $this->events_by_slot)) {
- $this->events_by_slot[$events->slot_label] = array();
+ $this->events_by_slot[$events->slot_label] = [];
}
$this->events_by_slot[$events->slot_label][] = clone($events);
}
@@ -55,13 +55,13 @@ public function buildQuickForm() {
//jquery_ui_add('ui.dialog');
$slot_index = -1;
- $slot_fields = array();
- $session_options = array();
- $defaults = array();
+ $slot_fields = [];
+ $session_options = [];
+ $defaults = [];
$previous_event_choices = $this->cart->get_subparticipants($this->main_participant);
foreach ($this->events_by_slot as $slot_name => $events) {
$slot_index++;
- $slot_buttons = array();
+ $slot_buttons = [];
$group_name = "slot_$slot_index";
foreach ($events as $event) {
$seats_available = $this->checkEventCapacity($event->id);
@@ -70,12 +70,12 @@ public function buildQuickForm() {
$slot_buttons[] = $radio;
$event_description = ($event_is_full ? $event->event_full_text . "
']
+ );
// financial type
if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() ||
@@ -272,11 +268,11 @@ public function buildQuickForm() {
}
else {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
- $this->addSelect('financial_type_id', array('context' => 'search', 'options' => $financialTypes));
+ $this->addSelect('financial_type_id', ['context' => 'search', 'options' => $financialTypes]);
}
// add pay later options
$this->addElement('checkbox', 'is_pay_later', ts('Enable Pay Later option?'), NULL,
- array('onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);")
+ ['onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);"]
);
$this->addElement('textarea', 'pay_later_text', ts('Pay Later Label'),
CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_text'),
@@ -294,22 +290,22 @@ public function buildQuickForm() {
else {
$this->assign('price', TRUE);
}
- $this->add('select', 'price_set_id', ts('Price Set'),
- array(
- '' => ts('- none -'),
- ) + $price,
- NULL, array('onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);")
- );
- $default = array($this->createElement('radio', NULL, NULL, NULL, 0));
- $this->add('hidden', 'price_field_id', '', array('id' => 'price_field_id'));
+ $this->addField('price_set_id', [
+ 'entity' => 'PriceSet',
+ 'options' => $price,
+ 'onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);",
+ ]);
+
+ $default = [$this->createElement('radio', NULL, NULL, NULL, 0)];
+ $this->add('hidden', 'price_field_id', '', ['id' => 'price_field_id']);
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
- $this->add('hidden', "price_field_value[$i]", '', array('id' => "price_field_value[$i]"));
+ $this->add('hidden', "price_field_value[$i]", '', ['id' => "price_field_value[$i]"]);
// value
$this->add('text', "value[$i]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'));
- $this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
// default
$default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
@@ -318,14 +314,14 @@ public function buildQuickForm() {
$this->addGroup($default, 'default');
$this->addElement('checkbox', 'is_discount', ts('Discounts by Signup Date?'), NULL,
- array('onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);")
+ ['onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);"]
);
$discountSection = $this->get('discountSection');
$this->assign('discountSection', $discountSection);
// form fields of Discount sets
- $defaultOption = array();
+ $defaultOption = [];
$_showHide = new CRM_Core_ShowHideBlocks('', '');
for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
@@ -346,11 +342,10 @@ public function buildQuickForm() {
isset($this->_submitValues['discount_end_date'][$i]) &&
$i < self::NUM_DISCOUNT - 1
) {
- $end_date = CRM_Utils_Date::processDate($this->_submitValues['discount_end_date'][$i]);
if (!empty($this->_submitValues['discount_end_date'][$i + 1])
&& empty($this->_submitValues['discount_start_date'][$i + 1])
) {
- list($this->_submitValues['discount_start_date'][$i + 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("+1 days $end_date")));
+ $this->_submitValues['discount_start_date'][$i + 1] = date('Y-m-d', strtotime("+1 days " . $this->_submitValues['discount_end_date'][$i]));
}
}
//Decrement by 1 of end date from next start date.
@@ -361,32 +356,25 @@ public function buildQuickForm() {
isset($this->_submitValues['discount_start_date']) &&
isset($this->_submitValues['discount_start_date'][$i])
) {
- $start_date = CRM_Utils_Date::processDate($this->_submitValues['discount_start_date'][$i]);
if (!empty($this->_submitValues['discount_start_date'][$i])
&& empty($this->_submitValues['discount_end_date'][$i - 1])
) {
- list($this->_submitValues['discount_end_date'][$i - 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("-1 days $start_date")));
+ list($this->_submitValues['discount_end_date'][$i - 1]) = date('Y-m-d', strtotime("-1 days " . $this->_submitValues['discount_start_date'][$i]));
}
}
- //discount name
$this->add('text', 'discount_name[' . $i . ']', ts('Discount Name'),
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title')
);
-
- $this->add('hidden', "discount_price_set[$i]", '', array('id' => "discount_price_set[$i]"));
-
- //discount start date
- $this->addDate('discount_start_date[' . $i . ']', ts('Discount Start Date'), FALSE, array('formatType' => 'activityDate'));
-
- //discount end date
- $this->addDate('discount_end_date[' . $i . ']', ts('Discount End Date'), FALSE, array('formatType' => 'activityDate'));
+ $this->add('hidden', "discount_price_set[$i]", '', ['id' => "discount_price_set[$i]"]);
+ $this->add('datepicker', 'discount_start_date[' . $i . ']', ts('Discount Start Date'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'discount_end_date[' . $i . ']', ts('Discount End Date'), [], FALSE, ['time' => FALSE]);
}
$_showHide->addToTemplate();
$this->addElement('submit', $this->getButtonName('submit'), ts('Add Discount Set to Fee Table'),
- array('class' => 'crm-form-submit cancel')
+ ['class' => 'crm-form-submit cancel']
);
- if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
+ if (Civi::settings()->get('deferred_revenue_enabled')) {
$deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
$this->assign('deferredFinancialType', array_keys($deferredFinancialType));
}
@@ -398,7 +386,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Fee', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Fee', 'formRule']);
}
/**
@@ -411,7 +399,7 @@ public function addRules() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
if (!empty($values['is_discount'])) {
$occurDiscount = array_count_values($values['discount_name']);
$countemptyrows = 0;
@@ -448,7 +436,7 @@ public static function formRule($values) {
foreach ($occurDiscount as $key => $value) {
if ($value > 1 && $key <> '') {
if ($key == $values['discount_name'][$i]) {
- $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', array(1 => $key));
+ $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', [1 => $key]);
}
}
}
@@ -496,7 +484,7 @@ public static function formRule($values) {
if (empty($values['price_set_id'])) {
//check fee label and amount
$check = 0;
- $optionKeys = array();
+ $optionKeys = [];
foreach ($values['label'] as $key => $val) {
if (trim($val) && trim($values['value'][$key])) {
$optionKeys[$key] = $key;
@@ -526,19 +514,24 @@ public static function formRule($values) {
$errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.');
}
}
+ else {
+ if (empty($values['payment_processor'])) {
+ $errors['payment_processor'] = ts('You have indicated that this is a paid event, but no payment option has been selected. If this is not a paid event, please select the "No" option at the top of the page. If this is a paid event, please select at least one payment processor and/or enable the pay later option.');
+ }
+ }
}
return empty($errors) ? TRUE : $errors;
}
public function buildAmountLabel() {
- $default = array();
+ $default = [];
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "discounted_label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
// value
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
- $this->add('text', "discounted_value[$i][$j]", ts('Value'), array('size' => 10));
- $this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $this->add('text', "discounted_value[$i][$j]", ts('Value'), ['size' => 10]);
+ $this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
}
// default
@@ -553,7 +546,7 @@ public function buildAmountLabel() {
*/
public function postProcess() {
$eventTitle = '';
- $params = $this->exportValues();
+ $params = $this->cleanMoneyFields($this->exportValues());
$this->set('discountSection', 0);
@@ -564,7 +557,7 @@ public function postProcess() {
}
if (!empty($params['payment_processor'])) {
- $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
+ $params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
}
else {
$params['payment_processor'] = 'null';
@@ -603,17 +596,17 @@ public function postProcess() {
$labels = CRM_Utils_Array::value('label', $params);
$values = CRM_Utils_Array::value('value', $params);
$default = CRM_Utils_Array::value('default', $params);
- $options = array();
+ $options = [];
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
- $options[] = array(
+ $options[] = [
'label' => trim($labels[$i]),
- 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
+ 'value' => $values[$i],
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
- );
+ ];
}
}
if (!empty($options)) {
@@ -672,8 +665,8 @@ public function postProcess() {
}
}
- $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
- $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
+ $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : [];
+ $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : [];
if (CRM_Utils_Array::value('is_discount', $params) == 1) {
// if there are discounted set of label / values,
// create custom options for them
@@ -683,26 +676,26 @@ public function postProcess() {
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
- $discountOptions = array();
+ $discountOptions = [];
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) &&
!CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))
) {
- $discountOptions[] = array(
+ $discountOptions[] = [
'label' => trim($labels[$i]),
- 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])),
+ 'value' => $values[$i][$j],
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
- );
+ ];
}
}
if (!empty($discountOptions)) {
- $fieldParams = array();
+ $fieldParams = [];
$params['default_discount_fee_id'] = NULL;
$keyCheck = $j - 1;
- $setParams = array();
+ $setParams = [];
if (empty($discountPriceSets[$keyCheck])) {
if (!$eventTitle) {
$eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
@@ -726,10 +719,10 @@ public function postProcess() {
}
else {
$priceSetID = $discountPriceSets[$j - 1];
- $setParams = array(
+ $setParams = [
'title' => $params['discount_name'][$j],
'id' => $priceSetID,
- );
+ ];
if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
$setParams['financial_type_id'] = $params['financial_type_id'];
}
@@ -763,13 +756,13 @@ public function postProcess() {
}
}
- $discountParams = array(
+ $discountParams = [
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
'price_set_id' => $priceSetID,
- 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]),
- 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]),
- );
+ 'start_date' => $params['discount_start_date'][$j],
+ 'end_date' => $params['discount_end_date'][$j],
+ ];
CRM_Core_BAO_Discount::add($discountParams);
}
}
@@ -817,4 +810,36 @@ public function getTitle() {
return ts('Event Fees');
}
+ /**
+ * Clean money fields in submitted params to remove formatting.
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ protected function cleanMoneyFields($params) {
+ foreach ($params['value'] as $index => $value) {
+ if (CRM_Utils_System::isNull($value)) {
+ unset($params['value'][$index]);
+ }
+ else {
+ $params['value'][$index] = CRM_Utils_Rule::cleanMoney(trim($value));
+ }
+ }
+ foreach ($params['discounted_value'] as $index => $discountedValueSet) {
+ foreach ($discountedValueSet as $innerIndex => $value) {
+ if (CRM_Utils_System::isNull($value)) {
+ unset($params['discounted_value'][$index][$innerIndex]);
+ }
+ else {
+ $params['discounted_value'][$index][$innerIndex] = CRM_Utils_Rule::cleanMoney(trim($value));
+ }
+ }
+ if (empty($params['discounted_value'][$index])) {
+ unset($params['discounted_value'][$index]);
+ }
+ }
+ return $params;
+ }
+
}
diff --git a/CRM/Event/Form/ManageEvent/Location.php b/CRM/Event/Form/ManageEvent/Location.php
index 87ba5c250036..3573106ad521 100644
--- a/CRM/Event/Form/ManageEvent/Location.php
+++ b/CRM/Event/Form/ManageEvent/Location.php
@@ -1,9 +1,9 @@
setSelectedChild('location');
$this->_values = $this->get('values');
if ($this->_id && empty($this->_values)) {
//get location values.
- $params = array(
+ $params = [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$this->_values = CRM_Core_BAO_Location::getValues($params);
//get event values.
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $this->_values);
$this->set('values', $this->_values);
}
@@ -124,7 +126,7 @@ public function setDefaultValues() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Location', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Location', 'formRule']);
}
/**
@@ -147,17 +149,14 @@ public static function formRule($fields) {
* Function to build location block.
*/
public function buildQuickForm() {
- //load form for child blocks
- if ($this->_addBlockName) {
- $className = "CRM_Contact_Form_Edit_{$this->_addBlockName}";
- return $className::buildQuickForm($this);
- }
+ CRM_Contact_Form_Edit_Address::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Email::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Email::buildQuickForm($this, 2);
+ CRM_Contact_Form_Edit_Phone::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Phone::buildQuickForm($this, 2);
$this->applyFilter('__ALL__', 'trim');
- //build location blocks.
- CRM_Contact_Form_Location::buildQuickForm($this);
-
//fix for CRM-1971
$this->assign('action', $this->_action);
@@ -184,20 +183,19 @@ public function buildQuickForm() {
$locationEvents = array_unique($locationEvents);
}
- $events = array();
if (!empty($locationEvents)) {
$this->assign('locEvents', TRUE);
- $optionTypes = array(
+ $optionTypes = [
'1' => ts('Create new location'),
'2' => ts('Use existing location'),
- );
+ ];
$this->addRadio('location_option', ts("Choose Location"), $optionTypes);
if (!isset($locationEvents[$this->_oldLocBlockId]) || (!$this->_oldLocBlockId)) {
- $locationEvents = array('' => ts('- select -')) + $locationEvents;
+ $locationEvents = ['' => ts('- select -')] + $locationEvents;
}
- $this->add('select', 'loc_event_id', ts('Use Location'), $locationEvents, FALSE, array('class' => 'crm-select2'));
+ $this->add('select', 'loc_event_id', ts('Use Location'), $locationEvents, FALSE, ['class' => 'crm-select2']);
}
$this->addElement('advcheckbox', 'is_show_location', ts('Show Location?'));
parent::buildQuickForm();
@@ -231,7 +229,8 @@ public function postProcess() {
);
}
- // if 'create new loc' optioin is selected OR selected new loc is different
+ $this->_values['address'] = $this->_values['phone'] = $this->_values['email'] = [];
+ // if 'create new loc' option is selected OR selected new loc is different
// from old one, go ahead and delete the old loc provided thats not being
// used by any other event
if ($this->_oldLocBlockId && $deleteOldBlock) {
@@ -243,11 +242,11 @@ public function postProcess() {
$params['entity_id'] = $this->_id;
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
- foreach (array(
- 'address',
- 'phone',
- 'email',
- ) as $block) {
+ foreach ([
+ 'address',
+ 'phone',
+ 'email',
+ ] as $block) {
if (empty($params[$block]) || !is_array($params[$block])) {
continue;
}
@@ -256,12 +255,14 @@ public function postProcess() {
$values['is_primary'] = 1;
}
$values['location_type_id'] = ($defaultLocationType->id) ? $defaultLocationType->id : 1;
+ if (isset($this->_values[$block][$count])) {
+ $values['id'] = $this->_values[$block][$count]['id'];
+ }
}
}
// create/update event location
- $location = CRM_Core_BAO_Location::create($params, TRUE, 'event');
- $params['loc_block_id'] = $location['id'];
+ $params['loc_block_id'] = CRM_Core_BAO_Location::create($params, TRUE, 'event')['id'];
// finally update event params
$params['id'] = $this->_id;
diff --git a/CRM/Event/Form/ManageEvent/Registration.php b/CRM/Event/Form/ManageEvent/Registration.php
index 9634feef78f8..f7df5fc3ea5c 100644
--- a/CRM/Event/Form/ManageEvent/Registration.php
+++ b/CRM/Event/Form/ManageEvent/Registration.php
@@ -1,9 +1,9 @@
_profileBottomNumAdd = CRM_Utils_Array::value('addProfileNumAdd', $_GET, 0);
parent::preProcess();
+ $this->setSelectedChild('registration');
$this->assign('addProfileBottom', $this->_addProfileBottom);
$this->assign('profileBottomNum', $this->_profileBottomNum);
@@ -96,23 +97,23 @@ public function setDefaultValues() {
$this->setShowHide($defaults);
if (isset($eventId)) {
- $params = array('id' => $eventId);
+ $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
- $ufJoinParams = array(
+ $ufJoinParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent',
'entity_id' => $eventId,
- );
+ ];
list($defaults['custom_pre_id'],
$defaults['custom_post']
) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
// Get the id for the event registration profile
- $eventRegistrationIdParams = $eventRegistrationIdDefaults = array(
+ $eventRegistrationIdParams = $eventRegistrationIdDefaults = [
'name' => 'event_registration',
- );
+ ];
CRM_Core_BAO_UFGroup::retrieve($eventRegistrationIdParams, $eventRegistrationIdDefaults);
// Set event registration as the default profile if none selected
@@ -142,11 +143,11 @@ public function setDefaultValues() {
if (!empty($defaults['is_multiple_registrations'])) {
// CRM-4377: set additional participants’ profiles – set to ‘none’ if explicitly unset (non-active)
- $ufJoinAddParams = array(
+ $ufJoinAddParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent_Additional',
'entity_id' => $eventId,
- );
+ ];
list($defaults['additional_custom_pre_id'],
$defaults['additional_custom_post']
@@ -165,7 +166,7 @@ public function setDefaultValues() {
$defaults["additional_custom_post_id_multiple[$key]"] = $value;
}
}
- $this->assign('profilePostMultipleAdd', CRM_Utils_Array::value('additional_custom_post', $defaults));
+ $this->assign('profilePostMultipleAdd', CRM_Utils_Array::value('additional_custom_post', $defaults, []));
}
}
else {
@@ -178,16 +179,6 @@ public function setDefaultValues() {
$defaults['thankyou_title'] = CRM_Utils_Array::value('thankyou_title', $defaults, ts('Thank You for Registering'));
$defaults['approval_req_text'] = CRM_Utils_Array::value('approval_req_text', $defaults, ts('Participation in this event requires approval. Submit your registration request here. Once approved, you will receive an email with a link to a web page where you can complete the registration process.'));
- if (!empty($defaults['registration_start_date'])) {
- list($defaults['registration_start_date'], $defaults['registration_start_date_time'])
- = CRM_Utils_Date::setDateDefaults($defaults['registration_start_date'], 'activityDateTime');
- }
-
- if (!empty($defaults['registration_end_date'])) {
- list($defaults['registration_end_date'], $defaults['registration_end_date_time'])
- = CRM_Utils_Date::setDateDefaults($defaults['registration_end_date'], 'activityDateTime');
- }
-
return $defaults;
}
@@ -200,7 +191,7 @@ public function setDefaultValues() {
* @return void
*/
public function setShowHide($defaults) {
- $this->_showHide = new CRM_Core_ShowHideBlocks(array('registration' => 1),
+ $this->_showHide = new CRM_Core_ShowHideBlocks(['registration' => 1],
''
);
if (empty($defaults)) {
@@ -237,27 +228,27 @@ public function buildQuickForm() {
'is_online_registration',
ts('Allow Online Registration'),
NULL,
- array(
+ [
'onclick' => "return showHideByValue('is_online_registration'," .
"''," .
"'registration_blocks'," .
"'block'," .
"'radio'," .
"false );",
- )
+ ]
);
$this->add('text', 'registration_link_text', ts('Registration Link Text'));
if (!$this->_isTemplate) {
- $this->addDateTime('registration_start_date', ts('Registration Start Date'), FALSE, array('formatType' => 'activityDateTime'));
- $this->addDateTime('registration_end_date', ts('Registration End Date'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'registration_start_date', ts('Registration Start Date'), [], FALSE, ['time' => TRUE]);
+ $this->add('datepicker', 'registration_end_date', ts('Registration End Date'), [], FALSE, ['time' => TRUE]);
}
- $params = array(
+ $params = [
'used' => 'Supervised',
'contact_type' => 'Individual',
- );
+ ];
$dedupeRuleFields = CRM_Dedupe_BAO_Rule::dedupeRuleFields($params);
foreach ($dedupeRuleFields as $key => $fields) {
@@ -271,7 +262,7 @@ public function buildQuickForm() {
// CRM-17745: Make maximum additional participants configurable
$numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 9);
- $this->add('select', 'max_additional_participants', ts('Maximum additional participants'), $numericOptions, FALSE, array('class' => 'required'));
+ $this->add('select', 'max_additional_participants', ts('Maximum additional participants'), $numericOptions, FALSE, ['class' => 'required']);
$this->addElement('checkbox',
'allow_same_participant_emails',
@@ -279,9 +270,9 @@ public function buildQuickForm() {
);
$this->assign('ruleFields', json_encode($ruleFields));
- $dedupeRules = array(
+ $dedupeRules = [
'' => '- Unsupervised rule -',
- );
+ ];
$dedupeRules += CRM_Dedupe_BAO_RuleGroup::getByType('Individual');
$this->add('select', 'dedupe_rule_group_id', ts('Duplicate matching rule'), $dedupeRules);
@@ -291,14 +282,14 @@ public function buildQuickForm() {
'requires_approval',
ts('Require participant approval?'),
NULL,
- array('onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);")
+ ['onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);"]
);
$this->add('textarea', 'approval_req_text', ts('Approval message'), $attributes['approval_req_text']);
}
$this->add('text', 'expiration_time', ts('Pending participant expiration (hours)'));
$this->addRule('expiration_time', ts('Please enter the number of hours (as an integer).'), 'integer');
- $this->addField('allow_selfcancelxfer', array('label' => ts('Allow self-service cancellation or transfer?'), 'type' => 'advcheckbox'));
+ $this->addField('allow_selfcancelxfer', ['label' => ts('Allow self-service cancellation or transfer?'), 'type' => 'advcheckbox']);
$this->add('text', 'selfcancelxfer_time', ts('Cancellation or transfer time limit (hours)'));
$this->addRule('selfcancelxfer_time', ts('Please enter the number of hours (as an integer).'), 'integer');
self::buildRegistrationBlock($this);
@@ -316,7 +307,7 @@ public function buildQuickForm() {
*
*/
public function buildRegistrationBlock(&$form) {
- $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'intro_text') + array('class' => 'collapsed', 'preset' => 'civievent');
+ $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'intro_text') + ['class' => 'collapsed', 'preset' => 'civievent'];
$form->add('wysiwyg', 'intro_text', ts('Introductory Text'), $attributes);
$form->add('wysiwyg', 'footer_text', ts('Footer Text'), $attributes);
@@ -357,17 +348,17 @@ public function buildMultipleProfileBottom(&$form, $count, $prefix = '', $label
* ['allowCoreTypes' => array, 'allowSubTypes' => array, 'profileEntities' => array]
*/
public static function getProfileSelectorTypes() {
- $configs = array(
- 'allowCoreTypes' => array(),
- 'allowSubTypes' => array(),
- 'profileEntities' => array(),
- 'usedFor' => array(),
- );
-
- $configs['allowCoreTypes'] = array_merge(array(
- 'Contact',
- 'Individual',
- ), CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $configs = [
+ 'allowCoreTypes' => [],
+ 'allowSubTypes' => [],
+ 'profileEntities' => [],
+ 'usedFor' => [],
+ ];
+
+ $configs['allowCoreTypes'] = array_merge([
+ 'Contact',
+ 'Individual',
+ ], CRM_Contact_BAO_ContactType::subTypes('Individual'));
$configs['allowCoreTypes'][] = 'Participant';
if (CRM_Core_Permission::check('manage event profiles') && !CRM_Core_Permission::check('administer CiviCRM')) {
$configs['usedFor'][] = 'CiviEvent';
@@ -377,16 +368,16 @@ public static function getProfileSelectorTypes() {
if ($id) {
$participantEventType = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $id, 'event_type_id', 'id');
$participantRole = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'default_role_id');
- $configs['allowSubTypes']['ParticipantEventName'] = array($id);
- $configs['allowSubTypes']['ParticipantEventType'] = array($participantEventType);
- $configs['allowSubTypes']['ParticipantRole'] = array($participantRole);
+ $configs['allowSubTypes']['ParticipantEventName'] = [$id];
+ $configs['allowSubTypes']['ParticipantEventType'] = [$participantEventType];
+ $configs['allowSubTypes']['ParticipantRole'] = [$participantRole];
}
- $configs['profileEntities'][] = array('entity_name' => 'contact_1', 'entity_type' => 'IndividualModel');
- $configs['profileEntities'][] = array(
+ $configs['profileEntities'][] = ['entity_name' => 'contact_1', 'entity_type' => 'IndividualModel'];
+ $configs['profileEntities'][] = [
'entity_name' => 'participant_1',
'entity_type' => 'ParticipantModel',
'entity_sub_type' => '*',
- );
+ ];
return $configs;
}
@@ -403,11 +394,11 @@ public function buildConfirmationBlock(&$form) {
$is_monetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_id, 'is_monetary');
$form->assign('is_monetary', $is_monetary);
if ($is_monetary == "0") {
- $form->addYesNo('is_confirm_enabled', ts('Use a confirmation screen?'), NULL, NULL, array('onclick' => "return showHideByValue('is_confirm_enabled','','confirm_screen_settings','block','radio',false);"));
+ $form->addYesNo('is_confirm_enabled', ts('Use a confirmation screen?'), NULL, NULL, ['onclick' => "return showHideByValue('is_confirm_enabled','','confirm_screen_settings','block','radio',false);"]);
}
$form->add('text', 'confirm_title', ts('Title'), $attributes['confirm_title']);
- $form->add('wysiwyg', 'confirm_text', ts('Introductory Text'), $attributes['confirm_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
- $form->add('wysiwyg', 'confirm_footer_text', ts('Footer Text'), $attributes['confirm_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
+ $form->add('wysiwyg', 'confirm_text', ts('Introductory Text'), $attributes['confirm_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
+ $form->add('wysiwyg', 'confirm_footer_text', ts('Footer Text'), $attributes['confirm_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
}
/**
@@ -419,7 +410,7 @@ public function buildConfirmationBlock(&$form) {
public function buildMailBlock(&$form) {
$form->registerRule('emailList', 'callback', 'emailList', 'CRM_Utils_Rule');
$attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
- $form->addYesNo('is_email_confirm', ts('Send Confirmation Email?'), NULL, NULL, array('onclick' => "return showHideByValue('is_email_confirm','','confirmEmail','block','radio',false);"));
+ $form->addYesNo('is_email_confirm', ts('Send Confirmation Email?'), NULL, NULL, ['onclick' => "return showHideByValue('is_email_confirm','','confirmEmail','block','radio',false);"]);
$form->add('textarea', 'confirm_email_text', ts('Text'), $attributes['confirm_email_text']);
$form->add('text', 'cc_confirm', ts('CC Confirmation To'), CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'cc_confirm'));
$form->addRule('cc_confirm', ts('Please enter a valid list of comma delimited email addresses'), 'emailList');
@@ -436,8 +427,8 @@ public function buildMailBlock(&$form) {
public function buildThankYouBlock(&$form) {
$attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
$form->add('text', 'thankyou_title', ts('Title'), $attributes['thankyou_title']);
- $form->add('wysiwyg', 'thankyou_text', ts('Introductory Text'), $attributes['thankyou_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
- $form->add('wysiwyg', 'thankyou_footer_text', ts('Footer Text'), $attributes['thankyou_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
+ $form->add('wysiwyg', 'thankyou_text', ts('Introductory Text'), $attributes['thankyou_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
+ $form->add('wysiwyg', 'thankyou_footer_text', ts('Footer Text'), $attributes['thankyou_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
}
/**
@@ -450,7 +441,7 @@ public function addRules() {
if ($this->_addProfileBottom || $this->_addProfileBottomAdd) {
return;
}
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Registration', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Registration', 'formRule'], $this);
}
/**
@@ -482,26 +473,21 @@ public static function formRule($values, $files, $form) {
}
}
- if (
- isset($values['registration_start_date']) &&
- isset($values['registration_end_date'])
- ) {
- $start = CRM_Utils_Date::processDate($values['registration_start_date']);
- $end = CRM_Utils_Date::processDate($values['registration_end_date']);
- if ($end < $start) {
+ if (isset($values['registration_start_date']) && isset($values['registration_end_date'])) {
+ if ($values['registration_end_date'] < $values['registration_start_date']) {
$errorMsg['registration_end_date'] = ts('Registration end date should be after Registration start date');
}
}
//check that the selected profiles have either firstname+lastname or email required
- $profileIds = array(
+ $profileIds = [
CRM_Utils_Array::value('custom_pre_id', $values),
CRM_Utils_Array::value('custom_post_id', $values),
- );
- $additionalProfileIds = array(
+ ];
+ $additionalProfileIds = [
CRM_Utils_Array::value('additional_custom_pre_id', $values),
CRM_Utils_Array::value('additional_custom_post_id', $values),
- );
+ ];
//additional profile fields default to main if not set
if (!is_numeric($additionalProfileIds[0])) {
$additionalProfileIds[0] = $profileIds[0];
@@ -525,7 +511,7 @@ public static function formRule($values, $files, $form) {
$additionalCustomPreId = $additionalCustomPostId = NULL;
$isPreError = $isPostError = TRUE;
if (!empty($values['allow_same_participant_emails']) && !empty($values['is_multiple_registrations'])) {
- $types = array_merge(array('Individual'), CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $types = array_merge(['Individual'], CRM_Contact_BAO_ContactType::subTypes('Individual'));
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types);
//check for additional custom pre profile
@@ -651,7 +637,7 @@ public static function formRule($values, $files, $form) {
* @return bool
*/
public static function getEmailFields($profileIds) {
- $emailFields = array();
+ $emailFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -672,7 +658,7 @@ public static function getEmailFields($profileIds) {
* @return bool
*/
public static function isProfileComplete($profileIds) {
- $profileReqFields = array();
+ $profileReqFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -708,21 +694,21 @@ public static function isProfileComplete($profileIds) {
*/
public static function canProfilesDedupe($profileIds, $rgId = 0) {
// find the unsupervised rule
- $rgParams = array(
+ $rgParams = [
'used' => 'Unsupervised',
'contact_type' => 'Individual',
- );
+ ];
if ($rgId > 0) {
$rgParams['id'] = $rgId;
}
$activeRg = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($rgParams);
// get the combinations that could be a match for the rule
- $okCombos = $combos = array();
+ $okCombos = $combos = [];
CRM_Dedupe_BAO_RuleGroup::combos($activeRg[0], $activeRg[1], $combos);
// create an index of what combinations involve each field
- $index = array();
+ $index = [];
foreach ($combos as $comboid => $combo) {
foreach ($combo as $cfield) {
$index[$cfield][$comboid] = TRUE;
@@ -732,7 +718,7 @@ public static function canProfilesDedupe($profileIds, $rgId = 0) {
}
// get profiles and see if they have the necessary combos
- $profileReqFields = array();
+ $profileReqFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -808,7 +794,8 @@ public function postProcess() {
// format params
$params['is_online_registration'] = CRM_Utils_Array::value('is_online_registration', $params, FALSE);
- $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE); // CRM-11182
+ // CRM-11182
+ $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE);
$params['is_multiple_registrations'] = CRM_Utils_Array::value('is_multiple_registrations', $params, FALSE);
$params['allow_same_participant_emails'] = CRM_Utils_Array::value('allow_same_participant_emails', $params, FALSE);
$params['requires_approval'] = CRM_Utils_Array::value('requires_approval', $params, FALSE);
@@ -821,31 +808,20 @@ public function postProcess() {
$params['selfcancelxfer_time'] = !empty($params['selfcancelxfer_time']) ? $params['selfcancelxfer_time'] : 0;
}
- if (!$this->_isTemplate) {
- $params['registration_start_date'] = CRM_Utils_Date::processDate($params['registration_start_date'],
- $params['registration_start_date_time'],
- TRUE
- );
- $params['registration_end_date'] = CRM_Utils_Date::processDate($params['registration_end_date'],
- $params['registration_end_date_time'],
- TRUE
- );
- }
-
CRM_Event_BAO_Event::add($params);
// also update the ProfileModule tables
- $ufJoinParams = array(
+ $ufJoinParams = [
'is_active' => 1,
'module' => 'CiviEvent',
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
- );
+ ];
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
- $uf = array();
+ $uf = [];
$wt = 2;
if (!empty($params['custom_pre_id'])) {
$uf[1] = $params['custom_pre_id'];
@@ -869,17 +845,17 @@ public function postProcess() {
}
}
// also update the ProfileModule tables
- $ufJoinParamsAdd = array(
+ $ufJoinParamsAdd = [
'is_active' => 1,
'module' => 'CiviEvent_Additional',
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
- );
+ ];
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParamsAdd);
if (!empty($params['is_multiple_registrations'])) {
- $ufAdd = array();
+ $ufAdd = [];
$wtAdd = 2;
if (array_key_exists('additional_custom_pre_id', $params)) {
@@ -907,7 +883,7 @@ public function postProcess() {
}
if (!empty($params['additional_custom_post_id_multiple'])) {
- $additionalPostMultiple = array();
+ $additionalPostMultiple = [];
foreach ($params['additional_custom_post_id_multiple'] as $key => $value) {
if (is_null($value) && !empty($params['custom_post_id'])) {
$additionalPostMultiple[$key] = $params['custom_post_id'];
@@ -936,14 +912,14 @@ public function postProcess() {
}
// get the profiles to evaluate what they collect
- $profileIds = array(
+ $profileIds = [
CRM_Utils_Array::value('custom_pre_id', $params),
CRM_Utils_Array::value('custom_post_id', $params),
- );
- $additionalProfileIds = array(
+ ];
+ $additionalProfileIds = [
CRM_Utils_Array::value('additional_custom_pre_id', $params),
CRM_Utils_Array::value('additional_custom_post_id', $params),
- );
+ ];
// additional profile fields default to main if not set
if (!is_numeric($additionalProfileIds[0])) {
$additionalProfileIds[0] = $profileIds[0];
@@ -988,7 +964,7 @@ public function postProcess() {
}
}
if ($cantDedupe) {
- CRM_Core_Session::setStatus($cantDedupe, $dedupeTitle, 'alert dedupenotify', array('expires' => 0));
+ CRM_Core_Session::setStatus($cantDedupe, $dedupeTitle, 'alert dedupenotify', ['expires' => 0]);
}
// Update tab "disabled" css class
diff --git a/CRM/Event/Form/ManageEvent/Repeat.php b/CRM/Event/Form/ManageEvent/Repeat.php
index f031f006e0be..c7fb5591e1a2 100644
--- a/CRM/Event/Form/ManageEvent/Repeat.php
+++ b/CRM/Event/Form/ManageEvent/Repeat.php
@@ -14,17 +14,19 @@ class CRM_Event_Form_ManageEvent_Repeat extends CRM_Event_Form_ManageEvent {
/**
* Parent Event Start Date.
+ * @var string
*/
protected $_parentEventStartDate = NULL;
/**
* Parent Event End Date.
+ * @var string
*/
protected $_parentEventEndDate = NULL;
-
public function preProcess() {
parent::preProcess();
+ $this->setSelectedChild('repeat');
$this->assign('currentEventId', $this->_id);
$checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($this->_id, 'civicrm_event');
@@ -35,13 +37,13 @@ public function preProcess() {
*/
//Get all connected event ids
$allEventIdsArray = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($checkParentExistsForThisId, 'civicrm_event');
- $allEventIds = array();
+ $allEventIds = [];
if (!empty($allEventIdsArray)) {
foreach ($allEventIdsArray as $key => $val) {
$allEventIds[] = $val['id'];
}
if (!empty($allEventIds)) {
- $params = array();
+ $params = [];
$query = "
SELECT *
FROM civicrm_event
@@ -53,7 +55,7 @@ public function preProcess() {
$permissions = CRM_Event_BAO_Event::checkPermission();
while ($dao->fetch()) {
if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
- $manageEvent[$dao->id] = array();
+ $manageEvent[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
}
}
@@ -62,9 +64,9 @@ public function preProcess() {
}
}
- $parentEventParams = array('id' => $this->_id);
- $parentEventValues = array();
- $parentEventReturnProperties = array('start_date', 'end_date');
+ $parentEventParams = ['id' => $this->_id];
+ $parentEventValues = [];
+ $parentEventReturnProperties = ['start_date', 'end_date'];
$parentEventAttributes = CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $parentEventParams, $parentEventValues, $parentEventReturnProperties);
$this->_parentEventStartDate = $parentEventAttributes->start_date;
$this->_parentEventEndDate = $parentEventAttributes->end_date;
@@ -78,11 +80,10 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
//Always pass current event's start date by default
- $currentEventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'start_date', 'id');
- list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($currentEventStartDate, 'activityDateTime');
+ $defaults['repetition_start_date'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'start_date', 'id');
$recurringEntityDefaults = CRM_Core_Form_RecurringEntity::setDefaultValues();
return array_merge($defaults, $recurringEntityDefaults);
}
@@ -96,10 +97,10 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
if ($this->_parentEventStartDate && $this->_parentEventEndDate) {
$interval = CRM_Core_BAO_RecurringEntity::getInterval($this->_parentEventStartDate, $this->_parentEventEndDate);
- $params['intervalDateColumns'] = array('end_date' => $interval);
+ $params['intervalDateColumns'] = ['end_date' => $interval];
}
- $params['dateColumns'] = array('start_date');
- $params['excludeDateRangeColumns'] = array('start_date', 'end_date');
+ $params['dateColumns'] = ['start_date'];
+ $params['excludeDateRangeColumns'] = ['start_date', 'end_date'];
$params['entity_table'] = 'civicrm_event';
$params['entity_id'] = $this->_id;
@@ -110,46 +111,46 @@ public function postProcess() {
unset($params['id']);
$url = 'civicrm/event/manage/repeat';
- $urlParams = "action=update&reset=1&id={$this->_id}";
+ $urlParams = "action=update&reset=1&id={$this->_id}&selectedChild=repeat";
- $linkedEntities = array(
- array(
+ $linkedEntities = [
+ [
'table' => 'civicrm_price_set_entity',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => FALSE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_uf_join',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => FALSE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_tell_friend',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => TRUE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_pcp_block',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => TRUE,
- ),
- );
+ ],
+ ];
CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_event', $linkedEntities);
CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
}
@@ -168,8 +169,8 @@ public function postProcess() {
*
* @return array
*/
- static public function getParticipantCountforEvent($listOfRelatedEntities = array()) {
- $participantDetails = array();
+ public static function getParticipantCountforEvent($listOfRelatedEntities = []) {
+ $participantDetails = [];
if (!empty($listOfRelatedEntities)) {
$implodeRelatedEntities = implode(',', array_map(function ($entity) {
return $entity['id'];
@@ -192,21 +193,21 @@ static public function getParticipantCountforEvent($listOfRelatedEntities = arra
}
/**
- * This function checks if there was any registraion for related event ids,
- * and returns array of ids with no regsitrations
+ * This function checks if there was any registration for related event ids,
+ * and returns array of ids with no registrations
*
- * @param string or int or object... $eventID
+ * @param mixed $eventID string, int or object
*
* @return array
*/
public static function checkRegistrationForEvents($eventID) {
- $eventIdsWithNoRegistration = array();
+ $eventIdsWithNoRegistration = [];
if ($eventID) {
$getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($eventID, 'civicrm_event', TRUE);
$participantDetails = CRM_Event_Form_ManageEvent_Repeat::getParticipantCountforEvent($getRelatedEntities);
//Check if participants exists for events
foreach ($getRelatedEntities as $key => $value) {
- if (!CRM_Utils_Array::value($value['id'], $participantDetails['countByID']) && $value['id'] != $eventID) {
+ if (empty($participantDetails['countByID'][$value['id']]) && $value['id'] != $eventID) {
//CRM_Event_BAO_Event::del($value['id']);
$eventIdsWithNoRegistration[] = $value['id'];
}
diff --git a/CRM/Event/Form/ManageEvent/ScheduleReminders.php b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
index aa8e69182bd0..4129564e5739 100644
--- a/CRM/Event/Form/ManageEvent/ScheduleReminders.php
+++ b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
@@ -1,9 +1,9 @@
setSelectedChild('reminder');
$setTab = CRM_Utils_Request::retrieve('setTab', 'Int', $this, FALSE, 0);
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => ($this->_isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
- )));
+ ]));
$reminderList = CRM_Core_BAO_ActionSchedule::getList(FALSE, $mapping, $this->_id);
if ($reminderList && is_array($reminderList)) {
// Add action links to each of the reminders
@@ -70,7 +71,7 @@ public function preProcess() {
$format['action'] = CRM_Core_Action::formLink(
$links,
$action,
- array('id' => $format['id']),
+ ['id' => $format['id']],
ts('more'),
FALSE,
'actionSchedule.manage.action',
diff --git a/CRM/Event/Form/ManageEvent/TabHeader.php b/CRM/Event/Form/ManageEvent/TabHeader.php
index a818a54e481f..c373f901a87d 100644
--- a/CRM/Event/Form/ManageEvent/TabHeader.php
+++ b/CRM/Event/Form/ManageEvent/TabHeader.php
@@ -1,9 +1,9 @@
get('tabHeader');
@@ -52,11 +53,11 @@ public static function build(&$form) {
$form->assign_by_ref('tabHeader', $tabs);
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')
- ->addSetting(array(
- 'tabSettings' => array(
+ ->addSetting([
+ 'tabSettings' => [
'active' => self::getCurrentTab($tabs),
- ),
- ));
+ ],
+ ]);
CRM_Event_Form_ManageEvent::addProfileEditScripts();
return $tabs;
}
@@ -72,26 +73,28 @@ public static function process(&$form) {
return NULL;
}
- $default = array(
+ $default = [
'link' => NULL,
'valid' => TRUE,
'active' => TRUE,
'current' => FALSE,
'class' => 'ajaxForm',
- );
-
- $tabs = array();
- $tabs['settings'] = array('title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage') + $default;
- $tabs['location'] = array('title' => ts('Event Location')) + $default;
- $tabs['fee'] = array('title' => ts('Fees')) + $default;
- $tabs['registration'] = array('title' => ts('Online Registration')) + $default;
- if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
- $tabs['reminder'] = array('title' => ts('Schedule Reminders'), 'class' => 'livePage') + $default;
+ ];
+
+ $tabs = [];
+ $tabs['settings'] = ['title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage'] + $default;
+ $tabs['location'] = ['title' => ts('Event Location')] + $default;
+ $tabs['fee'] = ['title' => ts('Fees')] + $default;
+ $tabs['registration'] = ['title' => ts('Online Registration')] + $default;
+ // @fixme I don't understand the event permissions check here - can we just get rid of it?
+ $permissions = CRM_Event_BAO_Event::getAllPermissions();
+ if (CRM_Core_Permission::check('administer CiviCRM') || !empty($permissions[CRM_Core_Permission::EDIT])) {
+ $tabs['reminder'] = ['title' => ts('Schedule Reminders'), 'class' => 'livePage'] + $default;
}
- $tabs['conference'] = array('title' => ts('Conference Slots')) + $default;
- $tabs['friend'] = array('title' => ts('Tell a Friend')) + $default;
- $tabs['pcp'] = array('title' => ts('Personal Campaigns')) + $default;
- $tabs['repeat'] = array('title' => ts('Repeat')) + $default;
+ $tabs['conference'] = ['title' => ts('Conference Slots')] + $default;
+ $tabs['friend'] = ['title' => ts('Tell a Friend')] + $default;
+ $tabs['pcp'] = ['title' => ts('Personal Campaigns')] + $default;
+ $tabs['repeat'] = ['title' => ts('Repeat')] + $default;
// Repeat tab must refresh page when switching repeat mode so js & vars will get set-up
if (!$form->_isRepeatingEvent) {
@@ -107,9 +110,9 @@ public static function process(&$form) {
$eventID = $form->getVar('_id');
if ($eventID) {
// disable tabs based on their configuration status
- $eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
+ ]));
$sql = "
SELECT e.loc_block_id as is_location, e.is_online_registration, e.is_monetary, taf.is_active, pcp.is_active as is_pcp, sch.id as is_reminder, re.id as is_repeating_event
FROM civicrm_event e
@@ -121,10 +124,10 @@ public static function process(&$form) {
";
//Check if repeat is configured
$eventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($eventID, 'civicrm_event');
- $params = array(
- 1 => array($eventID, 'Integer'),
- 2 => array($eventNameMapping->getId(), 'Integer'),
- );
+ $params = [
+ 1 => [$eventID, 'Integer'],
+ 2 => [$eventNameMapping->getId(), 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if (!$dao->fetch()) {
CRM_Core_Error::fatal();
@@ -155,7 +158,7 @@ public static function process(&$form) {
// see if any other modules want to add any tabs
// note: status of 'valid' flag of any injected tab, needs to be taken care in the hook implementation.
CRM_Utils_Hook::tabset('civicrm/event/manage', $tabs,
- array('event_id' => $eventID));
+ ['event_id' => $eventID]);
$fullName = $form->getVar('_name');
$className = CRM_Utils_String::getClassName($fullName);
@@ -165,7 +168,7 @@ public static function process(&$form) {
switch ($className) {
case 'Event':
$attributes = $form->getVar('_attributes');
- $class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
+ $class = CRM_Utils_Request::retrieveComponent($attributes);
break;
case 'EventInfo':
@@ -235,7 +238,7 @@ public static function getCurrentTab($tabs) {
if (is_array($tabs)) {
foreach ($tabs as $subPage => $pageVal) {
- if ($pageVal['current'] === TRUE) {
+ if (CRM_Utils_Array::value('current', $pageVal) === TRUE) {
$current = $subPage;
break;
}
diff --git a/CRM/Event/Form/Participant.php b/CRM/Event/Form/Participant.php
index 0a8dc5db4857..54e82d0d368e 100644
--- a/CRM/Event/Form/Participant.php
+++ b/CRM/Event/Form/Participant.php
@@ -1,9 +1,9 @@
contactID
*
* The id of the contact associated with this participation.
*
* @var int
+ * @deprecated
*/
public $_contactId;
@@ -106,58 +106,67 @@ class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment
* Are we operating in "single mode", i.e. adding / editing only
* one participant record, or is this a batch add operation
*
- * @var boolean
+ * @var bool
*/
public $_single = FALSE;
/**
* If event is paid or unpaid.
+ * @var bool
*/
public $_isPaidEvent;
/**
* Page action.
+ * @var int
*/
public $_action;
/**
* Role Id.
+ * @var int
*/
protected $_roleId = NULL;
/**
* Event Type Id.
+ * @var int
*/
protected $_eventTypeId = NULL;
/**
* Participant status Id.
+ * @var int
*/
protected $_statusId = NULL;
/**
* Cache all the participant statuses.
+ * @var array
*/
protected $_participantStatuses;
/**
* Participant mode.
+ * @var string
*/
public $_mode = NULL;
/**
* Event ID preselect.
+ * @var int
*/
public $_eID = NULL;
/**
* Line Item for Price Set.
+ * @var array
*/
public $_lineItem = NULL;
/**
* Contribution mode for event registration for offline mode.
- *
+ * @var string
* @deprecated
*/
public $_contributeMode = 'direct';
@@ -166,32 +175,37 @@ class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment
/**
* Store id of role custom data type ( option value )
+ * @var int
*/
protected $_roleCustomDataTypeID;
/**
* Store id of event Name custom data type ( option value)
+ * @var int
*/
protected $_eventNameCustomDataTypeID;
/**
* Selected discount id.
+ * @var int
*/
public $_originalDiscountId = NULL;
/**
* Event id.
+ * @var int
*/
public $_eventId = NULL;
/**
* Id of payment, if any
+ * @var int
*/
public $_paymentId = NULL;
/**
- * @todo add explanatory note about this
* @var null
+ * @todo add explanatory note about this
*/
public $_onlinePendingContributionId = NULL;
@@ -202,10 +216,18 @@ public function getDefaultEntity() {
return 'Participant';
}
+ /**
+ * Default form context used as part of addField()
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Set variables up before form is built.
*
* @return void
+ * @throws \CRM_Core_Exception
*/
public function preProcess() {
parent::preProcess();
@@ -216,11 +238,11 @@ public function preProcess() {
// @todo eliminate this duplication.
$this->_contactId = $this->_contactID;
$this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $this->_context);
if ($this->_contactID) {
- $this->setPageTitle(ts('Event Registration for %1', array(1 => $this->userDisplayName)));
+ $this->setPageTitle(ts('Event Registration for %1', [1 => $this->userDisplayName]));
}
else {
$this->setPageTitle(ts('Event Registration'));
@@ -263,15 +285,7 @@ public function preProcess() {
}
}
}
-
- // get the option value for custom data type
- $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
- $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
- $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
- $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
- $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
- $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
- $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
+ $this->setCustomDataTypes();
if ($this->_mode) {
$this->assign('participantMode', $this->_mode);
@@ -292,12 +306,12 @@ public function preProcess() {
$this->_single = TRUE;
$this->assign('urlPath', 'civicrm/contact/view/participant');
if (!$this->_id && !$this->_contactId) {
- $breadCrumbs = array(
- array(
+ $breadCrumbs = [
+ [
'title' => ts('CiviEvent Dashboard'),
'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumbs);
}
@@ -373,6 +387,7 @@ public function preProcess() {
// when custom data is included in this page
if (!empty($_POST['hidden_custom'])) {
+ $eventId = (int) CRM_Utils_Array::value('event_id', $_POST);
// Custom data of type participant role
// Note: Some earlier commits imply $_POST['role_id'] could be a comma separated string,
// not sure if that ever really happens
@@ -385,13 +400,13 @@ public function preProcess() {
}
//custom data of type participant event
- CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $_POST['event_id'], 1, 'Participant', $this->_id);
+ CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $eventId, 1, 'Participant', $this->_id);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
// custom data of type participant event type
$eventTypeId = NULL;
- if ($eventId = CRM_Utils_Array::value('event_id', $_POST)) {
+ if ($eventId) {
$eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
}
CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
@@ -420,23 +435,23 @@ public function preProcess() {
* This function sets the default values for the form in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
+ * @throws \CRM_Core_Exception
*/
public function setDefaultValues() {
if ($this->_showFeeBlock) {
return CRM_Event_Form_EventFees::setDefaultValues($this);
}
- $defaults = array();
+ $defaults = [];
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
if ($this->_id) {
- $ids = array();
- $params = array('id' => $this->_id);
+ $ids = [];
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
@@ -467,15 +482,6 @@ public function setDefaultValues() {
}
}
- if ($this->_action & (CRM_Core_Action::VIEW | CRM_Core_Action::BROWSE)) {
- $inactiveNeeded = TRUE;
- $viewMode = TRUE;
- }
- else {
- $viewMode = FALSE;
- $inactiveNeeded = FALSE;
- }
-
//setting default register date
if ($this->_action == CRM_Core_Action::ADD) {
$statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
@@ -513,6 +519,7 @@ public function setDefaultValues() {
if (!empty($submittedEvent[0])) {
$eventID = $submittedEvent[0];
}
+ $defaults[$this->_id]['register_date'] = date('Y-m-d H:i:s');
}
else {
$defaults[$this->_id]['record_contribution'] = 0;
@@ -532,9 +539,6 @@ public function setDefaultValues() {
}
}
- list($defaults[$this->_id]['register_date'], $defaults[$this->_id]['register_date_time'])
- = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('register_date', $defaults[$this->_id]), 'activityDateTime');
-
//assign event and role id, this is needed for Custom data building
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
if (!empty($defaults[$this->_id]['participant_role_id'])) {
@@ -586,8 +590,11 @@ public function setDefaultValues() {
* Build the form object.
*
* @return void
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function buildQuickForm() {
+
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
$partiallyPaidStatusId = array_search('Partially paid', $participantStatuses);
$this->assign('partiallyPaidStatusId', $partiallyPaidStatusId);
@@ -610,51 +617,50 @@ public function buildQuickForm() {
TRUE
)) - 1;
if ($additionalParticipant) {
- $deleteParticipants = array(
+ $deleteParticipants = [
1 => ts('Delete this participant record along with associated participant record(s).'),
2 => ts('Delete only this participant record.'),
- );
+ ];
$this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '
');
- $this->setDefaults(array('delete_participant' => 1));
+ $this->setDefaults(['delete_participant' => 1]);
$this->assign('additionalParticipant', $additionalParticipant);
}
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
return;
}
if ($this->_single && $this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Contact'), array(
- 'create' => TRUE,
- 'api' => array('extra' => array('email')),
- ), TRUE);
+ $this->addEntityRef('contact_id', ts('Contact'), [
+ 'create' => TRUE,
+ 'api' => ['extra' => ['email']],
+ ], TRUE);
}
- $eventFieldParams = array(
- 'entity' => 'event',
- 'select' => array('minimumInputLength' => 0),
- 'api' => array(
- 'extra' => array('campaign_id', 'default_role_id', 'event_type_id'),
- ),
- );
+ $eventFieldParams = [
+ 'entity' => 'Event',
+ 'select' => ['minimumInputLength' => 0],
+ 'api' => [
+ 'extra' => ['campaign_id', 'default_role_id', 'event_type_id'],
+ ],
+ ];
if ($this->_mode) {
// exclude events which are not monetary when credit card registration is used
$eventFieldParams['api']['params']['is_monetary'] = 1;
- $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
}
+ $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
$element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
@@ -680,26 +686,25 @@ public function buildQuickForm() {
}
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
-
- $this->addDateTime('register_date', ts('Registration Date'), TRUE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'register_date', ts('Registration Date'), [], TRUE, ['time' => TRUE]);
if ($this->_id) {
$this->assign('entityID', $this->_id);
}
- $this->addSelect('role_id', array('multiple' => TRUE, 'class' => 'huge'), TRUE);
+ $this->addSelect('role_id', ['multiple' => TRUE, 'class' => 'huge'], TRUE);
// CRM-4395
- $checkCancelledJs = array('onchange' => "return sendNotification( );");
+ $checkCancelledJs = ['onchange' => "return sendNotification( );"];
$confirmJS = NULL;
if ($this->_onlinePendingContributionId) {
$cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
$cancelledContributionStatusId = array_search('Cancelled',
CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
);
- $checkCancelledJs = array(
+ $checkCancelledJs = [
'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
- );
+ ];
$participantStatusId = array_search('Pending from pay later',
CRM_Event_PseudoConstant::participantStatus()
@@ -707,18 +712,18 @@ public function buildQuickForm() {
$contributionStatusId = array_search('Completed',
CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
);
- $confirmJS = array('onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );");
+ $confirmJS = ['onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );"];
}
// get the participant status names to build special status array which is used to show notification
// checkbox below participant status select
$participantStatusName = CRM_Event_PseudoConstant::participantStatus();
- $notificationStatuses = array(
+ $notificationStatuses = [
'Cancelled',
'Pending from waitlist',
'Pending from approval',
'Expired',
- );
+ ];
// get the required status and then implode only ids
$notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
@@ -734,42 +739,42 @@ public function buildQuickForm() {
}
}
- $this->addSelect('status_id', $checkCancelledJs + array(
- 'options' => $statusOptions,
- 'option_url' => 'civicrm/admin/participant_status',
- ), TRUE);
+ $this->addSelect('status_id', $checkCancelledJs + [
+ 'options' => $statusOptions,
+ 'option_url' => 'civicrm/admin/participant_status',
+ ], TRUE);
$this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
- $this->add('text', 'source', ts('Event Source'));
+ $this->addField('source', ['entity' => 'Participant', 'name' => 'source']);
$noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
$this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
'js' => $confirmJS,
- );
+ ];
$path = CRM_Utils_System::currentPath();
- $excludeForPaths = array(
+ $excludeForPaths = [
'civicrm/contact/search',
'civicrm/group/search',
- );
+ ];
if (!in_array($path, $excludeForPaths)) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
'js' => $confirmJS,
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
if ($this->_action == CRM_Core_Action::VIEW) {
@@ -780,11 +785,10 @@ public function buildQuickForm() {
/**
* Add local and global form rules.
*
- *
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Participant', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Participant', 'formRule'], $this);
}
/**
@@ -809,7 +813,7 @@ public static function formRule($values, $files, $self) {
return TRUE;
}
- $errorMsg = array();
+ $errorMsg = [];
if (!empty($values['payment_processor_id'])) {
// make sure that payment instrument values (e.g. credit card number and cvv) are valid
@@ -823,7 +827,9 @@ public static function formRule($values, $files, $self) {
if (empty($values['payment_instrument_id'])) {
$errorMsg['payment_instrument_id'] = ts('Payment Method is a required field.');
}
- CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
+ if (!empty($values['priceSetId'])) {
+ CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
+ }
}
// validate contribution status for 'Failed'.
@@ -857,10 +863,17 @@ public static function formRule($values, $files, $self) {
}
$eventId = CRM_Utils_Array::value('event_id', $values);
- if (!empty($contactId) && !empty($eventId)) {
+
+ $event = new CRM_Event_DAO_Event();
+ $event->id = $eventId;
+ $event->find(TRUE);
+
+ if (!$event->allow_same_participant_emails && !empty($contactId) && !empty($eventId)) {
+ $cancelledStatusID = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Cancelled');
$dupeCheck = new CRM_Event_BAO_Participant();
$dupeCheck->contact_id = $contactId;
$dupeCheck->event_id = $eventId;
+ $dupeCheck->whereAdd("status_id != {$cancelledStatusID} ");
$dupeCheck->find(TRUE);
if (!empty($dupeCheck->id)) {
$errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
@@ -906,7 +919,7 @@ public function postProcess() {
}
if (!$this->_single && !empty($event_id)) {
$duplicateContacts = 0;
- while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
+ foreach ($this->_contactIds as $k => $dupeCheckContactId) {
// Eliminate contacts that have already been assigned to this event.
$dupeCheck = new CRM_Event_BAO_Participant();
$dupeCheck->contact_id = $dupeCheckContactId;
@@ -920,7 +933,7 @@ public function postProcess() {
if ($duplicateContacts > 0) {
$msg = ts(
"%1 contacts have already been assigned to this event. They were not added a second time.",
- array(1 => $duplicateContacts)
+ [1 => $duplicateContacts]
);
CRM_Core_Session::setStatus($msg);
}
@@ -935,6 +948,44 @@ public function postProcess() {
}
}
+ $statusMsg = $this->submit($params);
+ CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
+ $session = CRM_Core_Session::singleton();
+ $buttonName = $this->controller->getButtonName();
+ if ($this->_context == 'standalone') {
+ if ($buttonName == $this->getButtonName('upload', 'new')) {
+ $urlParams = 'reset=1&action=add&context=standalone';
+ if ($this->_mode) {
+ $urlParams .= '&mode=' . $this->_mode;
+ }
+ if ($this->_eID) {
+ $urlParams .= '&eid=' . $this->_eID;
+ }
+ $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
+ }
+ else {
+ $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
+ "reset=1&cid={$this->_contactId}&selectedChild=participant"
+ ));
+ }
+ }
+ elseif ($buttonName == $this->getButtonName('upload', 'new')) {
+ $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
+ "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
+ ));
+ }
+ }
+
+ /**
+ * Submit form.
+ *
+ * @param array $params
+ *
+ * @return string
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function submit($params) {
$participantStatus = CRM_Event_PseudoConstant::participantStatus();
// set the contact, when contact is selected
if (!empty($params['contact_id'])) {
@@ -954,10 +1005,10 @@ public function postProcess() {
}
if ($this->_isPaidEvent) {
- $contributionParams = array();
- $lineItem = array();
- $additionalParticipantDetails = array();
- if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
+ $contributionParams = ['skipCleanMoney' => TRUE];
+ $lineItem = [];
+ $additionalParticipantDetails = [];
+ if (Civi::settings()->get('deferred_revenue_enabled')) {
$eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
$contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
@@ -987,16 +1038,16 @@ public function postProcess() {
}
else {
- //check if discount is selected
- if (!empty($params['discount_id'])) {
- $discountId = $params['discount_id'];
- }
- else {
- $discountId = $params['discount_id'] = 'null';
+ // check that discount_id is set
+ if (empty($params['discount_id'])) {
+ $params['discount_id'] = 'null';
}
//lets carry currency, CRM-4453
$params['fee_currency'] = $config->defaultCurrency;
+ if (!isset($lineItem[0])) {
+ $lineItem[0] = [];
+ }
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
$params, $lineItem[0]
);
@@ -1031,7 +1082,7 @@ public function postProcess() {
$this->_lineItem = $lineItem;
$lineItem = array_merge($lineItem, $additionalParticipantDetails);
- $participantCount = array();
+ $participantCount = [];
foreach ($lineItem as $k) {
foreach ($k as $v) {
if (CRM_Utils_Array::value('participant_count', $v) > 0) {
@@ -1057,8 +1108,6 @@ public function postProcess() {
$amountOwed = $params['amount'];
unset($params['amount']);
}
- $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
- $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
$params['contact_id'] = $this->_contactId;
// overwrite actual payment amount if entered
@@ -1080,6 +1129,8 @@ public function postProcess() {
$this->_params['participant_register_date'] = $params['register_date'];
$roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
+ $now = date('YmdHis');
+
if ($this->_mode) {
if (!$this->_isPaidEvent) {
CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
@@ -1094,10 +1145,10 @@ public function postProcess() {
// set source if not set
if (empty($params['source'])) {
- $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
- 1 => $userName,
- 2 => $eventTitle,
- ));
+ $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', [
+ 1 => $userName,
+ 2 => $eventTitle,
+ ]);
}
else {
$this->_params['participant_source'] = $params['source'];
@@ -1107,8 +1158,7 @@ public function postProcess() {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
$this->_mode
);
- $now = date('YmdHis');
- $fields = array();
+ $fields = [];
// set email for primary location.
$fields['email-Primary'] = 1;
@@ -1132,7 +1182,7 @@ public function postProcess() {
$fields["email-{$this->_bltID}"] = 1;
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
- $nameFields = array('first_name', 'middle_name', 'last_name');
+ $nameFields = ['first_name', 'middle_name', 'last_name'];
foreach ($nameFields as $name) {
$fields[$name] = 1;
@@ -1145,7 +1195,7 @@ public function postProcess() {
}
if (!empty($this->_params['participant_role_id'])) {
- $customFieldsRole = array();
+ $customFieldsRole = [];
foreach ($this->_params['participant_role_id'] as $roleKey) {
$customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
@@ -1167,10 +1217,8 @@ public function postProcess() {
);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
- $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
- $this->_id,
- 'Participant'
- );
+
+ $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
}
//do cleanup line items if participant edit the Event Fee.
@@ -1180,9 +1228,7 @@ public function postProcess() {
if ($this->_mode) {
// add all the additional payment params we need
- $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
- $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
-
+ $this->_params = $this->prepareParamsForPaymentProcessor($this->_params);
$this->_params['amount'] = $params['fee_amount'];
$this->_params['amount_level'] = $params['amount_level'];
$this->_params['currencyID'] = $config->defaultCurrency;
@@ -1201,17 +1247,21 @@ public function postProcess() {
// so more conservative approach is called for.
// In fact the use of $params and $this->_params & $this->_contactId vs $contactID
// needs rationalising.
- $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
+ $mapParams = array_merge(['contact_id' => $contactID], $this->_params);
CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
$payment = $this->_paymentProcessor['object'];
// CRM-15622: fix for incorrect contribution.fee_amount
$paymentParams['fee_amount'] = NULL;
- $result = $payment->doPayment($paymentParams);
-
- if (is_a($result, 'CRM_Core_Error')) {
- CRM_Core_Error::displaySessionError($result);
+ try {
+ $result = $payment->doPayment($paymentParams);
+ }
+ catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
+ // @todo un comment the following line out when we are creating a contribution before we get to this point
+ // see dev/financial#53 about ensuring we create a pending contribution before we try processing payment
+ // CRM_Contribute_BAO_Contribution::failPayment($contributionID);
+ CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
"reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
));
@@ -1232,9 +1282,7 @@ public function postProcess() {
$this->set('params', $this->_params);
$this->assign('trxn_id', $result['trxn_id']);
- $this->assign('receive_date',
- CRM_Utils_Date::processDate($this->_params['receive_date'])
- );
+ $this->assign('receive_date', $this->_params['receive_date']);
//add contribution record
$this->_params['financial_type_id']
@@ -1242,10 +1290,15 @@ public function postProcess() {
$this->_params['mode'] = $this->_mode;
//add contribution record
- $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
+ $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution(
+ $this, $this->_params,
+ $result, $contactID,
+ FALSE, FALSE,
+ $this->_paymentProcessor
+ );
// add participant record
- $participants = array();
+ $participants = [];
if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
$this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
$this->_params['role_id']
@@ -1263,18 +1316,18 @@ public function postProcess() {
$participants[0]->id,
'Participant'
);
- //add participant payment
- $paymentParticipant = array(
+
+ // Add participant payment
+ $participantPaymentParams = [
'participant_id' => $participants[0]->id,
'contribution_id' => $contribution->id,
- );
- $ids = array();
+ ];
+ civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
- CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
$this->_contactIds[] = $this->_contactId;
}
else {
- $participants = array();
+ $participants = [];
if ($this->_single) {
if ($params['role_id']) {
$params['role_id'] = $roleIdWithSeparator;
@@ -1309,7 +1362,7 @@ public function postProcess() {
$this->_contactIds[] = $this->_contactId;
}
- $contributions = array();
+ $contributions = [];
if (!empty($params['record_contribution'])) {
if (!empty($params['id'])) {
if ($this->_onlinePendingContributionId) {
@@ -1328,10 +1381,10 @@ public function postProcess() {
//build contribution params
if (!$this->_onlinePendingContributionId) {
if (empty($params['source'])) {
- $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
- 1 => $eventTitle,
- 2 => $userName,
- ));
+ $contributionParams['source'] = ts('%1 : Offline registration (by %2)', [
+ 1 => $eventTitle,
+ 2 => $userName,
+ ]);
}
else {
$contributionParams['source'] = $params['source'];
@@ -1342,10 +1395,9 @@ public function postProcess() {
$contributionParams['non_deductible_amount'] = 'null';
$contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
$contributionParams['contact_id'] = $this->_contactID;
- // @todo change receive_date to datepicker field. Strip out all wrangling.
- $contributionParams['receive_date'] = $params['receive_date'];
+ $contributionParams['receive_date'] = CRM_Utils_Array::value('receive_date', $params, 'null');
- $recordContribution = array(
+ $recordContribution = [
'financial_type_id',
'payment_instrument_id',
'trxn_id',
@@ -1354,7 +1406,7 @@ public function postProcess() {
'campaign_id',
'pan_truncation',
'card_type_id',
- );
+ ];
foreach ($recordContribution as $f) {
$contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
@@ -1374,10 +1426,10 @@ public function postProcess() {
$contributionParams['participant_id'] = $this->_id;
}
// Set is_pay_later flag for back-office offline Pending status contributions
- if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
+ if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
$contributionParams['is_pay_later'] = 1;
}
- elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
+ elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
$contributionParams['is_pay_later'] = 0;
}
@@ -1399,7 +1451,7 @@ public function postProcess() {
// the owed amount
$contributionParams['partial_payment_total'] = $amountOwed;
// the actual amount paid
- $contributionParams['partial_amount_pay'] = $params['total_amount'];
+ $contributionParams['partial_amount_to_pay'] = $params['total_amount'];
}
}
@@ -1409,29 +1461,28 @@ public function postProcess() {
if ($this->_single) {
if (empty($ids)) {
- $ids = array();
+ $ids = [];
}
$contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
}
else {
- $ids = array();
+ $ids = [];
foreach ($this->_contactIds as $contactID) {
$contributionParams['contact_id'] = $contactID;
$contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
}
}
- //insert payment record for this participation
+ // Insert payment record for this participant
if (empty($ids['contribution'])) {
foreach ($this->_contactIds as $num => $contactID) {
- $ppDAO = new CRM_Event_DAO_ParticipantPayment();
- $ppDAO->participant_id = $participants[$num]->id;
- $ppDAO->contribution_id = $contributions[$num]->id;
- $ppDAO->save();
+ $participantPaymentParams = [
+ 'participant_id' => $participants[$num]->id,
+ 'contribution_id' => $contributions[$num]->id,
+ ];
+ civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
}
}
- // next create the transaction record
- $transaction = new CRM_Core_Transaction();
// CRM-11124
if ($this->_params['discount_id']) {
@@ -1442,7 +1493,6 @@ public function postProcess() {
CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
);
}
- $transaction->commit();
}
}
@@ -1485,8 +1535,8 @@ public function postProcess() {
);
}
- $sent = array();
- $notSent = array();
+ $sent = [];
+ $notSent = [];
if (!empty($params['send_receipt'])) {
if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
$receiptFrom = $params['from_email_address'];
@@ -1494,8 +1544,8 @@ public function postProcess() {
$this->assign('module', 'Event Registration');
//use of the message template below requires variables in different format
- $event = $events = array();
- $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
+ $event = $events = [];
+ $returnProperties = ['event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
//get all event details.
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
@@ -1506,7 +1556,7 @@ public function postProcess() {
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = CRM_Utils_Array::value('role_id', $params);
if (is_array($participantRoles)) {
- $selectedRoles = array();
+ $selectedRoles = [];
foreach ($participantRoles as $roleId) {
$selectedRoles[] = $role[$roleId];
}
@@ -1526,10 +1576,10 @@ public function postProcess() {
$this->assign('isShowLocation', $event['is_show_location']);
if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $params['event_id'],
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
@@ -1550,7 +1600,7 @@ public function postProcess() {
$this->assign('totalAmount', $contributionParams['total_amount']);
if (isset($contributionParams['partial_payment_total'])) {
// balance amount
- $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
+ $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_to_pay'];
$this->assign('balanceAmount', $balanceAmount);
}
$this->assign('isPrimary', 1);
@@ -1578,24 +1628,26 @@ public function postProcess() {
}
$this->assign('register_date', $params['register_date']);
- if ($params['receive_date']) {
+ if (isset($params['receive_date'])) {
$this->assign('receive_date', $params['receive_date']);
}
- $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
+ $participant = [['participant_id', '=', $participants[0]->id, 0, 0]];
// check whether its a test drive ref CRM-3075
if (!empty($this->_defaultValues['is_test'])) {
- $participant[] = array('participant_test', '=', 1, 0, 0);
+ $participant[] = ['participant_test', '=', 1, 0, 0];
}
- $template = CRM_Core_Smarty::singleton();
- $customGroup = array();
+ $customGroup = [];
//format submitted data
foreach ($params['custom'] as $fieldID => $values) {
foreach ($values as $fieldValue) {
- $customFields[$fieldID]['id'] = $fieldID;
- $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
- $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace(' ', '', $formattedValue);
+ $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
+ if ($isPublic) {
+ $customFields[$fieldID]['id'] = $fieldID;
+ $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
+ $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace(' ', '', $formattedValue);
+ }
}
}
@@ -1618,15 +1670,15 @@ public function postProcess() {
if ($this->_isPaidEvent) {
// fix amount for each of participants ( for bulk mode )
- $eventAmount = array();
+ $eventAmount = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
//add dataArray in the receipts in ADD and UPDATE condition
- $dataArray = array();
+ $dataArray = [];
if ($this->_action & CRM_Core_Action::ADD) {
- $line = $lineItem[0];
+ $line = isset($lineItem[0]) ? $lineItem[0] : [];
}
elseif ($this->_action & CRM_Core_Action::UPDATE) {
$line = $this->_values['line_items'];
@@ -1644,30 +1696,30 @@ public function postProcess() {
}
}
$this->assign('totalTaxAmount', $totalTaxAmount);
- $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
+ $this->assign('taxTerm', $this->getSalesTaxTerm());
$this->assign('dataArray', $dataArray);
}
if (!empty($additionalParticipantDetails)) {
$params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
}
- $eventAmount[$num] = array(
+ $eventAmount[$num] = [
'label' => preg_replace('//', '', $params['amount_level']),
'amount' => $params['fee_amount'],
- );
+ ];
//as we are using same template for online & offline registration.
//So we have to build amount as array.
$eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
$this->assign('amount', $eventAmount);
}
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_offline_receipt',
'contactId' => $contactID,
'isTest' => !empty($this->_defaultValues['is_test']),
'PDFFilename' => ts('confirmation') . '.pdf',
- );
+ ];
// try to send emails only if email id is present
// and the do-not-email option is not checked for that contact
@@ -1687,7 +1739,7 @@ public function postProcess() {
);
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
- if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
+ if (!empty($taxAmt) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
$sendTemplateParams['isEmailPdf'] = TRUE;
$sendTemplateParams['contributionId'] = $contributionId;
}
@@ -1713,10 +1765,38 @@ public function postProcess() {
$this->_id = $participants[0]->id;
}
+ return $this->getStatusMsg($params, $sent, $updateStatusMsg, $notSent);
+ }
+
+ /**
+ * Set the various IDs relating to custom data types.
+ */
+ public function setCustomDataTypes() {
+ $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
+ $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
+ $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
+ $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
+ $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
+ $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
+ $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
+ }
+
+ /**
+ * Get status message
+ *
+ * @param array $params
+ * @param int $sent
+ * @param string $updateStatusMsg
+ * @param int $notSent
+ *
+ * @return string
+ */
+ protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
+ $statusMsg = '';
if (($this->_action & CRM_Core_Action::UPDATE)) {
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contributorDisplayName]);
if (!empty($params['send_receipt']) && count($sent)) {
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', [1 => $this->_contributorEmail]);
}
if ($updateStatusMsg) {
@@ -1725,46 +1805,22 @@ public function postProcess() {
}
elseif ($this->_action & CRM_Core_Action::ADD) {
if ($this->_single) {
- $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
+ $statusMsg = ts('Event registration for %1 has been added.', [1 => $this->_contributorDisplayName]);
if (!empty($params['send_receipt']) && count($sent)) {
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $this->_contributorEmail]);
}
}
else {
- $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
+ $statusMsg = ts('Total Participant(s) added to event: %1.', [1 => count($this->_contactIds)]);
if (count($notSent) > 0) {
- $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
+ $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', [1 => count($notSent)]);
}
elseif (isset($params['send_receipt'])) {
$statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
}
}
}
- CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
- $session = CRM_Core_Session::singleton();
- $buttonName = $this->controller->getButtonName();
- if ($this->_context == 'standalone') {
- if ($buttonName == $this->getButtonName('upload', 'new')) {
- $urlParams = 'reset=1&action=add&context=standalone';
- if ($this->_mode) {
- $urlParams .= '&mode=' . $this->_mode;
- }
- if ($this->_eID) {
- $urlParams .= '&eid=' . $this->_eID;
- }
- $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
- }
- else {
- $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
- "reset=1&cid={$this->_contactId}&selectedChild=participant"
- ));
- }
- }
- elseif ($buttonName == $this->getButtonName('upload', 'new')) {
- $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
- "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
- ));
- }
+ return $statusMsg;
}
}
diff --git a/CRM/Event/Form/ParticipantFeeSelection.php b/CRM/Event/Form/ParticipantFeeSelection.php
index 368747194285..d79cc636e17d 100644
--- a/CRM/Event/Form/ParticipantFeeSelection.php
+++ b/CRM/Event/Form/ParticipantFeeSelection.php
@@ -1,9 +1,9 @@
assign('lineItemTotal', $total);
}
- $title = ts("Change selections for %1", array(1 => $this->_contributorDisplayName));
+ $title = ts("Change selections for %1", [1 => $this->_contributorDisplayName]);
if ($title) {
CRM_Utils_System::setTitle($title);
}
@@ -123,7 +123,7 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $params = array('id' => $this->_participantId);
+ $params = ['id' => $this->_participantId];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $this->_eventId);
@@ -159,16 +159,15 @@ public function buildQuickForm() {
$this->assign('pendingRefund', array_search('Pending refund', $statuses));
$this->assign('participantStatus', $this->_participantStatus);
- $config = CRM_Core_Config::singleton();
- $this->assign('currencySymbol', $config->defaultCurrencySymbol);
+ $this->assign('currencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
// line items block
- $lineItem = $event = array();
- $params = array('id' => $this->_eventId);
+ $lineItem = $event = [];
+ $params = ['id' => $this->_eventId];
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
- $this->_values = array();
+ $this->_values = [];
CRM_Event_Form_Registration::initEventFee($this, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($this, TRUE);
@@ -181,16 +180,16 @@ public function buildQuickForm() {
$statusOptions = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
$this->add('select', 'status_id', ts('Participant Status'),
- array(
+ [
'' => ts('- select -'),
- ) + $statusOptions,
+ ] + $statusOptions,
TRUE
);
$this->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
- array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
+ ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails['from_email_id']);
@@ -200,26 +199,26 @@ public function buildQuickForm() {
$noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
$this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- );
+ ];
if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_participantId)) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save and Record Payment'),
'subName' => 'new',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Form_ParticipantFeeSelection', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_ParticipantFeeSelection', 'formRule'], $this);
}
/**
@@ -230,7 +229,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
return $errors;
}
@@ -239,12 +238,12 @@ public function postProcess() {
$feeBlock = $this->_values['fee'];
$lineItems = $this->_values['line_items'];
- CRM_Event_BAO_Participant::changeFeeSelections($params, $this->_participantId, $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount, $params['priceSetId']);
+ CRM_Price_BAO_LineItem::changeFeeSelections($params, $this->_participantId, 'participant', $this->_contributionId, $feeBlock, $lineItems);
$this->contributionAmt = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionId, 'total_amount');
// email sending
if (!empty($params['send_receipt'])) {
- $fetchParticipantVals = array('id' => $this->_participantId);
- CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails, CRM_Core_DAO::$_nullArray);
+ $fetchParticipantVals = ['id' => $this->_participantId];
+ CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails);
$participantParams = array_merge($params, $participantDetails[$this->_participantId]);
$mailSent = $this->emailReceipt($participantParams);
}
@@ -252,13 +251,13 @@ public function postProcess() {
// update participant
CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $this->_participantId, 'status_id', $params['status_id']);
if (!empty($params['note'])) {
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_participant',
'note' => $params['note'],
'entity_id' => $this->_participantId,
'contact_id' => $this->_contactId,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Note::add($noteParams);
}
CRM_Core_Session::setStatus(ts("The fee selection has been changed for this participant"), ts('Saved'), 'success');
@@ -279,7 +278,7 @@ public function postProcess() {
*/
public function emailReceipt(&$params) {
$updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', FALSE, FALSE);
- $lineItem = array();
+ $lineItem = [];
if ($updatedLineItem) {
$lineItem[] = $updatedLineItem;
}
@@ -292,8 +291,8 @@ public function emailReceipt(&$params) {
$this->assign('module', 'Event Registration');
//use of the message template below requires variables in different format
- $event = $events = array();
- $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
+ $event = $events = [];
+ $returnProperties = ['fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
//get all event details.
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
@@ -304,7 +303,7 @@ public function emailReceipt(&$params) {
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = CRM_Utils_Array::value('role_id', $params);
if (is_array($participantRoles)) {
- $selectedRoles = array();
+ $selectedRoles = [];
foreach (array_keys($participantRoles) as $roleId) {
$selectedRoles[] = $role[$roleId];
}
@@ -324,10 +323,10 @@ public function emailReceipt(&$params) {
$this->assign('isShowLocation', $event['is_show_location']);
if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $params['event_id'],
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
@@ -366,13 +365,13 @@ public function emailReceipt(&$params) {
$this->assign('contactID', $this->_contactId);
$this->assign('participantID', $this->_participantId);
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_offline_receipt',
'contactId' => $this->_contactId,
'isTest' => FALSE,
'PDFFilename' => ts('confirmation') . '.pdf',
- );
+ ];
// try to send emails only if email id is present
// and the do-not-email option is not checked for that contact
diff --git a/CRM/Event/Form/ParticipantView.php b/CRM/Event/Form/ParticipantView.php
index 922916614248..8b51c854655b 100644
--- a/CRM/Event/Form/ParticipantView.php
+++ b/CRM/Event/Form/ParticipantView.php
@@ -1,9 +1,9 @@
$participantID);
+ $params = ['id' => $participantID];
CRM_Event_BAO_Participant::getValues($params,
$values,
@@ -100,8 +100,25 @@ public function preProcess() {
}
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
+ // CRM-20879: Show 'Transfer or Cancel' option beside 'Change fee selection'
+ // only if logged in user have 'edit event participants' permission and
+ // participant status is not Cancelled or Transferred
+ if (CRM_Core_Permission::check('edit event participants') && !in_array($status, ['Cancelled', 'Transferred'])) {
+ $this->assign('transferOrCancelLink',
+ CRM_Utils_System::url(
+ 'civicrm/event/selfsvcupdate',
+ [
+ 'reset' => 1,
+ 'is_backoffice' => 1,
+ 'pid' => $participantID,
+ 'cs' => CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf'),
+ ]
+ )
+ );
+ }
+
if ($values[$participantID]['is_test']) {
- $values[$participantID]['status'] .= ' (test) ';
+ $values[$participantID]['status'] = CRM_Core_TestEntity::appendTestText($values[$participantID]['status']);
}
// Get Note
@@ -138,19 +155,19 @@ public function preProcess() {
$eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
$eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
$allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']);
- $groupTree = array();
- $finalTree = array();
+ $groupTree = [];
+ $finalTree = [];
foreach ($allRoleIDs as $k => $v) {
- $roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $v, $roleCustomDataTypeID);
- $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL,
+ $roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL, $v, $roleCustomDataTypeID);
+ $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL,
$values[$participantID]['event_id'], $eventNameCustomDataTypeID
);
$eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id');
- $eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID);
+ $eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID);
$groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
$groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree);
- $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', $this, $participantID));
+ $groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID));
foreach ($groupTree as $treeId => $trees) {
$finalTree[$treeId] = $trees;
}
@@ -175,7 +192,7 @@ public function preProcess() {
"action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::check('edit event participants')) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
@@ -190,7 +207,7 @@ public function preProcess() {
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']);
- $participantCount = array();
+ $participantCount = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
@@ -214,7 +231,7 @@ public function preProcess() {
$title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')';
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
- $viewRoles = array();
+ $viewRoles = [];
foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
@@ -237,15 +254,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Form/Registration.php b/CRM/Event/Form/Registration.php
index 05e90604121a..d12d4ed4cd1a 100644
--- a/CRM/Event/Form/Registration.php
+++ b/CRM/Event/Form/Registration.php
@@ -1,9 +1,9 @@
_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
- $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
+ $this->_action = CRM_Utils_Request::retrieve('action', 'Alphanumeric', $this, FALSE, CRM_Core_Action::ADD);
//CRM-4320
$this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
@@ -231,8 +231,6 @@ public function preProcess() {
// check for waitlisting.
$this->_allowWaitlist = $this->get('allowWaitlist');
- $this->_forcePayement = $this->get('forcePayement');
-
//get the additional participant ids.
$this->_additionalParticipantIds = $this->get('additionalParticipantIds');
$config = CRM_Core_Config::singleton();
@@ -250,7 +248,6 @@ public function preProcess() {
// get all the values from the dao object
$this->_values = $this->_fields = array();
- $this->_forcePayement = FALSE;
//retrieve event information
$params = array('id' => $this->_eventId);
@@ -391,17 +388,12 @@ public function preProcess() {
$this->_contributeMode = $this->get('contributeMode');
$this->assign('contributeMode', $this->_contributeMode);
- // setting CMS page title
- CRM_Utils_System::setTitle($this->_values['event']['title']);
- $this->assign('title', $this->_values['event']['title']);
+ $this->setTitle($this->_values['event']['title']);
$this->assign('paidEvent', $this->_values['event']['is_monetary']);
// we do not want to display recently viewed items on Registration pages
$this->assign('displayRecent', FALSE);
- // Registration page values are cleared from session, so can't use normal Printer Friendly view.
- // Use Browser Print instead.
- $this->assign('browserPrint', TRUE);
$isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
$this->assign('isShowLocation', $isShowLocation);
@@ -419,10 +411,7 @@ public function preProcess() {
$this->assign('bltID', $this->_bltID);
$isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
$this->assign('isShowLocation', $isShowLocation);
- //CRM-6907
- $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'],
- $config->defaultCurrency
- );
+ CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values['event']);
//lets allow user to override campaign.
$campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
@@ -484,7 +473,7 @@ public function assignToTemplate() {
$this->assign($v, $params[$v]);
}
}
- elseif (CRM_Utils_Array::value('amount', $params) == 0) {
+ elseif (empty($params['amount'])) {
$this->assign($v, CRM_Utils_Array::value($v, $params));
}
}
@@ -519,9 +508,7 @@ public function assignToTemplate() {
// also assign all participantIDs to the template
// useful in generating confirmation numbers if needed
- $this->assign('participantIDs',
- $this->_participantIDS
- );
+ $this->assign('participantIDs', $this->_participantIDS);
}
/**
@@ -618,9 +605,7 @@ public function buildCustom($id, $name, $viewOnly = FALSE) {
}
if ($addCaptcha && !$viewOnly) {
- $captcha = CRM_Utils_ReCAPTCHA::singleton();
- $captcha->add($this);
- $this->assign('isCaptcha', TRUE);
+ CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
}
}
}
@@ -709,12 +694,12 @@ public static function initEventFee(&$form, $eventID) {
* Handle process after the confirmation of payment by User.
*
* @param int $contactID
- * @param null $contribution
- * @param null $payment
+ * @param \CRM_Contribute_BAO_Contribution $contribution
+ *
+ * @throws \CiviCRM_API3_Exception
*/
- public function confirmPostProcess($contactID = NULL, $contribution = NULL, $payment = NULL) {
+ public function confirmPostProcess($contactID = NULL, $contribution = NULL) {
// add/update contact information
- $fields = array();
unset($this->_params['note']);
//to avoid conflict overwrite $this->_params
@@ -737,6 +722,8 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
// CRM-10032
$this->processFirstParticipant($participant->id);
}
+ $this->_params['participantID'] = $participant->id;
+ $this->set('primaryParticipant', $this->_params);
CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
'civicrm_participant',
@@ -757,19 +744,11 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
}
if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
- $paymentParams = array(
+ $paymentParams = [
'participant_id' => $participant->id,
'contribution_id' => $contribution->id,
- );
- $ids = array();
- $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
- }
-
- //set only primary participant's params for transfer checkout.
- // The concept of contributeMode is deprecated.
- if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
- $this->_params['participantID'] = $participant->id;
- $this->set('primaryParticipant', $this->_params);
+ ];
+ civicrm_api3('ParticipantPayment', 'create', $paymentParams);
}
$this->assign('action', $this->_action);
@@ -791,12 +770,11 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
}
// we should use primary email for
- // 1. free event registration.
- // 2. pay later participant.
- // 3. waiting list participant.
- // 4. require approval participant.
+ // 1. pay later participant.
+ // 2. waiting list participant.
+ // 3. require approval participant.
if (!empty($this->_params['is_pay_later']) ||
- $this->_allowWaitlist || $this->_requireApproval || empty($this->_values['event']['is_monetary'])
+ $this->_allowWaitlist || $this->_requireApproval
) {
$mail = 'email-Primary';
}
@@ -814,6 +792,7 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
* @param int $contactID
*
* @return \CRM_Event_BAO_Participant
+ * @throws \CiviCRM_API3_Exception
*/
public static function addParticipant(&$form, $contactID) {
if (empty($form->_params)) {
@@ -822,23 +801,6 @@ public static function addParticipant(&$form, $contactID) {
$params = $form->_params;
$transaction = new CRM_Core_Transaction();
- $groupName = 'participant_role';
- $query = "
-SELECT v.label as label ,v.value as value
-FROM civicrm_option_value v,
- civicrm_option_group g
-WHERE v.option_group_id = g.id
- AND g.name = %1
- AND v.is_active = 1
- AND g.is_active = 1
-";
- $p = array(1 => array($groupName, 'String'));
-
- $dao = CRM_Core_DAO::executeQuery($query, $p);
- if ($dao->fetch()) {
- $roleID = $dao->value;
- }
-
// handle register date CRM-4320
$registerDate = NULL;
if (!empty($form->_allowConfirmation) && $form->_participantId) {
@@ -859,9 +821,7 @@ public static function addParticipant(&$form, $contactID) {
'status_id' => CRM_Utils_Array::value('participant_status',
$params, 1
),
- 'role_id' => CRM_Utils_Array::value('participant_role_id',
- $params, $roleID
- ),
+ 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: self::getDefaultRoleID(),
'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
'source' => CRM_Utils_String::ellipsify(
isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
@@ -913,6 +873,21 @@ public static function addParticipant(&$form, $contactID) {
return $participant;
}
+ /**
+ * Get the ID of the default (first) participant role
+ *
+ * @return int
+ * @throws \CiviCRM_API3_Exception
+ */
+ private static function getDefaultRoleID() {
+ return (int) civicrm_api3('OptionValue', 'getvalue', [
+ 'return' => "value",
+ 'option_group_id' => "participant_role",
+ 'is_active' => 1,
+ 'options' => ['limit' => 1, 'sort' => "is_default DESC"],
+ ]);
+ }
+
/**
* Calculate the total participant count as per params.
*
@@ -1249,7 +1224,7 @@ public static function resetElementValue($optionFullIds = array(), &$form) {
*
* @param string $elementName
* @param array $optionIds
- * @param CRM_Core_form $form
+ * @param CRM_Core_Form $form
*/
public static function resetSubmittedValue($elementName, $optionIds = array(), &$form) {
if (empty($elementName) ||
@@ -1259,10 +1234,10 @@ public static function resetSubmittedValue($elementName, $optionIds = array(), &
return;
}
foreach (array(
- 'constantValues',
- 'submitValues',
- 'defaultValues',
- ) as $val) {
+ 'constantValues',
+ 'submitValues',
+ 'defaultValues',
+ ) as $val) {
$values = $form->{"_$val"};
if (!is_array($values) || empty($values)) {
continue;
@@ -1536,6 +1511,8 @@ protected function getAmountLevel($params, $discountID) {
* @param array $params
* Form values.
* @param int $contactID
+ *
+ * @throws \CiviCRM_API3_Exception
*/
public function processRegistration($params, $contactID = NULL) {
$session = CRM_Core_Session::singleton();
@@ -1616,7 +1593,7 @@ public function processRegistration($params, $contactID = NULL) {
}
$this->set('value', $value);
- $this->confirmPostProcess($contactID, NULL, NULL);
+ $this->confirmPostProcess($contactID, NULL);
//lets get additional participant id to cancel.
if ($this->_allowConfirmation && is_array($cancelledIds)) {
@@ -1645,66 +1622,79 @@ public function processRegistration($params, $contactID = NULL) {
if ($this->_contributeMode != 'checkout' ||
$this->_contributeMode != 'notify'
) {
- $isTest = FALSE;
- if ($this->_action & CRM_Core_Action::PREVIEW) {
- $isTest = TRUE;
- }
+ $this->sendMails($params, $registerByID, $participantCount);
+ }
+ }
- //handle if no additional participant.
- if (!$registerByID) {
- $registerByID = $this->get('registerByID');
- }
- $primaryContactId = $this->get('primaryContactId');
+ /**
+ * Send Mail to participants.
+ *
+ * @param $params
+ * @param $registerByID
+ * @param array $participantCount
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ private function sendMails($params, $registerByID, array $participantCount) {
+ $isTest = FALSE;
+ if ($this->_action & CRM_Core_Action::PREVIEW) {
+ $isTest = TRUE;
+ }
- //build an array of custom profile and assigning it to template.
- $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
- $primaryContactId, $isTest, TRUE
- );
+ //handle if no additional participant.
+ if (!$registerByID) {
+ $registerByID = $this->get('registerByID');
+ }
+ $primaryContactId = $this->get('primaryContactId');
- //lets carry all participant params w/ values.
- foreach ($additionalIDs as $participantID => $contactId) {
- $participantNum = NULL;
- if ($participantID == $registerByID) {
- $participantNum = 0;
- }
- else {
- if ($participantNum = array_search('participant', $participantCount)) {
- unset($participantCount[$participantNum]);
- }
- }
+ //build an array of custom profile and assigning it to template.
+ $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
+ $primaryContactId, $isTest, TRUE
+ );
- if ($participantNum === NULL) {
- break;
+ //lets carry all participant params w/ values.
+ foreach ($additionalIDs as $participantID => $contactId) {
+ $participantNum = NULL;
+ if ($participantID == $registerByID) {
+ $participantNum = 0;
+ }
+ else {
+ if ($participantNum = array_search('participant', $participantCount)) {
+ unset($participantCount[$participantNum]);
}
+ }
- //carry the participant submitted values.
- $this->_values['params'][$participantID] = $params[$participantNum];
+ if ($participantNum === NULL) {
+ break;
}
- //lets send mails to all with meanigful text, CRM-4320.
- $this->assign('isOnWaitlist', $this->_allowWaitlist);
- $this->assign('isRequireApproval', $this->_requireApproval);
+ //carry the participant submitted values.
+ $this->_values['params'][$participantID] = $params[$participantNum];
+ }
- foreach ($additionalIDs as $participantID => $contactId) {
- if ($participantID == $registerByID) {
- //set as Primary Participant
- $this->assign('isPrimary', 1);
+ //lets send mails to all with meanigful text, CRM-4320.
+ $this->assign('isOnWaitlist', $this->_allowWaitlist);
+ $this->assign('isRequireApproval', $this->_requireApproval);
- $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
+ foreach ($additionalIDs as $participantID => $contactId) {
+ if ($participantID == $registerByID) {
+ //set as Primary Participant
+ $this->assign('isPrimary', 1);
- if (count($customProfile)) {
- $this->assign('customProfile', $customProfile);
- $this->set('customProfile', $customProfile);
- }
- }
- else {
- $this->assign('isPrimary', 0);
- $this->assign('customProfile', NULL);
- }
+ $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
- //send Confirmation mail to Primary & additional Participants if exists
- CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
+ if (count($customProfile)) {
+ $this->assign('customProfile', $customProfile);
+ $this->set('customProfile', $customProfile);
+ }
}
+ else {
+ $this->assign('isPrimary', 0);
+ $this->assign('customProfile', NULL);
+ }
+
+ //send Confirmation mail to Primary & additional Participants if exists
+ CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
}
}
diff --git a/CRM/Event/Form/Registration/AdditionalParticipant.php b/CRM/Event/Form/Registration/AdditionalParticipant.php
index 728cfb0043c7..b09b13ff3b80 100644
--- a/CRM/Event/Form/Registration/AdditionalParticipant.php
+++ b/CRM/Event/Form/Registration/AdditionalParticipant.php
@@ -1,9 +1,9 @@
assign('formId', $participantNo);
- $this->_params = array();
+ $this->_params = [];
$this->_params = $this->get('params');
$participantTot = $this->_params[0]['additional_participants'] + 1;
@@ -67,7 +68,7 @@ public function preProcess() {
if ($skipCount) {
$this->assign('skipCount', $skipCount);
}
- CRM_Utils_System::setTitle(ts('Register Participant %1 of %2', array(1 => $participantCnt, 2 => $participantTot)));
+ CRM_Utils_System::setTitle(ts('Register Participant %1 of %2', [1 => $participantCnt, 2 => $participantTot]));
//CRM-4320, hack to check last participant.
$this->_lastParticipant = FALSE;
@@ -85,7 +86,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = $unsetSubmittedOptions = array();
+ $defaults = $unsetSubmittedOptions = [];
$discountId = NULL;
//fix for CRM-3088, default value for discount set.
if (!empty($this->_values['discount'])) {
@@ -102,7 +103,7 @@ public function setDefaultValues() {
continue;
}
- $optionsFull = CRM_Utils_Array::value('option_full_ids', $val, array());
+ $optionsFull = CRM_Utils_Array::value('option_full_ids', $val, []);
foreach ($val['options'] as $keys => $values) {
if ($values['is_default'] && !in_array($keys, $optionsFull)) {
if ($val['html_type'] == 'CheckBox') {
@@ -179,37 +180,11 @@ public function buildQuickForm() {
if ($this->_values['event']['is_monetary']) {
CRM_Event_Form_Registration_Register::buildAmount($this);
}
- $first_name = $last_name = NULL;
- $pre = $post = array();
- foreach (array(
- 'pre',
- 'post',
- ) as $keys) {
- if (isset($this->_values['additional_custom_' . $keys . '_id'])) {
- $this->buildCustom($this->_values['additional_custom_' . $keys . '_id'], 'additionalCustom' . ucfirst($keys), TRUE);
- $$keys = CRM_Core_BAO_UFGroup::getFields($this->_values['additional_custom_' . $keys . '_id']);
- }
- foreach (array(
- 'first_name',
- 'last_name',
- ) as $name) {
- if (array_key_exists($name, $$keys) &&
- CRM_Utils_Array::value('is_required', CRM_Utils_Array::value($name, $$keys))
- ) {
- $$name = 1;
- }
- }
- }
-
- $required = ($button == 'skip' ||
- $this->_values['event']['allow_same_participant_emails'] == 1 &&
- ($first_name && $last_name)
- ) ? FALSE : TRUE;
//add buttons
$js = NULL;
if ($this->isLastParticipant(TRUE) && empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $this->submitOnce = TRUE;
}
//handle case where user might sart with waiting by group
@@ -262,23 +237,23 @@ public function buildQuickForm() {
$this->_allowWaitlist = FALSE;
$this->set('allowWaitlist', $this->_allowWaitlist);
if ($this->_requireApproval) {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
}
else {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed).", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed).", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
}
}
else {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
$allowToProceed = FALSE;
}
CRM_Core_Session::setStatus($statusMessage, ts('Registration Error'), 'error');
@@ -344,40 +319,37 @@ public function buildQuickForm() {
$this->assign('statusMessage', $statusMessage);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'back',
'name' => ts('Go Back'),
'spacing' => '  ',
- ),
- );
+ ],
+ ];
//CRM-4320
if ($allowToProceed) {
- $buttons = array_merge($buttons, array(
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- 'js' => $js,
- ),
- )
- );
+ $buttons = array_merge($buttons, [
+ [
+ 'type' => 'upload',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
if ($includeSkipButton) {
- $buttons = array_merge($buttons, array(
- array(
- 'type' => 'next',
- 'name' => ts('Skip Participant'),
- 'subName' => 'skip',
- 'icon' => 'fa-fast-forward',
- ),
- )
- );
+ $buttons = array_merge($buttons, [
+ [
+ 'type' => 'next',
+ 'name' => ts('Skip Participant'),
+ 'subName' => 'skip',
+ 'icon' => 'fa-fast-forward',
+ ],
+ ]);
}
}
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Form_Registration_AdditionalParticipant', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_AdditionalParticipant', 'formRule'], $this);
$this->unsavedChangesWarn = TRUE;
}
@@ -395,7 +367,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
//get the button name.
$button = substr($self->controller->getButtonName(), -4);
@@ -430,8 +402,8 @@ public static function formRule($fields, $files, $self) {
if ($key != $addParticipantNum) {
if (!$self->_values['event']['allow_same_participant_emails']) {
//collect all email fields
- $existingEmails = array();
- $additionalParticipantEmails = array();
+ $existingEmails = [];
+ $additionalParticipantEmails = [];
if (is_array($value)) {
foreach ($value as $key => $val) {
if (substr($key, 0, 6) == 'email-' && $val) {
@@ -474,7 +446,7 @@ public static function formRule($fields, $files, $self) {
//validate price field params.
$priceSetErrors = self::validatePriceSet($self, $allParticipantParams);
- $errors = array_merge($errors, CRM_Utils_Array::value($addParticipantNum, $priceSetErrors, array()));
+ $errors = array_merge($errors, CRM_Utils_Array::value($addParticipantNum, $priceSetErrors, []));
if (!$self->_allowConfirmation &&
is_numeric($self->_availableRegistrations)
@@ -492,10 +464,10 @@ public static function formRule($fields, $files, $self) {
if (!$self->_allowConfirmation && empty($self->_values['event']['has_waitlist']) &&
$totalParticipants > $self->_availableRegistrations
) {
- $errors['_qf_default'] = ts('Sorry, it looks like this event only has %2 spaces available, and you are trying to register %1 participants. Please change your selections accordingly.', array(
- 1 => $totalParticipants,
- 2 => $self->_availableRegistrations,
- ));
+ $errors['_qf_default'] = ts('Sorry, it looks like this event only has %2 spaces available, and you are trying to register %1 participants. Please change your selections accordingly.', [
+ 1 => $totalParticipants,
+ 2 => $self->_availableRegistrations,
+ ]);
}
}
}
@@ -550,11 +522,10 @@ public function validatePaymentValues($self, $fields) {
$validatePayement = FALSE;
if (!empty($fields['priceSetId'])) {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
if ($fields['amount'] > 0) {
$validatePayement = TRUE;
- // $self->_forcePayement = true;
// return false;
}
}
@@ -568,7 +539,7 @@ public function validatePaymentValues($self, $fields) {
return TRUE;
}
- $errors = array();
+ $errors = [];
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
@@ -583,7 +554,7 @@ public function validatePaymentValues($self, $fields) {
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $self->_params[0])) {
- $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
+ $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
if ($customizedValue == $greetingType && empty($self->_params[0][$greeting . '_custom'])) {
return FALSE;
}
@@ -613,6 +584,9 @@ public function postProcess() {
$params['contact_id'] = CRM_Event_Form_Registration_Register::getRegistrationContactID($params, $this, TRUE);
}
+ if (!empty($params['image_URL'])) {
+ CRM_Contact_BAO_Contact::processImageParams($params);
+ }
//carry campaign to partcipants.
if (array_key_exists('participant_campaign_id', $params)) {
$params['campaign_id'] = $params['participant_campaign_id'];
@@ -685,7 +659,7 @@ public function postProcess() {
$params['amount'] = $this->_values['fee'][$params['amount']]['value'];
}
else {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
//build line item array..
@@ -730,13 +704,14 @@ public function postProcess() {
$participantNo = count($this->_params);
if ($button != 'skip') {
- $statusMsg = ts('Registration information for participant %1 has been saved.', array(1 => $participantNo));
+ $statusMsg = ts('Registration information for participant %1 has been saved.', [1 => $participantNo]);
CRM_Core_Session::setStatus($statusMsg, ts('Registration Saved'), 'success');
}
// Check whether to process the registration now, calling processRegistration()
if (
- !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
+ // CRM-11182 - Optional confirmation screen
+ !$this->_values['event']['is_confirm_enabled']
&& !$this->_values['event']['is_monetary']
&& CRM_Utils_Array::value('additional_participants', $this->_params[0])
&& $this->isLastParticipant()
@@ -751,12 +726,12 @@ public function postProcess() {
* @return array
*/
public static function &getPages($additionalParticipant) {
- $details = array();
+ $details = [];
for ($i = 1; $i <= $additionalParticipant; $i++) {
- $details["Participant_{$i}"] = array(
+ $details["Participant_{$i}"] = [
'className' => 'CRM_Event_Form_Registration_AdditionalParticipant',
'title' => "Register Additional Participant {$i}",
- );
+ ];
}
return $details;
}
diff --git a/CRM/Event/Form/Registration/Confirm.php b/CRM/Event/Form/Registration/Confirm.php
index 7b8c7d1ffb7b..bf4542866be6 100644
--- a/CRM/Event/Form/Registration/Confirm.php
+++ b/CRM/Event/Form/Registration/Confirm.php
@@ -1,9 +1,9 @@
assign('hookDiscount', $this->_params[0]['discount']);
}
- // The concept of contributeMode is deprecated.
- if ($this->_contributeMode == 'express') {
- $params = array();
- // rfp == redirect from paypal
- // rfp is probably not required - the getPreApprovalDetails should deal with any payment-processor specific 'stuff'
- $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
- CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
- );
-
- //we lost rfp in case of additional participant. So set it explicitly.
- if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
- if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
- $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
- $params = array_merge($this->_params, $preApprovalParams);
- }
- CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, FALSE);
-
- // set a few other parameters that are not really specific to this method because we don't know what
- // will break if we change this.
- $params['amount'] = $this->_params[0]['amount'];
- if (!empty($this->_params[0]['discount'])) {
- $params['discount'] = $this->_params[0]['discount'];
- $params['discountAmount'] = $this->_params[0]['discountAmount'];
- $params['discountMessage'] = $this->_params[0]['discountMessage'];
- }
-
- $params['amount_level'] = $this->_params[0]['amount_level'];
- $params['currencyID'] = $this->_params[0]['currencyID'];
-
- // also merge all the other values from the profile fields
- $values = $this->controller->exportValues('Register');
- $skipFields = array(
- 'amount',
- "street_address-{$this->_bltID}",
- "city-{$this->_bltID}",
- "state_province_id-{$this->_bltID}",
- "postal_code-{$this->_bltID}",
- "country_id-{$this->_bltID}",
- );
-
- foreach ($values as $name => $value) {
- // skip amount field
- if (!in_array($name, $skipFields)) {
- $params[$name] = $value;
- }
- if (substr($name, 0, 6) == 'price_') {
- $params[$name] = $this->_params[0][$name];
- }
- }
- $this->set('getExpressCheckoutDetails', $params);
- }
- $this->_params[0] = array_merge($this->_params[0], $params);
- $this->_params[0]['is_primary'] = 1;
- }
- else {
+ if (!$this->preProcessExpress()) {
//process only primary participant params.
$registerParams = $this->_params[0];
- if (isset($registerParams["billing_state_province_id-{$this->_bltID}"])
- && $registerParams["billing_state_province_id-{$this->_bltID}"]
- ) {
- $registerParams["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($registerParams["billing_state_province_id-{$this->_bltID}"]);
- }
+ $registerParams = $this->prepareParamsForPaymentProcessor($registerParams);
- if (isset($registerParams["billing_country_id-{$this->_bltID}"]) && $registerParams["billing_country_id-{$this->_bltID}"]) {
- $registerParams["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($registerParams["billing_country_id-{$this->_bltID}"]);
- }
- if (isset($registerParams['credit_card_exp_date'])) {
- $registerParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($registerParams);
- $registerParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($registerParams);
- }
if ($this->_values['event']['is_monetary']) {
- $registerParams['ip_address'] = CRM_Utils_System::ipAddress();
$registerParams['currencyID'] = $this->_params[0]['currencyID'];
}
//assign back primary participant params.
@@ -170,6 +117,7 @@ public function preProcess() {
CRM_Utils_System::setTitle($this->_values['event']['confirm_title']);
}
+ // Personal campaign page
if ($this->_pcpId) {
$params = CRM_Contribute_Form_Contribution_Confirm::processPcp($this, $this->_params[0]);
$this->_params[0] = $params;
@@ -178,6 +126,69 @@ public function preProcess() {
$this->set('params', $this->_params);
}
+ /**
+ * Pre process function for Paypal Express confirm.
+ * @todo this is just a step in refactor as payment processor specific code does not belong in generic forms
+ *
+ * @return bool
+ * @throws \CRM_Core_Exception
+ */
+ private function preProcessExpress() {
+ if ($this->_contributeMode !== 'express') {
+ return FALSE;
+ }
+ $params = [];
+ // rfp == redirect from paypal
+ // @fixme rfp is probably not required - the getPreApprovalDetails should deal with any payment-processor specific 'stuff'
+ $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
+
+ //we lost rfp in case of additional participant. So set it explicitly.
+ if ($rfp || CRM_Utils_Array::value('additional_participants', $this->_params[0], FALSE)) {
+ if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
+ $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
+ $params = array_merge($this->_params, $preApprovalParams);
+ }
+ CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, FALSE);
+
+ // set a few other parameters that are not really specific to this method because we don't know what
+ // will break if we change this.
+ $params['amount'] = $this->_params[0]['amount'];
+ if (!empty($this->_params[0]['discount'])) {
+ $params['discount'] = $this->_params[0]['discount'];
+ $params['discountAmount'] = $this->_params[0]['discountAmount'];
+ $params['discountMessage'] = $this->_params[0]['discountMessage'];
+ }
+
+ $params['amount_level'] = $this->_params[0]['amount_level'];
+ $params['currencyID'] = $this->_params[0]['currencyID'];
+
+ // also merge all the other values from the profile fields
+ $values = $this->controller->exportValues('Register');
+ $skipFields = [
+ 'amount',
+ "street_address-{$this->_bltID}",
+ "city-{$this->_bltID}",
+ "state_province_id-{$this->_bltID}",
+ "postal_code-{$this->_bltID}",
+ "country_id-{$this->_bltID}",
+ ];
+
+ foreach ($values as $name => $value) {
+ // skip amount field
+ if (!in_array($name, $skipFields)) {
+ $params[$name] = $value;
+ }
+ if (substr($name, 0, 6) == 'price_') {
+ $params[$name] = $this->_params[0][$name];
+ }
+ }
+ $this->set('getExpressCheckoutDetails', $params);
+ }
+ $this->_params[0] = array_merge($this->_params[0], $params);
+ $this->_params[0]['is_primary'] = 1;
+ return TRUE;
+ }
+
/**
* Overwrite action, since we are only showing elements in frozen mode no help display needed.
*
@@ -199,9 +210,10 @@ public function buildQuickForm() {
$this->assignToTemplate();
if ($this->_values['event']['is_monetary'] &&
- ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0)
+ ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0) &&
+ !$this->_requireApproval
) {
- $this->_amount = array();
+ $this->_amount = [];
$taxAmount = 0;
foreach ($this->_params as $k => $v) {
@@ -212,10 +224,11 @@ public function buildQuickForm() {
//display tax amount on confirmation page
$taxAmount += $v['tax_amount'];
if (is_array($v)) {
- foreach (array(
- 'first_name',
- 'last_name',
- ) as $name) {
+ $this->cleanMoneyFields($v);
+ foreach ([
+ 'first_name',
+ 'last_name',
+ ] as $name) {
if (isset($v['billing_' . $name]) &&
!isset($v[$name])
) {
@@ -256,12 +269,9 @@ public function buildQuickForm() {
}
}
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- if ($invoicing) {
+ if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
$this->assign('totalTaxAmount', $taxAmount);
- $this->assign('taxTerm', $taxTerm);
+ $this->assign('taxTerm', CRM_Invoicing_Utils::getTaxTerm());
$this->assign('individual', $individual);
$this->set('individual', $individual);
}
@@ -274,26 +284,17 @@ public function buildQuickForm() {
}
if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
- $lineItemForTemplate = array();
- $getTaxDetails = FALSE;
+ $lineItemForTemplate = [];
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
if (!empty($value)) {
$lineItemForTemplate[$key] = $value;
}
- if ($invoicing) {
- foreach ($value as $v) {
- if (isset($v['tax_rate'])) {
- $getTaxDetails = TRUE;
- }
- }
- }
}
}
if (!empty($lineItemForTemplate)) {
- $this->assign('lineItem', $lineItemForTemplate);
+ $this->assignLineItemsToTemplate($lineItemForTemplate);
}
- $this->assign('getTaxDetails', $getTaxDetails);
}
//display additional participants profile.
@@ -303,22 +304,20 @@ public function buildQuickForm() {
$this->assign('isAmountzero', ($this->_totalAmount <= 0) ? TRUE : FALSE);
$contribButton = ts('Continue');
- $this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Go Back'),
- ),
- array(
- 'type' => 'next',
- 'name' => $contribButton,
- 'isDefault' => TRUE,
- 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
- ),
- )
- );
-
- $defaults = array();
- $fields = array();
+ $this->addButtons([
+ [
+ 'type' => 'back',
+ 'name' => ts('Go Back'),
+ ],
+ [
+ 'type' => 'next',
+ 'name' => $contribButton,
+ 'isDefault' => TRUE,
+ ],
+ ]);
+
+ $defaults = [];
+ $fields = [];
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
@@ -354,7 +353,7 @@ public function buildQuickForm() {
// Assign Participant Count to Lineitem Table
$this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
- $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_Confirm', 'formRule'], $this);
}
/**
@@ -367,7 +366,7 @@ public function buildQuickForm() {
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
$eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
if ($eventFull && empty($self->_allowConfirmation)) {
if (empty($self->_allowWaitlist)) {
@@ -398,6 +397,8 @@ public function postProcess() {
$now = date('YmdHis');
$this->_params = $this->get('params');
+ $this->cleanMoneyFields($this->_params);
+
if (!empty($this->_params[0]['contact_id'])) {
// unclear when this would be set & whether it could be checked in getContactID.
// perhaps it relates to when cid is in the url
@@ -429,8 +430,8 @@ public function postProcess() {
if ($this->_values['event']['is_monetary']) {
$this->set('finalAmount', $this->_amount);
}
- $participantCount = array();
- $taxAmount = $totalTaxAmount = 0;
+ $participantCount = [];
+ $totalTaxAmount = 0;
//unset the skip participant from params.
//build the $participantCount array.
@@ -444,7 +445,7 @@ public function postProcess() {
$participantCount[$participantNum] = 'participant';
}
$totalTaxAmount += CRM_Utils_Array::value('tax_amount', $record, 0);
- if (CRM_Utils_Array::value('is_primary', $record)) {
+ if (!empty($record['is_primary'])) {
$taxAmount = &$params[$participantNum]['tax_amount'];
}
//lets get additional participant id to cancel.
@@ -459,8 +460,7 @@ public function postProcess() {
$payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
$paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
- $this->participantIDS = array();
- $fields = array();
+ $fields = [];
foreach ($params as $key => $value) {
CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
//unset the billing parameters if it is pay later mode
@@ -473,7 +473,7 @@ public function postProcess() {
|| (!empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater)
|| empty($value['is_primary'])
) {
- $billingFields = array(
+ $billingFields = [
"email-{$this->_bltID}",
'billing_first_name',
'billing_middle_name',
@@ -486,7 +486,7 @@ public function postProcess() {
"billing_country-{$this->_bltID}",
"billing_country_id-{$this->_bltID}",
"address_name-{$this->_bltID}",
- );
+ ];
foreach ($billingFields as $field) {
unset($value[$field]);
}
@@ -514,8 +514,7 @@ public function postProcess() {
// transactions etc
// for things like tell a friend
if (!$this->getContactID() && !empty($value['is_primary'])) {
- $session = CRM_Core_Session::singleton();
- $session->set('transaction.userID', $contactID);
+ CRM_Core_Session::singleton()->set('transaction.userID', $contactID);
}
$value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
@@ -534,13 +533,12 @@ public function postProcess() {
$value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
}
- //there might be case user seleted pay later and
+ //there might be case user selected pay later and
//now becomes part of run time waiting list.
$value['is_pay_later'] = FALSE;
}
-
- // required only if paid event
- if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
+ elseif ($this->_values['event']['is_monetary']) {
+ // required only if paid event
if (is_array($this->_paymentProcessor)) {
$payment = $this->_paymentProcessor['object'];
}
@@ -654,8 +652,7 @@ public function postProcess() {
$registerDate = CRM_Utils_Array::value('participant_register_date', $params);
}
elseif (!empty($params['participant_register_date']) &&
- is_array($params['participant_register_date']) &&
- !empty($params['participant_register_date'])
+ is_array($params['participant_register_date'])
) {
$registerDate = CRM_Utils_Date::format($params['participant_register_date']);
}
@@ -664,7 +661,7 @@ public function postProcess() {
}
$this->assign('register_date', $registerDate);
- $this->confirmPostProcess($contactID, $contribution, $payment);
+ $this->confirmPostProcess($contactID, $contribution);
}
//handle if no additional participant.
@@ -685,14 +682,12 @@ public function postProcess() {
if ($this->_allowConfirmation &&
!empty($this->_additionalParticipantIds)
) {
- $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
+ $allParticipantIds = array_merge([$registerByID], $this->_additionalParticipantIds);
}
$entityTable = 'civicrm_participant';
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
- $dataArray = array();
+ $dataArray = [];
foreach ($this->_lineItem as $key => $value) {
if ($value == 'skip') {
continue;
@@ -705,7 +700,7 @@ public function postProcess() {
$lineItem[$this->_priceSetId] = $value;
CRM_Price_BAO_LineItem::processPriceSet($entityId, $lineItem, $contribution, $entityTable);
}
- if ($invoicing) {
+ if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
foreach ($value as $line) {
if (isset($line['tax_amount']) && isset($line['tax_rate'])) {
$totalTaxAmount = $line['tax_amount'] + $totalTaxAmount;
@@ -719,10 +714,8 @@ public function postProcess() {
}
}
}
- if ($invoicing) {
- $this->assign('dataArray', $dataArray);
- $this->assign('totalTaxAmount', $totalTaxAmount);
- }
+ $this->assign('dataArray', $dataArray);
+ $this->assign('totalTaxAmount', $totalTaxAmount);
}
//update status and send mail to cancelled additional participants, CRM-4320
@@ -738,6 +731,15 @@ public function postProcess() {
$isTest = TRUE;
}
+ $primaryParticipant = $this->get('primaryParticipant');
+
+ if (empty($primaryParticipant['participantID'])) {
+ CRM_Core_Error::deprecatedFunctionWarning('This line is not logically reachable.');
+ $primaryParticipant['participantID'] = $registerByID;
+ }
+ //otherwise send mail Confirmation/Receipt
+ $primaryContactId = $this->get('primaryContactId');
+
// for Transfer checkout.
// The concept of contributeMode is deprecated.
if (($this->_contributeMode == 'checkout' ||
@@ -747,12 +749,6 @@ public function postProcess() {
$this->_totalAmount > 0
) {
- $primaryParticipant = $this->get('primaryParticipant');
-
- if (empty($primaryParticipant['participantID'])) {
- $primaryParticipant['participantID'] = $registerByID;
- }
-
//build an array of custom profile and assigning it to template
$customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
if (count($customProfile)) {
@@ -774,7 +770,6 @@ public function postProcess() {
//lets carry all participant params w/ values.
foreach ($additionalIDs as $participantID => $contactId) {
- $participantNum = NULL;
$participantNum = $participantID;
if ($participantID == $registerByID) {
// This is the is primary participant.
@@ -786,13 +781,13 @@ public function postProcess() {
if ($participantNum === NULL) {
break;
}
- //unset current particpant so we don't check them again
+ //unset current participant so we don't check them again
unset($copyParticipantCountLines[$participantNum]);
}
}
// get values of line items
if ($this->_amount) {
- $amount = array();
+ $amount = [];
$amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
$amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
$params[$participantNum]['amounts'] = $amount;
@@ -800,7 +795,7 @@ public function postProcess() {
if (!empty($this->_lineItem)) {
$lineItems = $this->_lineItem;
- $lineItem = array();
+ $lineItem = [];
if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
$lineItem[] = $lineItemValue;
}
@@ -814,12 +809,11 @@ public function postProcess() {
}
//get event custom field information
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $this->_eventId, 0, $this->_values['event']['event_type_id']);
$primaryParticipant['eventCustomFields'] = $groupTree;
// call postprocess hook before leaving
$this->postProcessHook();
- // this does not return
$this->processPayment($payment, $primaryParticipant);
}
@@ -829,22 +823,20 @@ public function postProcess() {
}
}
else {
- //otherwise send mail Confirmation/Receipt
- $primaryContactId = $this->get('primaryContactId');
//build an array of cId/pId of participants
$additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID,
NULL, $primaryContactId, $isTest,
TRUE
);
- //lets send mails to all with meaningful text, CRM-4320.
+ //let's send mails to all with meaningful text, CRM-4320.
$this->assign('isOnWaitlist', $this->_allowWaitlist);
$this->assign('isRequireApproval', $this->_requireApproval);
//need to copy, since we are unsetting on the way.
$copyParticipantCount = $participantCount;
- //lets carry all paticipant params w/ values.
+ //let's carry all participant params w/ values.
foreach ($additionalIDs as $participantID => $contactId) {
$participantNum = NULL;
if ($participantID == $registerByID) {
@@ -883,8 +875,8 @@ public function postProcess() {
unset($participantCount[$participantNum]);
}
// Change $this->_values['participant'] to include additional participant values
- $ids = $participantValues = array();
- $participantParams = array('id' => $participantID);
+ $ids = $participantValues = [];
+ $participantParams = ['id' => $participantID];
CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
$this->_values['participant'] = $participantValues[$participantID];
@@ -892,7 +884,7 @@ public function postProcess() {
$this->assign('customProfile', NULL);
//Additional Participant should get only it's payment information
if (!empty($this->_amount)) {
- $amount = array();
+ $amount = [];
$params = $this->get('params');
$amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
$amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
@@ -900,17 +892,17 @@ public function postProcess() {
}
if ($this->_lineItem) {
$lineItems = $this->_lineItem;
- $lineItem = array();
+ $lineItem = [];
if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
$lineItem[] = $lineItemValue;
}
- if ($invoicing) {
+ if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
$individual = $this->get('individual');
$dataArray[key($dataArray)] = $individual[$participantNum]['totalTaxAmt'];
$this->assign('dataArray', $dataArray);
$this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
$this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
- $this->assign('individual', array($individual[$participantNum]));
+ $this->assign('individual', [$individual[$participantNum]]);
}
$this->assign('lineItem', $lineItem);
}
@@ -923,8 +915,6 @@ public function postProcess() {
$this->_values['params']['isRequireApproval'] = $this->_requireApproval;
//send mail to primary as well as additional participants.
- $this->assign('contactID', $contactId);
- $this->assign('participantID', $participantID);
CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
}
}
@@ -939,8 +929,12 @@ public function postProcess() {
* @param int $contactID
* @param bool $pending
* @param bool $isAdditionalAmount
+ * @param array $paymentProcessor
*
* @return \CRM_Contribute_BAO_Contribution
+ *
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public static function processContribution(
&$form, $params, $result, $contactID,
@@ -963,7 +957,7 @@ public static function processContribution(
// CRM-20264: fetch CC type ID and number (last 4 digit) and assign it back to $params
CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
- $contribParams = array(
+ $contribParams = [
'contact_id' => $contactID,
'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
'receive_date' => $now,
@@ -977,7 +971,7 @@ public static function processContribution(
'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
'card_type_id' => CRM_Utils_Array::value('card_type_id', $params),
'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $params),
- );
+ ];
if ($paymentProcessor) {
$contribParams['payment_instrument_id'] = $paymentProcessor['payment_instrument_id'];
@@ -985,12 +979,11 @@ public static function processContribution(
}
if (!$pending && $result) {
- $contribParams += array(
+ $contribParams += [
'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
- 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
'trxn_id' => $result['trxn_id'],
'receipt_date' => $receiptDate,
- );
+ ];
}
$allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
@@ -1004,22 +997,15 @@ public static function processContribution(
$contribParams['is_test'] = 1;
}
- $contribID = NULL;
if (!empty($contribParams['invoice_id'])) {
- $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
+ $contribParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
$contribParams['invoice_id'],
'id',
'invoice_id'
);
}
- $ids = array();
- if ($contribID) {
- $ids['contribution'] = $contribID;
- $contribParams['id'] = $contribID;
- }
-
- if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
+ if (Civi::settings()->get('deferred_revenue_enabled')) {
$eventStartDate = CRM_Utils_Array::value(
'start_date',
CRM_Utils_Array::value(
@@ -1039,8 +1025,9 @@ public static function processContribution(
}
$contribParams['skipLineItem'] = 1;
+ $contribParams['skipCleanMoney'] = 1;
// create contribution record
- $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
+ $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
// CRM-11124
CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params));
@@ -1078,7 +1065,7 @@ public static function fixLocationFields(&$params, &$fields, &$form) {
// the billing fields (if they are set)
if (is_array($fields)) {
if (!array_key_exists('first_name', $fields)) {
- $nameFields = array('first_name', 'middle_name', 'last_name');
+ $nameFields = ['first_name', 'middle_name', 'last_name'];
foreach ($nameFields as $name) {
$fields[$name] = 1;
if (array_key_exists("billing_$name", $params)) {
@@ -1124,7 +1111,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
//particular uf group
// get the add to groups
- $addToGroups = array();
+ $addToGroups = [];
if (!empty($form->_fields)) {
foreach ($form->_fields as $key => $value) {
@@ -1196,26 +1183,28 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
}
//get email primary first if exist
- $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
- if (!$subscribtionEmail['email']) {
- $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
+ $subscriptionEmail = ['email' => CRM_Utils_Array::value('email-Primary', $params)];
+ if (!$subscriptionEmail['email']) {
+ $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
}
// subscribing contact to groups
- if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) {
- CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID);
+ if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
+ CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
}
return $contactID;
}
/**
- * Assign Profiles.
+ * Assign Profiles to the template.
*
- * @param CRM_Core_Form $form
+ * @param CRM_Event_Form_Registration_Confirm $form
+ *
+ * @throws \Exception
*/
- public static function assignProfiles(&$form) {
+ public static function assignProfiles($form) {
$participantParams = $form->_params;
- $formattedValues = $profileFields = array();
+ $formattedValues = $profileFields = [];
$count = 1;
foreach ($participantParams as $participantNum => $participantValue) {
if ($participantNum) {
@@ -1226,10 +1215,10 @@ public static function assignProfiles(&$form) {
$prefix1 = '';
$prefix2 = '';
}
- if ($participantValue != 'skip') {
+ if ($participantValue !== 'skip') {
//get the customPre profile info
if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
- $values = $groupName = array();
+ $values = $groupName = [];
CRM_Event_BAO_Event::displayProfile($participantValue,
$form->_values[$prefix2 . 'custom_pre_id'],
$groupName,
@@ -1244,9 +1233,9 @@ public static function assignProfiles(&$form) {
}
//get the customPost profile info
if (!empty($form->_values[$prefix2 . 'custom_post_id'])) {
- $values = $groupName = array();
+ $values = $groupName = [];
foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) {
- $val = array();
+ $val = [];
CRM_Event_BAO_Event::displayProfile($participantValue,
$gids,
$group,
@@ -1296,13 +1285,14 @@ public static function testSubmit($params) {
$_REQUEST['id'] = $form->_eventId = $params['id'];
$form->controller = new CRM_Event_Controller_Registration();
$form->_params = $params['params'];
- $form->_amount = $form->_totalAmount = CRM_Utils_Array::value('totalAmount', $params);
+ // This happens in buildQuickForm so emulate here.
+ $form->_amount = $form->_totalAmount = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('totalAmount', $params));
$form->set('params', $params['params']);
- $form->_values['custom_pre_id'] = array();
- $form->_values['custom_post_id'] = array();
+ $form->_values['custom_pre_id'] = CRM_Utils_Array::value('custom_pre_id', $params);
+ $form->_values['custom_post_id'] = CRM_Utils_Array::value('custom_post_id', $params);
$form->_values['event'] = CRM_Utils_Array::value('event', $params);
$form->_contributeMode = $params['contributeMode'];
- $eventParams = array('id' => $params['id']);
+ $eventParams = ['id' => $params['id']];
CRM_Event_BAO_Event::retrieve($eventParams, $form->_values['event']);
$form->set('registerByID', $params['registerByID']);
if (!empty($params['paymentProcessorObj'])) {
@@ -1314,7 +1304,7 @@ public static function testSubmit($params) {
/**
* Process the payment, redirecting back to the page on error.
*
- * @param $payment
+ * @param \CRM_Core_Payment $payment
* @param $value
*
* @return array
@@ -1322,14 +1312,29 @@ public static function testSubmit($params) {
private function processPayment($payment, $value) {
try {
$result = $payment->doPayment($value, 'event');
- return array($result, $value);
+ return [$result, $value];
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
Civi::log()->error('Payment processor exception: ' . $e->getMessage());
CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
}
- return array();
+ return [];
+ }
+
+ /**
+ * Clean money fields from the form.
+ *
+ * @param array $params
+ */
+ protected function cleanMoneyFields(&$params) {
+ foreach ($this->submittableMoneyFields as $moneyField) {
+ foreach ($params as $index => $paramField) {
+ if (isset($paramField[$moneyField])) {
+ $params[$index][$moneyField] = CRM_Utils_Rule::cleanMoney($paramField[$moneyField]);
+ }
+ }
+ }
}
}
diff --git a/CRM/Event/Form/Registration/ParticipantConfirm.php b/CRM/Event/Form/Registration/ParticipantConfirm.php
index ff7d7b856b0e..e64d4e9e3443 100644
--- a/CRM/Event/Form/Registration/ParticipantConfirm.php
+++ b/CRM/Event/Form/Registration/ParticipantConfirm.php
@@ -1,9 +1,9 @@
_cc = CRM_Utils_Request::retrieve('cc', 'String', $this);
//get the contact and event id and assing to session.
- $values = array();
+ $values = [];
$csContactID = NULL;
if ($this->_participantId) {
- $params = array('id' => $this->_participantId);
+ $params = ['id' => $this->_participantId];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Participant', $params, $values,
- array('contact_id', 'event_id', 'status_id')
+ ['contact_id', 'event_id', 'status_id']
);
}
@@ -95,13 +98,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $params = array('id' => $this->_eventId);
- $values = array();
+ $params = ['id' => $this->_eventId];
+ $values = [];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $values,
- array('title')
+ ['title']
);
- $buttons = array();
+ $buttons = [];
// only pending status class family able to confirm.
$statusMsg = NULL;
@@ -115,27 +118,27 @@ public function buildQuickForm() {
$additonalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
$requireSpace = 1 + count($additonalIds);
if ($emptySeats !== NULL && ($requireSpace > $emptySeats)) {
- $statusMsg = ts("Oops, it looks like there are currently no available spaces for the %1 event.", array(1 => $values['title']));
+ $statusMsg = ts("Oops, it looks like there are currently no available spaces for the %1 event.", [1 => $values['title']]);
}
else {
if ($this->_cc == 'fail') {
- $statusMsg = '
' . ts('Click the "Confirm Registration" button to complete your registration in %1, or click "Cancel Registration" if you are no longer interested in attending this event.', array(
- 1 => $values['title'],
- )) . '
' . ts('Click the "Confirm Registration" button to complete your registration in %1, or click "Cancel Registration" if you are no longer interested in attending this event.', [
+ 1 => $values['title'],
+ ]) . '
' . ts('Click the "Confirm Registration" button to begin, or click "Cancel Registration" if you are no longer interested in attending this event.') . '
' . ts('Click the "Confirm Registration" button to begin, or click "Cancel Registration" if you are no longer interested in attending this event.') . '
" . ts("Email has been sent to : %1", array(1 => $displayName));
+ $statusMessage .= "
" . ts("Email has been sent to : %1", [1 => $displayName]);
}
}
$this->postProcessHook();
-
- CRM_Core_Error::statusBounce($statusMessage,
- CRM_Utils_System::url('civicrm/event/info',
+ CRM_Core_Session::setStatus($statusMessage);
+ CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/info',
"reset=1&id={$this->_eventId}&noFullMsg=1",
FALSE, NULL, FALSE, TRUE
)
diff --git a/CRM/Event/Form/Registration/Register.php b/CRM/Event/Form/Registration/Register.php
index 82a726eb31c8..ac1388a35b3b 100644
--- a/CRM/Event/Form/Registration/Register.php
+++ b/CRM/Event/Form/Registration/Register.php
@@ -1,9 +1,9 @@
_values['discount'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_values['discount'][$fields['amount']]) == 0
+ )
+ ) {
+ $isZeroAmount = TRUE;
+ }
+ elseif (!empty($fields['amount']) &&
+ (isset($form->_values['fee'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_values['fee'][$fields['amount']]) == 0
+ )
+ ) {
+ $isZeroAmount = TRUE;
+ }
+ return $isZeroAmount;
+ }
/**
* Get the contact id for the registration.
*
* @param array $fields
- * @param CRM_Core_Form $self
+ * @param CRM_Event_Form_Registration $form
* @param bool $isAdditional
*
* @return int|null
*/
- protected static function getRegistrationContactID($fields, $self, $isAdditional) {
-
+ public static function getRegistrationContactID($fields, $form, $isAdditional) {
$contactID = NULL;
if (!$isAdditional) {
- $contactID = $self->getContactID();
+ $contactID = $form->getContactID();
}
if (!$contactID && is_array($fields) && $fields) {
- $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $self->_values['event']));
+ $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $form->_values['event']), ['event_id' => CRM_Utils_Array::value('id', $form->_values['event'])]);
}
return $contactID;
}
/**
* Set variables up before form is built.
+ *
+ * @throws \CRM_Core_Exception
*/
public function preProcess() {
parent::preProcess();
@@ -116,7 +162,7 @@ public function preProcess() {
// We hide the payment fields if the event is full or requires approval,
// and the current user has not yet been approved CRM-12279
$this->_noFees = (($eventFull || $this->_requireApproval) && !$this->_allowConfirmation);
- $this->_paymentProcessors = $this->_noFees ? array() : $this->get('paymentProcessors');
+ $this->_paymentProcessors = $this->_noFees ? [] : $this->get('paymentProcessors');
$this->preProcessPaymentOptions();
$this->_allowWaitlist = FALSE;
@@ -144,9 +190,14 @@ public function preProcess() {
/**
* Set default values for the form.
+ *
+ * @return array
+ *
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
if (!$this->_allowConfirmation && $this->_requireApproval) {
$this->_defaults['bypass_payment'] = 1;
}
@@ -223,7 +274,7 @@ public function setDefaultValues() {
if (empty($val['options'])) {
continue;
}
- $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, array());
+ $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, []);
foreach ($val['options'] as $keys => $values) {
if ($values['is_default'] && empty($values['is_full'])) {
@@ -301,7 +352,7 @@ public function buildQuickForm() {
if (!$this->_allowConfirmation || $this->_additionalParticipantIds) {
// CRM-17745: Make maximum additional participants configurable
// Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
- $additionalOptions = array();
+ $additionalOptions = [];
$additionalOptions[''] = 1;
for ($i = 1; $i <= $this->_values['event']['max_additional_participants']; $i++) {
$additionalOptions[$i] = $i + 1;
@@ -310,7 +361,7 @@ public function buildQuickForm() {
ts('How many people are you registering?'),
$additionalOptions,
NULL,
- array('onChange' => "allowParticipant()")
+ ['onChange' => "allowParticipant()"]
);
$isAdditionalParticipants = TRUE;
}
@@ -331,7 +382,7 @@ public function buildQuickForm() {
//case might be group become as a part of waitlist.
//If not waitlist then they require admin approve.
$allowGroupOnWaitlist = TRUE;
- $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", array(1 => $this->_availableRegistrations));
+ $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", [1 => $this->_availableRegistrations]);
if ($this->_requireApproval) {
$this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
@@ -359,21 +410,17 @@ public function buildQuickForm() {
self::buildAmount($this);
}
- $pps = array();
+ $pps = [];
//@todo this processor adding fn is another one duplicated on contribute - a shared
// common class would make this sort of thing extractable
- $onlinePaymentProcessorEnabled = FALSE;
if (!empty($this->_paymentProcessors)) {
foreach ($this->_paymentProcessors as $key => $name) {
- if ($name['billing_mode'] == 1) {
- $onlinePaymentProcessorEnabled = TRUE;
- }
$pps[$key] = $name['name'];
}
}
if ($this->getContactID() === 0 && !$this->_values['event']['is_multiple_registrations']) {
//@todo we are blocking for multiple registrations because we haven't tested
- $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
+ $this->addCIDZeroOptions();
}
if (!empty($this->_values['event']['is_pay_later']) &&
($this->_allowConfirmation || (!$this->_requireApproval && !$this->_allowWaitlist))
@@ -394,7 +441,7 @@ public function buildQuickForm() {
}
}
- $this->addElement('hidden', 'bypass_payment', NULL, array('id' => 'bypass_payment'));
+ $this->addElement('hidden', 'bypass_payment', NULL, ['id' => 'bypass_payment']);
$this->assign('bypassPayment', $bypassPayment);
@@ -412,7 +459,7 @@ public function buildQuickForm() {
$this->_values['custom_post_id']
) {
if (!is_array($this->_values['custom_post_id'])) {
- $profileIDs = array($this->_values['custom_post_id']);
+ $profileIDs = [$this->_values['custom_post_id']];
}
else {
$profileIDs = $this->_values['custom_post_id'];
@@ -454,10 +501,8 @@ public function buildQuickForm() {
) {
//freeze button to avoid multiple calls.
- $js = NULL;
-
if (empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $this->submitOnce = TRUE;
}
// CRM-11182 - Optional confirmation screen
@@ -473,19 +518,17 @@ public function buildQuickForm() {
$buttonLabel = ts('Continue');
}
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => $buttonLabel,
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- 'js' => $js,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => $buttonLabel,
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
- $this->addFormRule(array('CRM_Event_Form_Registration_Register', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_Register', 'formRule'], $this);
$this->unsavedChangesWarn = TRUE;
// add pcp fields
@@ -497,14 +540,16 @@ public function buildQuickForm() {
/**
* Build the radio/text form elements for the amount field
*
- * @param CRM_Core_Form $form
+ * @param CRM_Event_Form_Registration_Register $form
* Form object.
* @param bool $required
* True if you want to add formRule.
* @param int $discountId
* Discount id for the event.
+ *
+ * @throws \CRM_Core_Exception
*/
- static public function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
+ public static function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
// build amount only when needed, skip incase of event full and waitlisting is enabled
// and few other conditions check preProcess()
if (property_exists($form, '_noFees') && $form->_noFees) {
@@ -535,7 +580,7 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
}
}
if (!is_array($form->_feeBlock)) {
- $form->_feeBlock = array();
+ $form->_feeBlock = [];
}
//its time to call the hook.
@@ -566,6 +611,11 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
$adminFieldVisible = TRUE;
}
+ $hideAdminValues = TRUE;
+ if (CRM_Core_Permission::check('edit event participants')) {
+ $hideAdminValues = FALSE;
+ }
+
foreach ($form->_feeBlock as $field) {
// public AND admin visibility fields are included for back-office registration and back-office change selections
if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
@@ -583,11 +633,24 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
//user might modified w/ hook.
$options = CRM_Utils_Array::value('options', $field);
+ $formClasses = ['CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection'];
+
if (!is_array($options)) {
continue;
}
+ elseif ($hideAdminValues && !in_array($className, $formClasses)) {
+ $publicVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('public');
+ $adminVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('admin');
+
+ foreach ($options as $key => $currentOption) {
+ $optionVisibility = CRM_Utils_Array::value('visibility_id', $currentOption, $publicVisibilityID);
+ if ($optionVisibility == $adminVisibilityID) {
+ unset($options[$key]);
+ }
+ }
+ }
- $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, array());
+ $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, []);
//soft suppress required rule when option is full.
if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
@@ -610,14 +673,14 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
$form->assign('priceSet', $form->_priceSet);
}
else {
- $eventFeeBlockValues = array();
+ $eventFeeBlockValues = [];
foreach ($form->_feeBlock as $fee) {
if (is_array($fee)) {
//CRM-7632, CRM-6201
$totalAmountJs = NULL;
if ($className == 'CRM_Event_Form_Participant') {
- $totalAmountJs = array('onClick' => "fillTotalAmount(" . $fee['value'] . ")");
+ $totalAmountJs = ['onClick' => "fillTotalAmount(" . $fee['value'] . ")"];
}
$eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
@@ -643,12 +706,12 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
}
/**
- * @param CRM_Core_Form $form
+ * @param CRM_Event_Form_Registration $form
*/
public static function formatFieldsForOptionFull(&$form) {
$priceSet = $form->get('priceSet');
$priceSetId = $form->get('priceSetId');
- $defaultPricefieldIds = array();
+ $defaultPricefieldIds = [];
if (!empty($form->_values['line_items'])) {
foreach ($form->_values['line_items'] as $lineItem) {
$defaultPricefieldIds[] = $lineItem['price_field_value_id'];
@@ -661,7 +724,7 @@ public static function formatFieldsForOptionFull(&$form) {
return;
}
- $skipParticipants = $formattedPriceSetDefaults = array();
+ $skipParticipants = $formattedPriceSetDefaults = [];
if (!empty($form->_allowConfirmation) && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
$participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
$pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
@@ -686,7 +749,7 @@ public static function formatFieldsForOptionFull(&$form) {
$optionFullTotalAmount = 0;
$currentParticipantNo = (int) substr($form->_name, 12);
foreach ($form->_feeBlock as & $field) {
- $optionFullIds = array();
+ $optionFullIds = [];
$fieldId = $field['id'];
if (!is_array($field['options'])) {
continue;
@@ -736,7 +799,7 @@ public static function formatFieldsForOptionFull(&$form) {
//ignore option full for offline registration.
if ($className == 'CRM_Event_Form_Participant') {
- $optionFullIds = array();
+ $optionFullIds = [];
}
//finally get option ids in.
@@ -752,40 +815,41 @@ public static function formatFieldsForOptionFull(&$form) {
* The input form values.
* @param array $files
* The uploaded files if any.
- * @param $self
- *
+ * @param \CRM_Event_Form_Registration_Register $form
*
* @return bool|array
* true if no errors, else array of errors
+ *
+ * @throws \CRM_Core_Exception
*/
- public static function formRule($fields, $files, $self) {
- $errors = array();
+ public static function formRule($fields, $files, $form) {
+ $errors = [];
//check that either an email or firstname+lastname is included in the form(CRM-9587)
- self::checkProfileComplete($fields, $errors, $self->_eventId);
+ self::checkProfileComplete($fields, $errors, $form->_eventId);
//To check if the user is already registered for the event(CRM-2426)
- if (!$self->_skipDupeRegistrationCheck) {
- self::checkRegistration($fields, $self);
+ if (!$form->_skipDupeRegistrationCheck) {
+ self::checkRegistration($fields, $form);
}
//check for availability of registrations.
- if (!$self->_allowConfirmation && empty($fields['bypass_payment']) &&
- is_numeric($self->_availableRegistrations) &&
- CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations
+ if (!$form->_allowConfirmation && empty($fields['bypass_payment']) &&
+ is_numeric($form->_availableRegistrations) &&
+ CRM_Utils_Array::value('additional_participants', $fields) >= $form->_availableRegistrations
) {
- $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
+ $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", [1 => $form->_availableRegistrations]);
}
// during confirmation don't allow to increase additional participants, CRM-4320
- if ($self->_allowConfirmation && !empty($fields['additional_participants']) &&
- is_array($self->_additionalParticipantIds) &&
- $fields['additional_participants'] > count($self->_additionalParticipantIds)
+ if ($form->_allowConfirmation && !empty($fields['additional_participants']) &&
+ is_array($form->_additionalParticipantIds) &&
+ $fields['additional_participants'] > count($form->_additionalParticipantIds)
) {
- $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", array(1 => count($self->_additionalParticipantIds)));
+ $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", [1 => count($form->_additionalParticipantIds)]);
}
//don't allow to register w/ waiting if enough spaces available.
- if (!empty($fields['bypass_payment']) && $self->_allowConfirmation) {
- if (!is_numeric($self->_availableRegistrations) ||
- (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations)
+ if (!empty($fields['bypass_payment']) && $form->_allowConfirmation) {
+ if (!is_numeric($form->_availableRegistrations) ||
+ (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $form->_availableRegistrations)
) {
$errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
}
@@ -799,16 +863,16 @@ public static function formRule($fields, $files, $self) {
// priceset validations
if (!empty($fields['priceSetId']) &&
- !$self->_requireApproval && !$self->_allowWaitlist
+ !$form->_requireApproval && !$form->_allowWaitlist
) {
//format params.
- $formatted = self::formatPriceSetParams($self, $fields);
- $ppParams = array($formatted);
- $priceSetErrors = self::validatePriceSet($self, $ppParams);
- $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
+ $formatted = self::formatPriceSetParams($form, $fields);
+ $ppParams = [$formatted];
+ $priceSetErrors = self::validatePriceSet($form, $ppParams);
+ $primaryParticipantCount = self::getParticipantCount($form, $ppParams);
//get price set fields errors in.
- $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
+ $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, []));
$totalParticipants = $primaryParticipantCount;
if (!empty($fields['additional_participants'])) {
@@ -816,63 +880,41 @@ public static function formRule($fields, $files, $self) {
}
if (empty($fields['bypass_payment']) &&
- !$self->_allowConfirmation &&
- is_numeric($self->_availableRegistrations) &&
- $self->_availableRegistrations < $totalParticipants
+ !$form->_allowConfirmation &&
+ is_numeric($form->_availableRegistrations) &&
+ $form->_availableRegistrations < $totalParticipants
) {
- $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
+ $errors['_qf_default'] = ts("Only %1 Registrations available.", [1 => $form->_availableRegistrations]);
}
- $lineItem = array();
- CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
+ $lineItem = [];
+ CRM_Price_BAO_PriceSet::processAmount($form->_values['fee'], $fields, $lineItem);
$minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
if ($fields['amount'] < 0) {
$errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
}
elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
- $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', array(
+ $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', [
1 => CRM_Utils_Money::format($minAmt),
- ));
+ ]);
}
}
// @todo - can we remove the 'is_monetary' concept?
- if ($self->_values['event']['is_monetary']) {
- if (empty($self->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
+ if ($form->_values['event']['is_monetary']) {
+ if (empty($form->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
!isset($fields['payment_processor_id'])) {
$errors['payment_processor_id'] = ts('Please select a Payment Method');
}
- $isZeroAmount = $skipPaymentValidation = FALSE;
- if (!empty($fields['priceSetId'])) {
- if (CRM_Utils_Array::value('amount', $fields) == 0) {
- $isZeroAmount = TRUE;
- }
- }
- elseif (!empty($fields['amount']) &&
- (isset($self->_values['discount'][$fields['amount']])
- && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
- )
- ) {
- $isZeroAmount = TRUE;
- }
- elseif (!empty($fields['amount']) &&
- (isset($self->_values['fee'][$fields['amount']])
- && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0
- )
- ) {
- $isZeroAmount = TRUE;
- }
-
- if ($isZeroAmount && !($self->_forcePayement && !empty($fields['additional_participants']))) {
- $skipPaymentValidation = TRUE;
+ if (self::isZeroAmount($fields, $form)) {
+ return empty($errors) ? TRUE : $errors;
}
// also return if zero fees for valid members
if (!empty($fields['bypass_payment']) ||
- $skipPaymentValidation ||
- (!$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist))
+ (!$form->_allowConfirmation && ($form->_requireApproval || $form->_allowWaitlist))
) {
return empty($errors) ? TRUE : $errors;
}
@@ -880,16 +922,16 @@ public static function formRule($fields, $files, $self) {
$fields['payment_processor_id'],
$fields,
$errors,
- (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
+ (!$form->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
);
}
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
- $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
+ $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
$errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
- array(1 => ucwords(str_replace('_', ' ', $greeting)))
+ [1 => ucwords(str_replace('_', ' ', $greeting))]
);
}
}
@@ -913,7 +955,7 @@ public static function checkProfileComplete($fields, &$errors, $eventId) {
}
if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
- $defaults = $params = array('id' => $eventId);
+ $defaults = $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
$errors['_qf_default'] = $message;
@@ -1025,7 +1067,7 @@ public function postProcess() {
}
}
else {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
if ($params['tax_amount']) {
$this->set('tax_amount', $params['tax_amount']);
@@ -1035,11 +1077,11 @@ public function postProcess() {
$submittedLineItems[0] = $lineItem;
}
else {
- $submittedLineItems = array($lineItem);
+ $submittedLineItems = [$lineItem];
}
$submittedLineItems = array_filter($submittedLineItems);
$this->set('lineItem', $submittedLineItems);
- $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
+ $this->set('lineItemParticipantsCount', [$primaryParticipantCount]);
}
$this->set('amount', $params['amount']);
@@ -1059,23 +1101,9 @@ public function postProcess() {
$this->set('contributeMode', 'direct');
// This code is duplicated multiple places and should be consolidated.
- if (isset($params["state_province_id-{$this->_bltID}"]) &&
- $params["state_province_id-{$this->_bltID}"]
- ) {
- $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
- }
+ $params = $this->prepareParamsForPaymentProcessor($params);
- if (isset($params["country_id-{$this->_bltID}"]) &&
- $params["country_id-{$this->_bltID}"]
- ) {
- $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
- }
- if (isset($params['credit_card_exp_date'])) {
- $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
- $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
- }
if ($this->_values['event']['is_monetary']) {
- $params['ip_address'] = CRM_Utils_System::ipAddress();
$params['currencyID'] = $config->defaultCurrency;
$params['invoiceID'] = $invoiceID;
}
@@ -1086,7 +1114,7 @@ public function postProcess() {
$this->_params[0] = $params;
}
else {
- $this->_params = array();
+ $this->_params = [];
$this->_params[] = $params;
}
$this->set('params', $this->_params);
@@ -1109,7 +1137,7 @@ public function postProcess() {
"_qf_Register_display=1&qfKey={$this->controller->_key}",
TRUE, NULL, FALSE
);
- if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
+ if (!empty($params['additional_participants'])) {
$urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
}
else {
@@ -1125,7 +1153,7 @@ public function postProcess() {
$this->handlePreApproval($params);
}
elseif ($this->_paymentProcessor &&
- $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
+ (int) $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
) {
// The concept of contributeMode is deprecated - but still needs removal from the message templates.
$this->set('contributeMode', 'notify');
@@ -1134,20 +1162,21 @@ public function postProcess() {
else {
$params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
- $this->_params = array();
+ $this->_params = [];
$this->_params[] = $params;
$this->set('params', $this->_params);
if (
empty($params['additional_participants'])
- && !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
+ // CRM-11182 - Optional confirmation screen
+ && !$this->_values['event']['is_confirm_enabled']
) {
$this->processRegistration($this->_params);
}
}
// If registering > 1 participant, give status message
- if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
+ if (!empty($params['additional_participants'])) {
$statusMsg = ts('Registration information for participant 1 has been saved.');
CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
}
@@ -1159,58 +1188,58 @@ public function postProcess() {
*
* @param array $fields
* The input form values(anonymous user).
- * @param CRM_Event_Form_Registration_Register $self
+ * @param CRM_Event_Form_Registration_Register $form
* Event data.
* @param bool $isAdditional
* Treat isAdditional participants a bit differently.
*
* @return int
*/
- public static function checkRegistration($fields, &$self, $isAdditional = FALSE) {
+ public static function checkRegistration($fields, $form, $isAdditional = FALSE) {
// CRM-3907, skip check for preview registrations
// CRM-4320 participant need to walk wizard
if (
- ($self->_mode == 'test' || $self->_allowConfirmation)
+ ($form->_mode == 'test' || $form->_allowConfirmation)
) {
return FALSE;
}
- $contactID = self::getRegistrationContactID($fields, $self, $isAdditional);
+ $contactID = self::getRegistrationContactID($fields, $form, $isAdditional);
if ($contactID) {
$participant = new CRM_Event_BAO_Participant();
$participant->contact_id = $contactID;
- $participant->event_id = $self->_values['event']['id'];
+ $participant->event_id = $form->_values['event']['id'];
if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
$participant->role_id = $fields['participant_role'];
}
else {
- $participant->role_id = $self->_values['event']['default_role_id'];
+ $participant->role_id = $form->_values['event']['default_role_id'];
}
$participant->is_test = 0;
$participant->find();
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
while ($participant->fetch()) {
if (array_key_exists($participant->status_id, $statusTypes)) {
- if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
+ if (!$isAdditional && !$form->_values['event']['allow_same_participant_emails']) {
$registerUrl = CRM_Utils_System::url('civicrm/event/register',
- "reset=1&id={$self->_values['event']['id']}&cid=0"
+ "reset=1&id={$form->_values['event']['id']}&cid=0"
);
- if ($self->_pcpId) {
- $registerUrl .= '&pcpId=' . $self->_pcpId;
+ if ($form->_pcpId) {
+ $registerUrl .= '&pcpId=' . $form->_pcpId;
}
- $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', array(1 => $registerUrl));
+ $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', [1 => $registerUrl]);
CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
$url = CRM_Utils_System::url('civicrm/event/info',
- "reset=1&id={$self->_values['event']['id']}&noFullMsg=true"
+ "reset=1&id={$form->_values['event']['id']}&noFullMsg=true"
);
- if ($self->_action & CRM_Core_Action::PREVIEW) {
+ if ($form->_action & CRM_Core_Action::PREVIEW) {
$url .= '&action=preview';
}
- if ($self->_pcpId) {
- $url .= '&pcpId=' . $self->_pcpId;
+ if ($form->_pcpId) {
+ $url .= '&pcpId=' . $form->_pcpId;
}
CRM_Utils_System::redirect($url);
diff --git a/CRM/Event/Form/Registration/ThankYou.php b/CRM/Event/Form/Registration/ThankYou.php
index 3a29a96eeaef..00a1d89afa36 100644
--- a/CRM/Event/Form/Registration/ThankYou.php
+++ b/CRM/Event/Form/Registration/ThankYou.php
@@ -1,9 +1,9 @@
assignToTemplate();
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- $getTaxDetails = FALSE;
+ $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
$taxAmount = 0;
- $lineItemForTemplate = array();
+ $lineItemForTemplate = [];
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
if (!empty($value) && $value != 'skip') {
@@ -111,7 +109,6 @@ public function buildQuickForm() {
foreach ($value as $v) {
if (isset($v['tax_amount']) || isset($v['tax_rate'])) {
$taxAmount += $v['tax_amount'];
- $getTaxDetails = TRUE;
}
}
}
@@ -123,13 +120,11 @@ public function buildQuickForm() {
!CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config') &&
!empty($lineItemForTemplate)
) {
- $this->assign('lineItem', $lineItemForTemplate);
+ $this->assignLineItemsToTemplate($lineItemForTemplate);
}
if ($invoicing) {
- $this->assign('getTaxDetails', $getTaxDetails);
$this->assign('totalTaxAmount', $taxAmount);
- $this->assign('taxTerm', $taxTerm);
}
$this->assign('totalAmount', $this->_totalAmount);
@@ -148,8 +143,8 @@ public function buildQuickForm() {
if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
$this->assign('defaultRole', TRUE);
}
- $defaults = array();
- $fields = array();
+ $defaults = [];
+ $fields = [];
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
@@ -179,7 +174,7 @@ public function buildQuickForm() {
$params['entity_id'] = $this->_eventId;
$params['entity_table'] = 'civicrm_event';
- $data = array();
+ $data = [];
CRM_Friend_BAO_Friend::retrieve($params, $data);
if (!empty($data['is_active'])) {
$friendText = $data['title'];
diff --git a/CRM/Event/Form/Search.php b/CRM/Event/Form/Search.php
index 455210313596..e53572d90d2f 100644
--- a/CRM/Event/Form/Search.php
+++ b/CRM/Event/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
- $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
- $this->assign("context", $this->_context);
-
- // get user submitted values
- // get it from controller only if form has been submitted, else preProcess has set this
- if (!empty($_POST) && !$this->controller->isModal()) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
- else {
- $this->_formValues = $this->get('formValues');
- }
- if (empty($this->_formValues)) {
- if (isset($this->_ssID)) {
- $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
- }
- }
+ $this->loadStandardSearchOptionsFromUrl();
+ $this->loadFormValues();
if ($this->_force) {
$this->postProcess();
@@ -130,7 +117,7 @@ public function preProcess() {
);
}
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
NULL,
@@ -163,22 +150,19 @@ public function preProcess() {
/**
* Build the form object.
*
- *
* @return void
+ *
+ * @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
-
- if (CRM_Core_Permission::check('access deleted contacts') and Civi::settings()->get('contact_undelete')) {
- $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '
' . ts('(deleted contacts)'));
- }
+ $this->addContactSearchFields();
CRM_Event_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
- $lineItems = $eventIds = array();
+ $lineItems = $eventIds = [];
if (!$this->_single) {
$this->addRowSelectors($rows);
}
@@ -194,18 +178,18 @@ public function buildQuickForm() {
$participantCount = 0;
if (count($eventIds) == 1) {
//convert form values to clause.
- $seatClause = array();
+ $seatClause = [];
if (CRM_Utils_Array::value('participant_test', $this->_formValues) == '1' || CRM_Utils_Array::value('participant_test', $this->_formValues) == '0') {
$seatClause[] = "( participant.is_test = {$this->_formValues['participant_test']} )";
}
if (!empty($this->_formValues['participant_status_id'])) {
- $seatClause[] = CRM_Contact_BAO_Query::buildClause("participant.status_id", '=', $this->_formValues['participant_status_id'], 'Int');
+ $seatClause[] = CRM_Contact_BAO_Query::buildClause("participant.status_id", 'IN', $this->_formValues['participant_status_id'], 'Int');
if ($status = CRM_Utils_Array::value('IN', $this->_formValues['participant_status_id'])) {
$this->_formValues['participant_status_id'] = $status;
}
}
if (!empty($this->_formValues['participant_role_id'])) {
- $escapedRoles = array();
+ $escapedRoles = [];
foreach ((array) $this->_formValues['participant_role_id'] as $participantRole) {
$escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
}
@@ -215,11 +199,13 @@ public function buildQuickForm() {
// CRM-15379
if (!empty($this->_formValues['participant_fee_id'])) {
$participant_fee_id = $this->_formValues['participant_fee_id'];
+ $val_regexp = [];
foreach ($participant_fee_id as $k => &$val) {
$val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
+ $val_regexp[$k] = CRM_Core_DAO::escapeString(preg_quote(trim($val)));
$val = CRM_Core_DAO::escapeString(trim($val));
}
- $feeLabel = implode('|', $participant_fee_id);
+ $feeLabel = implode('|', $val_regexp);
$seatClause[] = "( participant.fee_level REGEXP '{$feeLabel}' )";
}
@@ -229,18 +215,14 @@ public function buildQuickForm() {
$this->assign('participantCount', $participantCount);
$this->assign('lineItems', $lineItems);
- $permission = CRM_Core_Permission::getPermission();
+ $taskParams['ssID'] = isset($this->_ssID) ? $this->_ssID : NULL;
+ $tasks = CRM_Event_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission(), $taskParams);
- $tasks = CRM_Event_Task::permissionedTaskTitles($permission);
if (isset($this->_ssID)) {
- if ($permission == CRM_Core_Permission::EDIT) {
- $tasks = $tasks + CRM_Event_Task::optionalTaskTitle();
- }
-
- $savedSearchValues = array(
+ $savedSearchValues = [
'id' => $this->_ssID,
'name' => CRM_Contact_BAO_SavedSearch::getName($this->_ssID, 'title'),
- );
+ ];
$this->assign_by_ref('savedSearch', $savedSearchValues);
$this->assign('ssID', $this->_ssID);
}
@@ -273,36 +255,49 @@ protected function getSortNameLabelWithOutEmail() {
}
/**
- * The post processing of the form gets done here.
+ * Get the label for the tag field.
*
- * Key things done during post processing are
- * - check for reset or next request. if present, skip post procesing.
- * - now check if user requested running a saved search, if so, then
- * the form values associated with the saved search are used for searching.
- * - if user has done a submit with new values the regular post submissing is
- * done.
- * The processing consists of using a Selector / Controller framework for getting the
- * search results.
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
*
- * @param
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Participant Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
*
- * @return void
+ * @return string
*/
- public function postProcess() {
- if ($this->_done) {
- return;
- }
+ protected function getGroupLabel() {
+ return ts('Participant Group(s)');
+ }
- $this->_done = TRUE;
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Participant Contact Type');
+ }
- if (!empty($_POST)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, array('participant_status_id'));
- }
+ /**
+ * Test submit the form.
+ * @param $formValues
+ */
+ public function testSubmit($formValues) {
+ $this->submit($formValues);
+ }
- if (empty($this->_formValues)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
+ /**
+ * Submit the search form with given values.
+ * @param $formValues
+ */
+ private function submit($formValues) {
+ $this->_formValues = $formValues;
$this->fixFormValues();
@@ -318,7 +313,7 @@ public function postProcess() {
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
@@ -341,7 +336,7 @@ public function postProcess() {
);
}
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
@@ -379,26 +374,49 @@ public function postProcess() {
}
/**
- * add the rules (mainly global rules) for form.
- * All local rules are added near the element
+ * The post processing of the form gets done here.
+ *
+ * Key things done during post processing are
+ * - check for reset or next request. if present, skip post procesing.
+ * - now check if user requested running a saved search, if so, then
+ * the form values associated with the saved search are used for searching.
+ * - if user has done a submit with new values the regular post submissing is
+ * done.
+ * The processing consists of using a Selector / Controller framework for getting the
+ * search results.
+ *
+ * @param
*
* @return void
- * @see valid_date
*/
- public function addRules() {
+ public function postProcess() {
+ if ($this->_done) {
+ return;
+ }
+
+ $this->_done = TRUE;
+ $formValues = [];
+
+ if (!empty($_POST)) {
+ $formValues = $this->controller->exportValues($this->_name);
+ CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, ['participant_status_id']);
+ }
+
+ if (empty($formValues)) {
+ $formValues = $this->controller->exportValues($this->_name);
+ }
+
+ $this->submit($formValues);
}
/**
- * Set the default form values.
- *
+ * add the rules (mainly global rules) for form.
+ * All local rules are added near the element
*
- * @return array
- * the default array reference
+ * @return void
+ * @see valid_date
*/
- public function setDefaultValues() {
- $defaults = array();
- $defaults = $this->_formValues;
- return $defaults;
+ public function addRules() {
}
public function fixFormValues() {
@@ -426,7 +444,7 @@ public function fixFormValues() {
elseif (is_array($status) && !array_key_exists('IN', $status)) {
$statusTypes = array_keys($status);
}
- $this->_formValues['participant_status_id'] = is_array($statusTypes) ? array('IN' => array_keys($statusTypes)) : $statusTypes;
+ $this->_formValues['participant_status_id'] = is_array($statusTypes) ? ['IN' => array_keys($statusTypes)] : $statusTypes;
}
$role = CRM_Utils_Request::retrieve('role', 'String');
diff --git a/CRM/Event/Form/SearchEvent.php b/CRM/Event/Form/SearchEvent.php
index d76fb9e4adec..402535ceb893 100644
--- a/CRM/Event/Form/SearchEvent.php
+++ b/CRM/Event/Form/SearchEvent.php
@@ -1,9 +1,9 @@
_showHide = new CRM_Core_ShowHideBlocks();
@@ -60,32 +60,31 @@ public function setDefaultValues() {
/**
* Build the form object.
*
- *
- * @return void
+ * @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
- $this->add('text', 'title', ts('Find'),
- array(CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'title'))
+ $this->add('text', 'title', ts('Event Name'),
+ [CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'title')]
);
- $this->addSelect('event_type_id', array('multiple' => TRUE, 'context' => 'search'));
+ $this->addSelect('event_type_id', ['multiple' => TRUE, 'context' => 'search']);
- $eventsByDates = array();
- $searchOption = array(ts('Show Current and Upcoming Events'), ts('Search All or by Date Range'));
- $this->addRadio('eventsByDates', ts('Events by Dates'), $searchOption, array('onclick' => "return showHideByValue('eventsByDates','1','id_fromToDates','block','radio',true);"), "
");
+ $eventsByDates = [];
+ $searchOption = [ts('Show Current and Upcoming Events'), ts('Search All or by Date Range')];
+ $this->addRadio('eventsByDates', ts('Events by Dates'), $searchOption, ['onclick' => "return showHideByValue('eventsByDates','1','id_fromToDates','block','radio',true);"], ' ');
- $this->addDate('start_date', ts('From'), FALSE, array('formatType' => 'searchDate'));
- $this->addDate('end_date', ts('To'), FALSE, array('formatType' => 'searchDate'));
+ $this->add('datepicker', 'start_date', ts('From'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'end_date', ts('To'), [], FALSE, ['time' => FALSE]);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
public function postProcess() {
@@ -93,14 +92,13 @@ public function postProcess() {
$parent = $this->controller->getParent();
$parent->set('searchResult', 1);
if (!empty($params)) {
- $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id');
+ $fields = ['title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
- if (substr($field, -4) == 'date') {
- $time = ($field == 'end_date') ? '235959' : NULL;
- $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
+ if ($field === 'end_date') {
+ $parent->set($field, $params[$field] . ' 23:59:59');
}
else {
$parent->set($field, $params[$field]);
diff --git a/CRM/Event/Form/SelfSvcTransfer.php b/CRM/Event/Form/SelfSvcTransfer.php
index 4469b0ef4ed6..6127eaee0c45 100644
--- a/CRM/Event/Form/SelfSvcTransfer.php
+++ b/CRM/Event/Form/SelfSvcTransfer.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -29,7 +29,7 @@
/**
*
* @package CRM
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*
*/
@@ -109,32 +109,39 @@ class CRM_Event_Form_SelfSvcTransfer extends CRM_Core_Form {
*
* @var string
*/
- protected $_participant = array();
+ protected $_participant = [];
/**
* particpant values
*
- * @array string
+ * @var string
*/
protected $_part_values;
/**
* details
*
- * @array string
+ * @var array
*/
- protected $_details = array();
+ protected $_details = [];
/**
* line items
*
- * @array string
+ * @var array
*/
- protected $_line_items = array();
+ protected $_line_items = [];
/**
* contact_id
*
- * @array string
+ * @var int
*/
protected $contact_id;
+ /**
+ * Is backoffice form?
+ *
+ * @var bool
+ */
+ protected $isBackoffice = FALSE;
+
/**
* Get source values for transfer based on participant id in URL. Line items will
* be transferred to this participant - at this point no transaction changes processed
@@ -147,8 +154,9 @@ public function preProcess() {
$this->_userContext = $session->readUserContext();
$this->_from_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
- $params = array('id' => $this->_from_participant_id);
- $participant = $values = array();
+ $this->isBackoffice = CRM_Utils_Request::retrieve('is_backoffice', 'String', $this, FALSE, NULL, 'REQUEST');
+ $params = ['id' => $this->_from_participant_id];
+ $participant = $values = [];
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_from_participant_id];
$this->set('values', $this->_part_values);
@@ -163,7 +171,7 @@ public function preProcess() {
if ($this->_from_participant_id) {
$this->assign('participantId', $this->_from_participant_id);
}
- $event = array();
+ $event = [];
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
@@ -171,7 +179,7 @@ public function preProcess() {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_from_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
- $details = array();
+ $details = [];
$details = CRM_Event_BAO_Participant::participantDetails($this->_from_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$query = "
@@ -204,16 +212,24 @@ public function preProcess() {
* return @void
*/
public function buildQuickForm() {
- $this->add('text', 'email', ts('To Email'), ts($this->_contact_email), TRUE);
- $this->add('text', 'last_name', ts('To Last Name'), ts($this->_to_contact_last_name), TRUE);
- $this->add('text', 'first_name', ts('To First Name'), ts($this->_to_contact_first_name), TRUE);
- $this->addButtons(array(
- array(
+ // use entityRef select field for contact when this form is used by staff/admin user
+ if ($this->isBackoffice) {
+ $this->addEntityRef("contact_id", ts('Select Contact'), ['create' => TRUE], TRUE);
+ }
+ // for front-end user show and use the basic three fields used to create a contact
+ else {
+ $this->add('text', 'email', ts('To Email'), $this->_contact_email, TRUE);
+ $this->add('text', 'last_name', ts('To Last Name'), $this->_to_contact_last_name, TRUE);
+ $this->add('text', 'first_name', ts('To First Name'), $this->_to_contact_first_name, TRUE);
+ }
+
+ $this->addButtons([
+ [
'type' => 'submit',
- 'name' => ts('Transfer Registration'),),
- )
- );
- $this->addFormRule(array('CRM_Event_Form_SelfSvcTransfer', 'formRule'), $this);
+ 'name' => ts('Transfer Registration'),
+ ],
+ ]);
+ $this->addFormRule(['CRM_Event_Form_SelfSvcTransfer', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -223,7 +239,7 @@ public function buildQuickForm() {
* return @array _defaults
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
return $this->_defaults;
}
@@ -233,11 +249,16 @@ public function setDefaultValues() {
* return array $errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
- //check that either an email or firstname+lastname is included in the form(CRM-9587)
- $to_contact_id = self::checkProfileComplete($fields, $errors, $self);
+ $errors = [];
+ if (!empty($fields['contact_id'])) {
+ $to_contact_id = $fields['contact_id'];
+ }
+ else {
+ //check that either an email or firstname+lastname is included in the form(CRM-9587)
+ $to_contact_id = self::checkProfileComplete($fields, $errors, $self);
+ }
//To check if the user is already registered for the event(CRM-2426)
- if ($to_contact_id) {
+ if (!empty($to_contact_id)) {
self::checkRegistration($fields, $self, $to_contact_id, $errors);
}
//return parent::formrule($fields, $files, $self);
@@ -258,7 +279,7 @@ public static function checkProfileComplete($fields, &$errors, $self) {
}
if (!$email && !(CRM_Utils_Array::value('first_name', $fields) &&
CRM_Utils_Array::value('last_name', $fields))) {
- $defaults = $params = array('id' => $eventId);
+ $defaults = $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
$errors['_qf_default'] = $message;
@@ -269,11 +290,12 @@ public static function checkProfileComplete($fields, &$errors, $self) {
$errors['email'] = ts('Enter valid email address.');
}
if (empty($errors) && empty($contact_id)) {
- $params = array(
+ $params = [
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
- 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE),);
+ 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE),
+ ];
//create new contact for this name/email pair
//if new contact, no need to check for contact already registered
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contact_id);
@@ -293,7 +315,7 @@ public static function checkRegistration($fields, $self, $contact_id, &$errors)
$query = "select event_id from civicrm_participant where contact_id = " . $contact_id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $to_event_id[] = $dao->event_id;
+ $to_event_id[] = $dao->event_id;
}
if (!empty($to_event_id)) {
foreach ($to_event_id as $id) {
@@ -311,16 +333,28 @@ public static function checkRegistration($fields, $self, $contact_id, &$errors)
public function postProcess() {
//For transfer, process form to allow selection of transferree
$params = $this->controller->exportValues($this->_name);
- //cancel 'from' participant row
- $query = "select contact_id from civicrm_email where email = '" . $params['email'] . "'";
- $dao = CRM_Core_DAO::executeQuery($query);
- while ($dao->fetch()) {
- $contact_id = $dao->contact_id;
+ if (!empty($params['contact_id'])) {
+ $contact_id = $params['contact_id'];
+ }
+ else {
+ //cancel 'from' participant row
+ $contact_id_result = civicrm_api3('Contact', 'get', [
+ 'sequential' => 1,
+ 'return' => ["id"],
+ 'email' => $params['email'],
+ 'options' => ['limit' => 1],
+ ]);
+ $contact_id_result = $contact_id_result['values'][0];
+ $contact_id = $contact_id_result['contact_id'];
+ $contact_is_deleted = $contact_id_result['contact_is_deleted'];
+ if ($contact_is_deleted || !is_numeric($contact_id)) {
+ CRM_Core_Error::statusBounce(ts('Contact does not exist.'));
+ }
}
- $from_participant = $params = array();
+ $from_participant = $params = [];
$query = "select role_id, source, fee_level, is_test, is_pay_later, fee_amount, discount_id, fee_currency,campaign_id, discount_amount from civicrm_participant where id = " . $this->_from_participant_id;
$dao = CRM_Core_DAO::executeQuery($query);
- $value_to = array();
+ $value_to = [];
while ($dao->fetch()) {
$value_to['role_id'] = $dao->role_id;
$value_to['source'] = $dao->source;
@@ -331,7 +365,11 @@ public function postProcess() {
}
$value_to['contact_id'] = $contact_id;
$value_to['event_id'] = $this->_event_id;
- $value_to['status_id'] = 1;
+ $value_to['status_id'] = CRM_Core_PseudoConstant::getKey(
+ 'CRM_Event_BAO_Participant',
+ 'status_id',
+ 'Registered'
+ );
$value_to['register_date'] = date("Y-m-d");
//first create the new participant row -don't set registered_by yet or email won't be sent
$participant = CRM_Event_BAO_Participant::create($value_to);
@@ -339,7 +377,7 @@ public function postProcess() {
$this->participantTransfer($participant);
//now update registered_by_id
$query = "UPDATE civicrm_participant cp SET cp.registered_by_id = %1 WHERE cp.id = ({$participant->id})";
- $params = array(1 => array($this->_from_participant_id, 'Integer'));
+ $params = [1 => [$this->_from_participant_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
//copy line items to new participant
$line_items = CRM_Price_BAO_LineItem::getLineItems($this->_from_participant_id);
@@ -350,7 +388,7 @@ public function postProcess() {
$new_item = CRM_Price_BAO_LineItem::create($item);
}
//now cancel the from participant record, leaving the original line-item(s)
- $value_from = array();
+ $value_from = [];
$value_from['id'] = $this->_from_participant_id;
$tansferId = array_search('Transferred', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value_from['status_id'] = $tansferId;
@@ -361,9 +399,12 @@ public function postProcess() {
CRM_Event_BAO_Participant::create($value_from);
$this->sendCancellation();
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $displayName));
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $displayName]);
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $email]);
CRM_Core_Session::setStatus($statusMsg, ts('Registration Transferred'), 'success');
+ if ($this->isBackoffice) {
+ return;
+ }
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
CRM_Utils_System::redirect($url);
}
@@ -374,19 +415,19 @@ public function postProcess() {
* return @ void
*/
public function participantTransfer($participant) {
- $contactDetails = array();
+ $contactDetails = [];
$contactIds[] = $participant->contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
+ FALSE, FALSE, NULL, [], 'CRM_Event_BAO_Participant');
foreach ($currentContactDetails as $contactId => $contactValues) {
$contactDetails[$contactId] = $contactValues;
}
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = " . $participant->id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -396,35 +437,35 @@ public function participantTransfer($participant) {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $domainValues = array();
+ $domainValues = [];
if (empty($domainValues)) {
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
}
- $eventDetails = array();
- $eventParams = array('id' => $participant->event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $participant->event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails);
//get default participant role.
$eventDetails['participant_role'] = CRM_Utils_Array::value($eventDetails['default_role_id'], $participantRoles);
//get the location info
- $locParams = array(
+ $locParams = [
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$eventDetails['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
$toEmail = CRM_Utils_Array::value('email', $contactDetails[$participant->contact_id]);
if ($toEmail) {
@@ -434,14 +475,14 @@ public function participantTransfer($participant) {
$receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
}
$participantName = $contactDetails[$participant->contact_id]['display_name'];
- $tplParams = array(
+ $tplParams = [
'event' => $eventDetails,
'participant' => $participantDetails[$participant->id],
'participantID' => $participant->id,
'participant_status' => 'Registered',
- );
+ ];
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_online_receipt',
'contactId' => $participantDetails[$participant->id]['contact_id'],
@@ -451,7 +492,7 @@ public function participantTransfer($participant) {
'toEmail' => $toEmail,
'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
- );
+ ];
CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
@@ -462,28 +503,28 @@ public function participantTransfer($participant) {
* return @ void
*/
public function sendCancellation() {
- $domainValues = array();
+ $domainValues = [];
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
- $participantRoles = array();
+ $participantRoles = [];
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_from_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -493,20 +534,20 @@ public function sendCancellation() {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $eventDetails = array();
- $eventParams = array('id' => $this->_event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $this->_event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
- $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
+ $locParams = ['entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'];
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_from_contact_id] = $this->_from_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(),
+ FALSE, FALSE, NULL, [],
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
@@ -521,8 +562,8 @@ public function sendCancellation() {
"Transferred",
""
);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
- $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contact_name]);
+ $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', [1 => $this->_contact_email]);
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
}
diff --git a/CRM/Event/Form/SelfSvcUpdate.php b/CRM/Event/Form/SelfSvcUpdate.php
index 693c53f19908..f8aafbddb54f 100644
--- a/CRM/Event/Form/SelfSvcUpdate.php
+++ b/CRM/Event/Form/SelfSvcUpdate.php
@@ -1,9 +1,9 @@
_userContext = $session->readUserContext();
- $participant = $values = array();
+ $participant = $values = [];
$this->_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
- $params = array('id' => $this->_participant_id);
+ $this->isBackoffice = CRM_Utils_Request::retrieve('is_backoffice', 'String', $this, FALSE, NULL, 'REQUEST');
+ $params = ['id' => $this->_participant_id];
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_participant_id];
$this->set('values', $this->_part_values);
@@ -135,7 +143,7 @@ public function preProcess() {
if ($this->_participant_id) {
$this->assign('participantId', $this->_participant_id);
}
- $event = array();
+ $event = [];
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
@@ -143,7 +151,7 @@ public function preProcess() {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
- $details = array();
+ $details = [];
$details = CRM_Event_BAO_Participant::participantDetails($this->_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_participant_id, 'contribution_id', 'participant_id');
@@ -159,7 +167,7 @@ public function preProcess() {
while ($dao->fetch()) {
$details['status'] = $dao->status;
$details['role'] = $dao->role;
- $details['fee_level'] = $dao->fee_level;
+ $details['fee_level'] = trim($dao->fee_level, CRM_Core_DAO::VALUE_SEPARATOR);
$details['fee_amount'] = $dao->fee_amount;
$details['register_date'] = $dao->register_date;
$details['event_start_date'] = $dao->start_date;
@@ -178,16 +186,16 @@ public function preProcess() {
}
$start_time = new Datetime($start_date);
$timenow = new Datetime();
- if (!empty($start_time) && $start_time < $timenow) {
+ if (!$this->isBackoffice && !empty($start_time) && $start_time < $timenow) {
$status = ts("Registration for this event cannot be cancelled or transferred once the event has begun. Contact the event organizer if you have questions.");
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
- if (!empty($time_limit) && $time_limit > 0) {
+ if (!$this->isBackoffice && !empty($time_limit) && $time_limit > 0) {
$interval = $timenow->diff($start_time);
$days = $interval->format('%d');
$hours = $interval->format('%h');
if ($hours <= $time_limit && $days < 1) {
- $status = ts("Registration for this event cannot be cancelled or transferred less than %1 hours prior to the event's start time. Contact the event organizer if you have questions.", array(1 => $time_limit));
+ $status = ts("Registration for this event cannot be cancelled or transferred less than %1 hours prior to the event's start time. Contact the event organizer if you have questions.", [1 => $time_limit]);
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
}
@@ -199,6 +207,7 @@ public function preProcess() {
// for self update (event.start_date > today, event can be 'self_updated'
// retrieve contact name and email, and let user verify his/her identity
}
+
/**
* buildQuickForm -populate input variables for source Event
* to cancel or transfer to another person
@@ -206,14 +215,14 @@ public function preProcess() {
* return @void
*/
public function buildQuickForm() {
- $this->add('select', 'action', ts('Transfer or Cancel Registration'), array(ts('-select-'), ts('Transfer'), ts('Cancel')), TRUE);
- $this->addButtons(array(
- array(
+ $this->add('select', 'action', ts('Transfer or Cancel Registration'), [ts('-select-'), ts('Transfer'), ts('Cancel')], TRUE);
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Submit'),
- ),
- ));
- $this->addFormRule(array('CRM_Event_Form_SelfSvcUpdate', 'formRule'), $this);
+ ],
+ ]);
+ $this->addFormRule(['CRM_Event_Form_SelfSvcUpdate', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -223,7 +232,7 @@ public function buildQuickForm() {
* return @void
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
$this->_defaults['details'] = $this->_details;
return $this->_defaults;
}
@@ -239,7 +248,7 @@ public function setDefaultValues() {
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if (empty($fields['action'])) {
$errors['action'] = ts("Please select Transfer OR Cancel action.");
}
@@ -274,11 +283,16 @@ public function postProcess() {
* return @void
*/
public function transferParticipant($params) {
- $transferUrl = 'civicrm/event/form/selfsvctransfer';
- $url = CRM_Utils_System::url('civicrm/event/selfsvctransfer', 'reset=1&action=add&pid=' . $this->_participant_id . '&cs=' . $this->_userChecksum);
- $this->controller->setDestination($url);
- $session = CRM_Core_Session::singleton();
- $session->replaceUserContext($url);
+ CRM_Utils_System::redirect(CRM_Utils_System::url(
+ 'civicrm/event/selfsvctransfer',
+ [
+ 'reset' => 1,
+ 'action' => 'add',
+ 'pid' => $this->_participant_id,
+ 'cs' => $this->_userChecksum,
+ 'is_backoffice' => $this->isBackoffice,
+ ]
+ ));
}
/**
@@ -290,34 +304,34 @@ public function transferParticipant($params) {
public function cancelParticipant($params) {
//set participant record status to Cancelled, refund payment if possible
// send email to participant and admin, and log Activity
- $value = array();
+ $value = [];
$value['id'] = $this->_participant_id;
$cancelledId = array_search('Cancelled',
CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value['status_id'] = $cancelledId;
CRM_Event_BAO_Participant::create($value);
- $domainValues = array();
+ $domainValues = [];
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
- $participantRoles = array();
+ $participantRoles = [];
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -327,20 +341,20 @@ public function cancelParticipant($params) {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $eventDetails = array();
- $eventParams = array('id' => $this->_event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $this->_event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
- $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
+ $locParams = ['entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'];
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_contact_id] = $this->_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(),
+ FALSE, FALSE, NULL, [],
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
@@ -355,9 +369,12 @@ public function cancelParticipant($params) {
"Cancelled",
""
);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
- $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contact_name]);
+ $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', [1 => $this->_contact_email]);
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
+ if (!empty($this->isBackoffice)) {
+ return;
+ }
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
CRM_Utils_System::redirect($url);
}
diff --git a/CRM/Event/Form/Task.php b/CRM/Event/Form/Task.php
index 231089cfc531..87e0a07a0c29 100644
--- a/CRM/Event/Form/Task.php
+++ b/CRM/Event/Form/Task.php
@@ -1,9 +1,9 @@
_participantIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_participantIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
- $eventTasks = CRM_Event_Task::tasks();
- $form->assign('taskName', $eventTasks[$form->_task]);
+ $tasks = CRM_Event_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission());
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -127,7 +108,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
//set the context for redirection for any task actions
$session = CRM_Core_Session::singleton();
- $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
+ $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
@@ -149,7 +130,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_participantIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_participantIds,
'civicrm_participant'
);
}
@@ -167,18 +148,17 @@ public function setContactIDs() {
* @return void
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Form/Task/AddToGroup.php b/CRM/Event/Form/Task/AddToGroup.php
index 10b3034a722a..42c63d4aa017 100644
--- a/CRM/Event/Form/Task/AddToGroup.php
+++ b/CRM/Event/Form/Task/AddToGroup.php
@@ -1,9 +1,9 @@
_id) {
- $this->addRadio('group_option', ts('Group Options'), $options, array('onclick' => "return showElements();"));
+ $this->addRadio('group_option', ts('Group Options'), $options, ['onclick' => "return showElements();"]);
$this->add('text', 'title', ts('Group Name:') . ' ',
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title')
);
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $this->_id, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $this->_id, 'title']
);
$this->add('textarea', 'description', ts('Description:') . ' ',
@@ -122,7 +122,7 @@ public function buildQuickForm() {
}
// add select for groups
- $group = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::group();
+ $group = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::group();
$groupElement = $this->add('select', 'group_id', ts('Select Group'), $group);
@@ -132,13 +132,13 @@ public function buildQuickForm() {
$groupElement->freeze();
// also set the group title
- $groupValues = array('id' => $this->_id, 'title' => $this->_title);
+ $groupValues = ['id' => $this->_id, 'title' => $this->_title];
$this->assign_by_ref('group', $groupValues);
}
// Set dynamic page title for 'Add Members Group (confirm)'
if ($this->_id) {
- CRM_Utils_System::setTitle(ts('Add Contacts: %1', array(1 => $this->_title)));
+ CRM_Utils_System::setTitle(ts('Add Contacts: %1', [1 => $this->_title]));
}
else {
CRM_Utils_System::setTitle(ts('Add Contacts to A Group'));
@@ -155,7 +155,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if ($this->_context === 'amtg') {
$defaults['group_id'] = $this->_id;
@@ -172,7 +172,7 @@ public function setDefaultValues() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Task_AddToGroup', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_Task_AddToGroup', 'formRule']);
}
/**
@@ -185,7 +185,7 @@ public function addRules() {
* list of errors to be posted back to the form
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!empty($params['group_option']) && empty($params['title'])) {
$errors['title'] = "Group Name is a required field";
@@ -207,7 +207,7 @@ public function postProcess() {
$params = $this->controller->exportValues();
$groupOption = CRM_Utils_Array::value('group_option', $params, NULL);
if ($groupOption) {
- $groupParams = array();
+ $groupParams = [];
$groupParams['title'] = $params['title'];
$groupParams['description'] = $params['description'];
$groupParams['visibility'] = "User and User Admin Only";
@@ -233,24 +233,24 @@ public function postProcess() {
list($total, $added, $notAdded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $groupID);
- $status = array(
- ts('%count contact added to group', array(
- 'count' => $added,
- 'plural' => '%count contacts added to group',
- )),
- );
+ $status = [
+ ts('%count contact added to group', [
+ 'count' => $added,
+ 'plural' => '%count contacts added to group',
+ ]),
+ ];
if ($notAdded) {
- $status[] = ts('%count contact was already in group', array(
- 'count' => $notAdded,
- 'plural' => '%count contacts were already in group',
- ));
+ $status[] = ts('%count contact was already in group', [
+ 'count' => $notAdded,
+ 'plural' => '%count contacts were already in group',
+ ]);
}
$status = '
';
- CRM_Core_Session::setStatus($status, ts('Added Contact to %1', array(
- 1 => $groupName,
- 'count' => $added,
- 'plural' => 'Added Contacts to %1',
- )), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts('Added Contact to %1', [
+ 1 => $groupName,
+ 'count' => $added,
+ 'plural' => 'Added Contacts to %1',
+ ]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Event/Form/Task/Badge.php b/CRM/Event/Form/Task/Badge.php
index 35ca60b222c1..6d21b4d8f624 100644
--- a/CRM/Event/Form/Task/Badge.php
+++ b/CRM/Event/Form/Task/Badge.php
@@ -1,9 +1,9 @@
_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
if ($this->_context == 'view') {
$this->_single = TRUE;
$participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
- $this->_participantIds = array($participantID);
+ $this->_participantIds = [$participantID];
$this->_componentClause = " civicrm_participant.id = $participantID ";
$this->assign('totalSelectedParticipants', 1);
@@ -83,9 +81,6 @@ public function preProcess() {
/**
* Build the form object.
- *
- *
- * @return void
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Make Name Badges'));
@@ -99,9 +94,9 @@ public function buildQuickForm() {
$this->add('select',
'badge_id',
ts('Name Badge Format'),
- array(
+ [
'' => ts('- select -'),
- ) + $label, TRUE
+ ] + $label, TRUE
);
$next = 'next';
@@ -111,9 +106,6 @@ public function buildQuickForm() {
/**
* Process the form after the input has been submitted and validated.
- *
- *
- * @return void
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
diff --git a/CRM/Event/Form/Task/Batch.php b/CRM/Event/Form/Task/Batch.php
index dfde70585969..e57358f3319c 100644
--- a/CRM/Event/Form/Task/Batch.php
+++ b/CRM/Event/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Name')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Name')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -102,7 +103,7 @@ public function buildQuickForm() {
$this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
if (array_key_exists('participant_status', $this->_fields)) {
$this->assign('statusProfile', 1);
@@ -111,7 +112,7 @@ public function buildQuickForm() {
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -129,18 +130,17 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Update Participant(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Update Participant(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_participantIds);
@@ -148,7 +148,7 @@ public function buildQuickForm() {
//load all campaigns.
if (array_key_exists('participant_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Event_DAO_Participant',
TRUE, 'campaign_id', 'id',
@@ -182,7 +182,7 @@ public function buildQuickForm() {
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields);
- $entityColumnValue = array();
+ $entityColumnValue = [];
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
@@ -225,7 +225,7 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
}
$this->addDefaultButtons(ts('Update Participant(s)'));
@@ -242,9 +242,9 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_participantIds as $participantId) {
- $details[$participantId] = array();
+ $details[$participantId] = [];
$details[$participantId] = CRM_Event_BAO_Participant::participantDetails($participantId);
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $participantId, 'Event');
@@ -273,70 +273,14 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
- $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
- if (isset($params['field'])) {
- foreach ($params['field'] as $key => $value) {
-
- //check for custom data
- $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
- $key,
- 'Participant'
- );
-
- $value['id'] = $key;
-
- if (!empty($value['participant_role'])) {
- if (is_array($value['participant_role'])) {
- $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
- }
- else {
- $value['role_id'] = $value['participant_role'];
- }
- }
-
- //need to send mail when status change
- $statusChange = FALSE;
- $relatedStatusChange = FALSE;
- if (!empty($value['participant_status'])) {
- $value['status_id'] = $value['participant_status'];
- $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
- if (!$fromStatusId) {
- $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
- }
-
- if ($fromStatusId != $value['status_id']) {
- $relatedStatusChange = TRUE;
- }
- if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
- $statusChange = TRUE;
- }
- }
-
- unset($value['participant_status']);
-
- civicrm_api3('Participant', 'create', $value);
-
- //need to trigger mails when we change status
- if ($statusChange) {
- CRM_Event_BAO_Participant::transitionParticipants(array($key), $value['status_id'], $fromStatusId);
- }
- if ($relatedStatusChange) {
- //update related contribution status, CRM-4395
- self::updatePendingOnlineContribution($key, $value['status_id']);
- }
- }
- CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
- }
- else {
- CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
- }
+ $this->submit($params);
}
/**
* @param int $participantId
* @param int $statusId
*
- * @return Ambigous|void
+ * @return mixed
*/
public static function updatePendingOnlineContribution($participantId, $statusId) {
if (!$participantId || !$statusId) {
@@ -370,13 +314,13 @@ public static function updatePendingOnlineContribution($participantId, $statusId
return;
}
- $params = array(
+ $params = [
'component_id' => $participantId,
'componentName' => 'Event',
'contribution_id' => $contributionId,
'contribution_status_id' => $contributionStatusId,
'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
- );
+ ];
//change related contribution status.
$updatedStatusId = self::updateContributionStatus($params);
@@ -406,7 +350,7 @@ public static function updateContributionStatus($params) {
return NULL;
}
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
//get the required ids.
$ids['contribution'] = $contributionId;
@@ -451,10 +395,10 @@ public static function updateContributionStatus($params) {
$contribution = &$objects['contribution'];
- $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+ $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
'labelColumn' => 'name',
'flip' => 1,
- ));
+ ]);
$input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = CRM_Utils_Array::value('IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved', $params);
if ($statusId == $contributionStatuses['Cancelled']) {
$baseIPN->cancelled($objects, $transaction, $input);
@@ -474,11 +418,11 @@ public static function updateContributionStatus($params) {
}
//set values for ipn code.
- foreach (array(
- 'fee_amount',
- 'check_number',
- 'payment_instrument_id',
- ) as $field) {
+ foreach ([
+ 'fee_amount',
+ 'check_number',
+ 'payment_instrument_id',
+ ] as $field) {
if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
$input[$field] = $contribution->$field;
}
@@ -510,7 +454,7 @@ public static function updateContributionStatus($params) {
* Assign the minimal set of variables to the template.
*/
public function assignToTemplate() {
- $notifyingStatuses = array('Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled');
+ $notifyingStatuses = ['Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled'];
$notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
$this->assign('status', TRUE);
if (!empty($notifyingStatuses)) {
@@ -519,4 +463,77 @@ public function assignToTemplate() {
}
}
+ /**
+ * @param $params
+ */
+ public function submit($params) {
+ $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
+ if (isset($params['field'])) {
+ foreach ($params['field'] as $key => $value) {
+
+ //check for custom data
+ $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
+ $key,
+ 'Participant'
+ );
+ foreach (array_keys($value) as $fieldName) {
+ // Unset the original custom field now that it has been formatting to the 'custom'
+ // array as it may not be in the right format for the api as is (notably for
+ // multiple checkbox values).
+ // @todo extract submit functions on other Batch update classes &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test them.
+ if (substr($fieldName, 0, 7) === 'custom_') {
+ unset($value[$fieldName]);
+ }
+ }
+
+ $value['id'] = $key;
+
+ if (!empty($value['participant_role'])) {
+ if (is_array($value['participant_role'])) {
+ $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
+ }
+ else {
+ $value['role_id'] = $value['participant_role'];
+ }
+ }
+
+ //need to send mail when status change
+ $statusChange = FALSE;
+ $relatedStatusChange = FALSE;
+ if (!empty($value['participant_status'])) {
+ $value['status_id'] = $value['participant_status'];
+ $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
+ if (!$fromStatusId) {
+ $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
+ }
+
+ if ($fromStatusId != $value['status_id']) {
+ $relatedStatusChange = TRUE;
+ }
+ if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
+ $statusChange = TRUE;
+ }
+ }
+
+ unset($value['participant_status']);
+
+ civicrm_api3('Participant', 'create', $value);
+
+ //need to trigger mails when we change status
+ if ($statusChange) {
+ CRM_Event_BAO_Participant::transitionParticipants([$key], $value['status_id'], $fromStatusId);
+ }
+ if ($relatedStatusChange) {
+ //update related contribution status, CRM-4395
+ self::updatePendingOnlineContribution($key, $value['status_id']);
+ }
+ }
+ CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
+ }
+ else {
+ CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
+ }
+ }
+
}
diff --git a/CRM/Event/Form/Task/Cancel.php b/CRM/Event/Form/Task/Cancel.php
index bc3956a34a99..2fc163490da3 100644
--- a/CRM/Event/Form/Task/Cancel.php
+++ b/CRM/Event/Form/Task/Cancel.php
@@ -1,9 +1,9 @@
addDefaultButtons(ts('Continue'), 'done');
+ $this->addDefaultButtons(ts('Cancel Registrations'), 'done');
}
/**
@@ -76,7 +77,7 @@ public function buildQuickForm() {
*/
public function postProcess() {
$params = $this->exportValues();
- $value = array();
+ $value = [];
foreach ($this->_participantIds as $participantId) {
$value['id'] = $participantId;
diff --git a/CRM/Event/Form/Task/Delete.php b/CRM/Event/Form/Task/Delete.php
index 275f77032de3..a784355f5fdb 100644
--- a/CRM/Event/Form/Task/Delete.php
+++ b/CRM/Event/Form/Task/Delete.php
@@ -1,9 +1,9 @@
ts('Delete this participant record along with associated participant record(s).'),
2 => ts('Delete only this participant record.'),
- );
+ ];
$this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '
');
- $this->setDefaults(array('delete_participant' => 1));
+ $this->setDefaults(['delete_participant' => 1]);
$this->addDefaultButtons(ts('Delete Participations'), 'done');
}
@@ -96,7 +96,7 @@ public function postProcess() {
$participantLinks = NULL;
if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
- $links = array();
+ $links = [];
foreach ($this->_participantIds as $participantId) {
$additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId));
$participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
@@ -131,7 +131,7 @@ public function postProcess() {
$deletedParticipants += $additionalCount;
}
- $status = ts('%count participant deleted.', array('plural' => '%count participants deleted.', 'count' => $deletedParticipants));
+ $status = ts('%count participant deleted.', ['plural' => '%count participants deleted.', 'count' => $deletedParticipants]);
if ($participantLinks) {
$status .= '
';
+ 1 => $threshold,
+ )) . ' ' . ts('Or Provide Contact ID or External ID.') . '
';
}
}
elseif (!in_array('event_title', $importKeys)) {
@@ -362,8 +360,7 @@ public static function formRule($fields, $files, $self) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Participant', 'name');
- if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
+ if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Participant'))) {
$errors['saveMappingName'] = ts('Duplicate Import Participant Mapping Name');
}
}
@@ -461,10 +458,7 @@ public function postProcess() {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Participant',
- 'name'
- ),
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Participant'),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
diff --git a/CRM/Event/Import/Form/Preview.php b/CRM/Event/Import/Form/Preview.php
index b42db7026fee..c2e32386fd06 100644
--- a/CRM/Event/Import/Form/Preview.php
+++ b/CRM/Event/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -98,7 +98,7 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -120,7 +120,7 @@ public function postProcess() {
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
+ $mapperKeys = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -131,7 +131,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -152,7 +152,7 @@ public function postProcess() {
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Event/Import/Form/Summary.php b/CRM/Event/Import/Form/Summary.php
index 1a9abaef1ac6..df860af8a0b9 100644
--- a/CRM/Event/Import/Form/Summary.php
+++ b/CRM/Event/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -105,7 +105,7 @@ public function preProcess() {
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Event/Import/Parser.php b/CRM/Event/Import/Parser.php
index 12ecfcf360c9..434f27961410 100644
--- a/CRM/Event/Import/Parser.php
+++ b/CRM/Event/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
@@ -192,14 +194,12 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -255,32 +255,26 @@ public function run(
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('View Participant URL'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('View Participant URL'),
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -316,7 +310,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -421,7 +415,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @return void
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Event/Import/Parser/Participant.php b/CRM/Event/Import/Parser/Participant.php
index 5d5b2431ee9f..7c41ed110a5a 100644
--- a/CRM/Event/Import/Parser/Participant.php
+++ b/CRM/Event/Import/Parser/Participant.php
@@ -1,9 +1,9 @@
addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newParticipants = array();
+ $this->_newParticipants = [];
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
@@ -287,8 +284,8 @@ public function import($onDuplicate, &$values) {
$params = &$this->getActiveFieldParams();
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
- $formatted = array('version' => 3);
- $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
+ $formatted = ['version' => 3];
+ $customFields = CRM_Core_BAO_CustomField::getFields('Participant');
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
@@ -317,7 +314,7 @@ public function import($onDuplicate, &$values) {
}
else {
$eventTitle = $params['event_title'];
- $qParams = array();
+ $qParams = [];
$dao = new CRM_Core_DAO();
$params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
$qParams
@@ -331,7 +328,7 @@ public function import($onDuplicate, &$values) {
$indieFields = CRM_Event_BAO_Participant::import();
}
- $formatValues = array();
+ $formatValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -340,7 +337,7 @@ public function import($onDuplicate, &$values) {
$formatValues[$key] = $field;
}
- $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
+ $formatError = $this->formatValues($formatted, $formatValues);
if ($formatError) {
array_unshift($values, $formatError['error_message']);
@@ -368,11 +365,11 @@ public function import($onDuplicate, &$values) {
'Participant'
);
if ($dao->find(TRUE)) {
- $ids = array(
+ $ids = [
'participant' => $formatValues['participant_id'],
'userId' => $session->get('userID'),
- );
- $participantValues = array();
+ ];
+ $participantValues = [];
//@todo calling api functions directly is not supported
$newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
if ($newParticipant['error_message']) {
@@ -381,10 +378,10 @@ public function import($onDuplicate, &$values) {
}
$newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
if (!empty($formatted['fee_level'])) {
- $otherParams = array(
+ $otherParams = [
'fee_label' => $formatted['fee_level'],
'event_id' => $newParticipant->event_id,
- );
+ ];
CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
}
@@ -399,11 +396,7 @@ public function import($onDuplicate, &$values) {
}
if ($this->_contactIdIndex < 0) {
-
- //retrieve contact id using contact dedupe rule
- $formatValues['contact_type'] = $this->_contactType;
- $formatValues['version'] = 3;
- $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
+ $error = $this->checkContactDuplicate($formatValues);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
@@ -417,10 +410,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = '';
@@ -509,4 +502,162 @@ public function &getImportedParticipations() {
public function fini() {
}
+ /**
+ * Format values
+ *
+ * @todo lots of tidy up needed here - very old function relocated.
+ *
+ * @param array $values
+ * @param array $params
+ *
+ * @return array|null
+ */
+ protected function formatValues(&$values, $params) {
+ $fields = CRM_Event_DAO_Participant::fields();
+ _civicrm_api3_store_values($fields, $params, $values);
+
+ $customFields = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
+
+ foreach ($params as $key => $value) {
+ // ignore empty values or empty arrays etc
+ if (CRM_Utils_System::isNull($value)) {
+ continue;
+ }
+
+ // Handling Custom Data
+ if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
+ $values[$key] = $value;
+ $type = $customFields[$customFieldID]['html_type'];
+ if ($type == 'CheckBox' || $type == 'Multi-Select') {
+ $mulValues = explode(',', $value);
+ $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
+ $values[$key] = [];
+ foreach ($mulValues as $v1) {
+ foreach ($customOption as $customValueID => $customLabel) {
+ $customValue = $customLabel['value'];
+ if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
+ (strtolower(trim($customValue)) == strtolower(trim($v1)))
+ ) {
+ if ($type == 'CheckBox') {
+ $values[$key][$customValue] = 1;
+ }
+ else {
+ $values[$key][] = $customValue;
+ }
+ }
+ }
+ }
+ }
+ elseif ($type == 'Select' || $type == 'Radio') {
+ $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
+ foreach ($customOption as $customFldID => $customValue) {
+ $val = CRM_Utils_Array::value('value', $customValue);
+ $label = CRM_Utils_Array::value('label', $customValue);
+ $label = strtolower($label);
+ $value = strtolower(trim($value));
+ if (($value == $label) || ($value == strtolower($val))) {
+ $values[$key] = $val;
+ }
+ }
+ }
+ }
+
+ switch ($key) {
+ case 'participant_contact_id':
+ if (!CRM_Utils_Rule::integer($value)) {
+ return civicrm_api3_create_error("contact_id not valid: $value");
+ }
+ if (!CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value")) {
+ return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
+ }
+ $values['contact_id'] = $values['participant_contact_id'];
+ unset($values['participant_contact_id']);
+ break;
+
+ case 'participant_register_date':
+ if (!CRM_Utils_Rule::dateTime($value)) {
+ return civicrm_api3_create_error("$key not a valid date: $value");
+ }
+ break;
+
+ case 'event_title':
+ $id = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
+ $values['event_id'] = $id;
+ break;
+
+ case 'event_id':
+ if (!CRM_Utils_Rule::integer($value)) {
+ return civicrm_api3_create_error("Event ID is not valid: $value");
+ }
+ $dao = new CRM_Core_DAO();
+ $qParams = [];
+ $svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
+ $qParams
+ );
+ if (!$svq) {
+ return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
+ }
+ break;
+
+ case 'participant_status_id':
+ if (!CRM_Utils_Rule::integer($value)) {
+ return civicrm_api3_create_error("Event Status ID is not valid: $value");
+ }
+ break;
+
+ case 'participant_status':
+ $status = CRM_Event_PseudoConstant::participantStatus();
+ $values['participant_status_id'] = CRM_Utils_Array::key($value, $status);;
+ break;
+
+ case 'participant_role_id':
+ case 'participant_role':
+ $role = CRM_Event_PseudoConstant::participantRole();
+ $participantRoles = explode(",", $value);
+ foreach ($participantRoles as $k => $v) {
+ $v = trim($v);
+ if ($key == 'participant_role') {
+ $participantRoles[$k] = CRM_Utils_Array::key($v, $role);
+ }
+ else {
+ $participantRoles[$k] = $v;
+ }
+ }
+ $values['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $participantRoles);
+ unset($values[$key]);
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ if (array_key_exists('participant_note', $params)) {
+ $values['participant_note'] = $params['participant_note'];
+ }
+
+ // CRM_Event_BAO_Participant::create() handles register_date,
+ // status_id and source. So, if $values contains
+ // participant_register_date, participant_status_id or participant_source,
+ // convert it to register_date, status_id or source
+ $changes = [
+ 'participant_register_date' => 'register_date',
+ 'participant_source' => 'source',
+ 'participant_status_id' => 'status_id',
+ 'participant_role_id' => 'role_id',
+ 'participant_fee_level' => 'fee_level',
+ 'participant_fee_amount' => 'fee_amount',
+ 'participant_id' => 'id',
+ ];
+
+ foreach ($changes as $orgVal => $changeVal) {
+ if (isset($values[$orgVal])) {
+ $values[$changeVal] = $values[$orgVal];
+ unset($values[$orgVal]);
+ }
+ }
+
+ return NULL;
+ }
+
}
diff --git a/CRM/Event/Info.php b/CRM/Event/Info.php
index 1c574456b95d..8e3e5338cafa 100644
--- a/CRM/Event/Info.php
+++ b/CRM/Event/Info.php
@@ -1,9 +1,9 @@
'CiviEvent',
'translatedName' => ts('CiviEvent'),
'title' => ts('CiviCRM Event Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -65,39 +66,39 @@ public function getInfo() {
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviEvent' => array(
+ $permissions = [
+ 'access CiviEvent' => [
ts('access CiviEvent'),
ts('Create events, view all events, and view participant records (for visible contacts)'),
- ),
- 'edit event participants' => array(
+ ],
+ 'edit event participants' => [
ts('edit event participants'),
ts('Record and update backend event registrations'),
- ),
- 'edit all events' => array(
+ ],
+ 'edit all events' => [
ts('edit all events'),
ts('Edit events even without specific ACL granted'),
- ),
- 'register for events' => array(
+ ],
+ 'register for events' => [
ts('register for events'),
ts('Register for events online'),
- ),
- 'view event info' => array(
+ ],
+ 'view event info' => [
ts('view event info'),
ts('View online event information pages'),
- ),
- 'view event participants' => array(
+ ],
+ 'view event participants' => [
ts('view event participants'),
- ),
- 'delete in CiviEvent' => array(
+ ],
+ 'delete in CiviEvent' => [
ts('delete in CiviEvent'),
ts('Delete participants and events that you can edit'),
- ),
- 'manage event profiles' => array(
+ ],
+ 'manage event profiles' => [
ts('manage event profiles'),
ts('Allow users to create, edit and copy event-related profile forms used for online event registration.'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -112,9 +113,9 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* @return array
*/
public function getAnonymousPermissionWarnings() {
- return array(
+ return [
'access CiviEvent',
- );
+ ];
}
/**
@@ -122,12 +123,12 @@ public function getAnonymousPermissionWarnings() {
* @return array
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Events'),
'title' => ts('Your Event(s)'),
- 'perm' => array('register for events'),
+ 'perm' => ['register for events'],
'weight' => 20,
- );
+ ];
}
/**
@@ -135,12 +136,20 @@ public function getUserDashboardElement() {
* @return array
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Events'),
'id' => 'participant',
'url' => 'participant',
'weight' => 40,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-calendar';
}
/**
@@ -148,10 +157,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Events'),
'weight' => 40,
- );
+ ];
}
/**
@@ -159,11 +168,11 @@ public function registerAdvancedSearchPane() {
* @return array
*/
public function getActivityTypes() {
- $types = array();
- $types['Event'] = array(
+ $types = [];
+ $types['Event'] = [
'title' => ts('Event'),
'callback' => 'CRM_Event_Page_EventInfo::run()',
- );
+ ];
return $types;
}
@@ -176,20 +185,20 @@ public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviEvent') &&
CRM_Core_Permission::check('edit event participants')
) {
- $shortCut[] = array(
+ $shortCut[] = [
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-participant',
'title' => ts('Event Registration'),
- );
+ ];
if ($newCredit) {
$title = ts('Event Registration') . '
(' . ts('credit card') . ')';
- $shortCut[0]['shortCuts'][] = array(
+ $shortCut[0]['shortCuts'][] = [
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-participant-cc',
'title' => $title,
- );
+ ];
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
diff --git a/CRM/Event/Page/AJAX.php b/CRM/Event/Page/AJAX.php
index 9f9af28663b5..7227988671db 100644
--- a/CRM/Event/Page/AJAX.php
+++ b/CRM/Event/Page/AJAX.php
@@ -1,9 +1,9 @@
fetch()) {
- $results[] = array('id' => $dao->id, 'text' => $dao->label);
+ $results[] = ['id' => $dao->id, 'text' => $dao->label];
}
CRM_Utils_JSON::output($results);
}
diff --git a/CRM/Event/Page/DashBoard.php b/CRM/Event/Page/DashBoard.php
index 745ac1e70cdb..b94825a8f12c 100644
--- a/CRM/Event/Page/DashBoard.php
+++ b/CRM/Event/Page/DashBoard.php
@@ -1,9 +1,9 @@
assign('context', $context);
// Sometimes we want to suppress the Event Full msg
@@ -71,7 +71,7 @@ public function run() {
);
//retrieve event information
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $values['event']);
if (!$values['event']['is_active']) {
@@ -80,6 +80,10 @@ public function run() {
return CRM_Utils_System::permissionDenied();
}
+ if (!$values['event']['is_public']) {
+ CRM_Utils_System::addHTMLHead('');
+ }
+
if (!empty($values['event']['is_template'])) {
// form is an Event Template
CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
@@ -92,12 +96,7 @@ public function run() {
// show event fees.
if ($this->_id && !empty($values['event']['is_monetary'])) {
- //CRM-6907
- $config = CRM_Core_Config::singleton();
- $config->defaultCurrency = CRM_Utils_Array::value('currency',
- $values['event'],
- $config->defaultCurrency
- );
+ CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values['event']);
//CRM-10434
$discountId = CRM_Core_BAO_Discount::findSet($this->_id, 'civicrm_event');
@@ -148,6 +147,12 @@ public function run() {
$displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
foreach ($fieldValues['options'] as $optionId => $optionVal) {
+ if (CRM_Utils_Array::value('visibility_id', $optionVal) != array_search('public', $visibility) &&
+ $adminFieldVisible == FALSE
+ ) {
+ continue;
+ }
+
$values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
if ($invoicing && isset($optionVal['tax_amount'])) {
$values['feeBlock']['value'][$fieldCnt] = CRM_Price_BAO_PriceField::getTaxLabel($optionVal, 'amount', $displayOpt, $taxTerm);
@@ -168,7 +173,7 @@ public function run() {
}
}
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_event'];
$values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
// fix phone type labels
@@ -182,7 +187,7 @@ public function run() {
}
//retrieve custom field information
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_id, 0, $values['event']['event_type_id'], NULL, TRUE, NULL, FALSE, TRUE, NULL, TRUE);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $this->_id, 0, $values['event']['event_type_id'], NULL, TRUE, NULL, FALSE, TRUE, NULL, TRUE);
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->_id);
$this->assign('action', CRM_Core_Action::VIEW);
//To show the event location on maps directly on event info page
@@ -213,14 +218,14 @@ public function run() {
}
}
- $center = array(
+ $center = [
'lat' => (float ) $sumLat / count($locations),
'lng' => (float ) $sumLng / count($locations),
- );
- $span = array(
+ ];
+ $span = [
'lat' => (float ) ($maxLat - $minLat),
'lng' => (float ) ($maxLng - $minLng),
- );
+ ];
$this->assign_by_ref('center', $center);
$this->assign_by_ref('span', $span);
if ($action == CRM_Core_Action::PREVIEW) {
@@ -266,8 +271,9 @@ public function run() {
);
$allowRegistration = FALSE;
+ $isEventOpenForRegistration = CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id);
if (!empty($values['event']['is_online_registration'])) {
- if (CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id)) {
+ if ($isEventOpenForRegistration == 1) {
// we always generate urls for the front end in joomla
$action_query = $action === CRM_Core_Action::PREVIEW ? "&action=$action" : '';
$url = CRM_Utils_System::url('civicrm/event/register',
@@ -306,11 +312,11 @@ public function run() {
$this->assign('allowRegistration', $allowRegistration);
$session = CRM_Core_Session::singleton();
- $params = array(
+ $params = [
'contact_id' => $session->get('userID'),
'event_id' => CRM_Utils_Array::value('id', $values['event']),
'role_id' => CRM_Utils_Array::value('default_role_id', $values['event']),
- );
+ ];
if ($eventFullMessage && ($noFullMsg == 'false') || CRM_Event_BAO_Event::checkRegistration($params)) {
$statusMessage = $eventFullMessage;
@@ -323,7 +329,7 @@ public function run() {
$registerUrl = CRM_Utils_System::url('civicrm/event/register',
"reset=1&id={$values['event']['id']}&cid=0"
);
- $statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', array(1 => $registerUrl));
+ $statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', [1 => $registerUrl]);
}
}
}
@@ -333,8 +339,9 @@ public function run() {
$statusMessage = ts('Event is currently full, but you can register and be a part of waiting list.');
}
}
-
- CRM_Core_Session::setStatus($statusMessage);
+ if ($isEventOpenForRegistration == 1) {
+ CRM_Core_Session::setStatus($statusMessage);
+ }
}
// we do not want to display recently viewed items, so turn off
$this->assign('displayRecent', FALSE);
diff --git a/CRM/Event/Page/ICalendar.php b/CRM/Event/Page/ICalendar.php
index 8cdc8d16dc72..4790280e7d8e 100644
--- a/CRM/Event/Page/ICalendar.php
+++ b/CRM/Event/Page/ICalendar.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Event'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Event'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=delete&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
'title' => ts('Delete Event'),
- ),
- CRM_Core_Action::COPY => array(
+ ],
+ CRM_Core_Action::COPY => [
'name' => ts('Copy'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'reset=1&action=copy&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
'title' => ts('Copy Event'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
+ public function eventLinks() {
+ if (!(self::$_eventLinks)) {
+ self::$_eventLinks = [
+ 'register_participant' => [
+ 'name' => ts('Register Participant'),
+ 'title' => ts('Register Participant'),
+ 'url' => 'civicrm/participant/add',
+ 'qs' => 'reset=1&action=add&context=standalone&eid=%%id%%',
+ ],
+ 'event_info' => [
+ 'name' => ts('Event Info'),
+ 'title' => ts('Event Info'),
+ 'url' => 'civicrm/event/info',
+ 'qs' => 'reset=1&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ 'online_registration_test' => [
+ 'name' => ts('Registration (Test-drive)'),
+ 'title' => ts('Online Registration (Test-drive)'),
+ 'url' => 'civicrm/event/register',
+ 'qs' => 'reset=1&action=preview&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ 'online_registration_live' => [
+ 'name' => ts('Registration (Live)'),
+ 'title' => ts('Online Registration (Live)'),
+ 'url' => 'civicrm/event/register',
+ 'qs' => 'reset=1&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ ];
+ }
+ return self::$_eventLinks;
+ }
+
/**
* Get tab Links for events.
*
@@ -108,74 +149,76 @@ public function &links() {
public static function &tabs($enableCart) {
$cacheKey = $enableCart ? 1 : 0;
if (!(self::$_tabLinks)) {
- self::$_tabLinks = array();
+ self::$_tabLinks = [];
}
if (!isset(self::$_tabLinks[$cacheKey])) {
self::$_tabLinks[$cacheKey]['settings']
- = array(
+ = [
'title' => ts('Info and Settings'),
'url' => 'civicrm/event/manage/settings',
'field' => 'id',
- );
+ ];
self::$_tabLinks[$cacheKey]['location']
- = array(
+ = [
'title' => ts('Location'),
'url' => 'civicrm/event/manage/location',
'field' => 'loc_block_id',
- );
+ ];
self::$_tabLinks[$cacheKey]['fee']
- = array(
+ = [
'title' => ts('Fees'),
'url' => 'civicrm/event/manage/fee',
'field' => 'is_monetary',
- );
+ ];
self::$_tabLinks[$cacheKey]['registration']
- = array(
+ = [
'title' => ts('Online Registration'),
'url' => 'civicrm/event/manage/registration',
'field' => 'is_online_registration',
- );
+ ];
- if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
+ // @fixme I don't understand the event permissions check here - can we just get rid of it?
+ $permissions = CRM_Event_BAO_Event::getAllPermissions();
+ if (CRM_Core_Permission::check('administer CiviCRM') || !empty($permissions[CRM_Core_Permission::EDIT])) {
self::$_tabLinks[$cacheKey]['reminder']
- = array(
+ = [
'title' => ts('Schedule Reminders'),
'url' => 'civicrm/event/manage/reminder',
'field' => 'reminder',
- );
+ ];
}
self::$_tabLinks[$cacheKey]['conference']
- = array(
+ = [
'title' => ts('Conference Slots'),
'url' => 'civicrm/event/manage/conference',
'field' => 'slot_label_id',
- );
+ ];
self::$_tabLinks[$cacheKey]['friend']
- = array(
+ = [
'title' => ts('Tell a Friend'),
'url' => 'civicrm/event/manage/friend',
'field' => 'friend',
- );
+ ];
self::$_tabLinks[$cacheKey]['pcp']
- = array(
+ = [
'title' => ts('Personal Campaign Pages'),
'url' => 'civicrm/event/manage/pcp',
'field' => 'is_pcp_enabled',
- );
+ ];
self::$_tabLinks[$cacheKey]['repeat']
- = array(
+ = [
'title' => ts('Repeat'),
'url' => 'civicrm/event/manage/repeat',
'field' => 'is_repeating_event',
- );
+ ];
}
if (!$enableCart) {
unset(self::$_tabLinks[$cacheKey]['conference']);
}
- CRM_Utils_Hook::tabset('civicrm/event/manage', self::$_tabLinks[$cacheKey], array());
+ CRM_Utils_Hook::tabset('civicrm/event/manage', self::$_tabLinks[$cacheKey], []);
return self::$_tabLinks[$cacheKey];
}
@@ -210,12 +253,12 @@ public function run() {
}
if (!$this->_isTemplate && $id) {
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Events'),
'url' => CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -266,16 +309,19 @@ public function browse() {
$this->search();
- $params = array();
+ $params = [];
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean',
$this, FALSE
);
$this->_searchResult = CRM_Utils_Request::retrieve('searchResult', 'Boolean', $this);
$whereClause = $this->whereClause($params, FALSE, $this->_force);
- $this->pagerAToZ($whereClause, $params);
- $params = array();
+ if (CRM_Core_Config::singleton()->includeAlphabeticalPager) {
+ $this->pagerAToZ($whereClause, $params);
+ }
+
+ $params = [];
$whereClause = $this->whereClause($params, TRUE, $this->_force);
// because is_template != 1 would be to simple
$whereClause .= ' AND (is_template = 0 OR is_template IS NULL)';
@@ -285,7 +331,7 @@ public function browse() {
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
// get all custom groups sorted by weight
- $manageEvent = array();
+ $manageEvent = [];
$query = "
SELECT *
@@ -295,13 +341,13 @@ public function browse() {
LIMIT $offset, $rowCount";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Event_DAO_Event');
- $permissions = CRM_Event_BAO_Event::checkPermission();
+ $permittedEventsByAction = CRM_Event_BAO_Event::getAllPermissions();
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// get the list of active event pcps
- $eventPCPS = array();
+ $eventPCPS = [];
$pcpDao = new CRM_PCP_DAO_PCPBlock();
$pcpDao->entity_table = 'civicrm_event';
@@ -313,17 +359,17 @@ public function browse() {
// check if we're in shopping cart mode for events
$enableCart = Civi::settings()->get('enable_cart');
$this->assign('eventCartEnabled', $enableCart);
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
+ ]));
$eventType = CRM_Core_OptionGroup::values('event_type');
while ($dao->fetch()) {
- if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
- $manageEvent[$dao->id] = array();
+ if (in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::VIEW])) {
+ $manageEvent[$dao->id] = [];
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($dao->id, 'civicrm_event');
$manageEvent[$dao->id]['repeat'] = '';
if ($repeat) {
- $manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
+ $manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
}
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
@@ -337,16 +383,30 @@ public function browse() {
$action -= CRM_Core_Action::DISABLE;
}
- if (!in_array($dao->id, $permissions[CRM_Core_Permission::DELETE])) {
+ if (!in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::DELETE])) {
$action -= CRM_Core_Action::DELETE;
}
- if (!in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
+ if (!in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::EDIT])) {
$action -= CRM_Core_Action::UPDATE;
}
+ $eventLinks = self::eventLinks();
+ if (!CRM_Core_Permission::check('edit event participants')) {
+ unset($eventLinks['register_participant']);
+ }
+
+ $manageEvent[$dao->id]['eventlinks'] = CRM_Core_Action::formLink($eventLinks,
+ NULL,
+ ['id' => $dao->id],
+ ts('Event Links'),
+ TRUE,
+ 'event.manage.eventlinks',
+ 'Event',
+ $dao->id
+ );
$manageEvent[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(),
$action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
TRUE,
'event.manage.list',
@@ -354,11 +414,11 @@ public function browse() {
$dao->id
);
- $params = array(
+ $params = [
'entity_id' => $dao->id,
'entity_table' => 'civicrm_event',
'is_active' => 1,
- );
+ ];
$defaults['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
@@ -378,7 +438,7 @@ public function browse() {
$manageEvent[$dao->id]['event_type'] = CRM_Utils_Array::value($manageEvent[$dao->id]['event_type_id'], $eventType);
$manageEvent[$dao->id]['is_repeating_event'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_RecurringEntity', $dao->id, 'parent_id', 'entity_id');
// allow hooks to set 'field' value which allows configuration pop-up to show a tab as enabled/disabled
- CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, array('event_id' => $dao->id));
+ CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, ['event_id' => $dao->id]);
}
}
@@ -397,6 +457,7 @@ public function browse() {
* all the fields in the event wizard
*
* @return void
+ * @throws \CRM_Core_Exception
*/
public function copy() {
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE, 0, 'GET');
@@ -437,8 +498,8 @@ public function search() {
* @return string
*/
public function whereClause(&$params, $sortBy = TRUE, $force) {
- $values = array();
- $clauses = array();
+ $values = [];
+ $clauses = [];
$title = $this->get('title');
$createdId = $this->get('cid');
@@ -449,10 +510,10 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
if ($title) {
$clauses[] = "title LIKE %1";
if (strpos($title, '%') !== FALSE) {
- $params[1] = array(trim($title), 'String', FALSE);
+ $params[1] = [trim($title), 'String', FALSE];
}
else {
- $params[1] = array(trim($title), 'String', TRUE);
+ $params[1] = [trim($title), 'String', TRUE];
}
}
@@ -461,7 +522,8 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
if (is_array($value)) {
$type = implode(',', $value);
}
- $clauses[] = "event_type_id IN ({$type})";
+ $clauses[] = "event_type_id IN (%2)";
+ $params[2] = [$type, 'String'];
}
$eventsByDates = $this->get('eventsByDates');
@@ -471,13 +533,13 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
$from = $this->get('start_date');
if (!CRM_Utils_System::isNull($from)) {
$clauses[] = '( end_date >= %3 OR end_date IS NULL )';
- $params[3] = array($from, 'String');
+ $params[3] = [$from, 'String'];
}
$to = $this->get('end_date');
if (!CRM_Utils_System::isNull($to)) {
$clauses[] = '( start_date <= %4 OR start_date IS NULL )';
- $params[4] = array($to, 'String');
+ $params[4] = [$to, 'String'];
}
}
else {
@@ -499,7 +561,7 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
$campaignIds = $this->get('campaign_id');
if (!CRM_Utils_System::isNull($campaignIds)) {
if (!is_array($campaignIds)) {
- $campaignIds = array($campaignIds);
+ $campaignIds = [$campaignIds];
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campaignIds)) . ' ) )';
}
diff --git a/CRM/Event/Page/ParticipantListing.php b/CRM/Event/Page/ParticipantListing.php
index abaf12c7c625..e58790c2a115 100644
--- a/CRM/Event/Page/ParticipantListing.php
+++ b/CRM/Event/Page/ParticipantListing.php
@@ -1,9 +1,9 @@
preProcess();
// get the class name from the participantListingID
- $className = CRM_Core_OptionGroup::getValue('participant_listing',
- $this->_participantListingID,
- 'value',
- 'Integer',
- 'description'
+ $className = CRM_Utils_Array::value($this->_participantListingID,
+ CRM_Core_PseudoConstant::get(
+ 'CRM_Event_BAO_Event',
+ 'participant_listing_id',
+ ['keyColumn' => 'value', 'labelColumn' => 'description']
+ )
);
-
if ($className == 'CRM_Event_Page_ParticipantListing') {
CRM_Core_Error::fatal(ts("Participant listing code file cannot be '%1'",
array(1 => $className)
diff --git a/CRM/Event/Page/ParticipantListing/Name.php b/CRM/Event/Page/ParticipantListing/Name.php
index c32386279375..d21bcddaef25 100644
--- a/CRM/Event/Page/ParticipantListing/Name.php
+++ b/CRM/Event/Page/ParticipantListing/Name.php
@@ -1,9 +1,9 @@
_participantListingType = 'Name';
diff --git a/CRM/Event/Page/ParticipantListing/NameAndEmail.php b/CRM/Event/Page/ParticipantListing/NameAndEmail.php
index 4fd01ed5c803..0b4c586936bc 100644
--- a/CRM/Event/Page/ParticipantListing/NameAndEmail.php
+++ b/CRM/Event/Page/ParticipantListing/NameAndEmail.php
@@ -1,9 +1,9 @@
_participantListingType = 'Name and Email';
diff --git a/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php b/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
index 585814f2c80f..e7b81bc3b05d 100644
--- a/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
+++ b/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
@@ -1,9 +1,9 @@
_id,
'title'
);
- CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Participants', [1 => $this->_eventTitle]));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
@@ -80,7 +80,7 @@ public function run() {
$whereClause = "
WHERE civicrm_event.id = %1";
- $params = array(1 => array($this->_id, 'Integer'));
+ $params = [1 => [$this->_id, 'Integer']];
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
@@ -98,21 +98,18 @@ public function run() {
ORDER BY $orderBy
LIMIT $offset, $rowCount";
- $rows = array();
+ $rows = [];
$object = CRM_Core_DAO::executeQuery($query, $params);
- $statusLookup = CRM_Event_PseudoConstant::participantStatus();
+ $statusLookup = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
while ($object->fetch()) {
$status = CRM_Utils_Array::value($object->status_id, $statusLookup);
- if ($status) {
- $status = ts($status);
- }
- $row = array(
+ $row = [
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'status' => $status,
'date' => $object->register_date,
- );
+ ];
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
@@ -127,7 +124,7 @@ public function run() {
*/
public function pager($fromClause, $whereClause, $whereParams) {
- $params = array();
+ $params = [];
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
@@ -154,22 +151,22 @@ public function pager($fromClause, $whereClause, $whereParams) {
public function orderBy() {
static $headers = NULL;
if (!$headers) {
- $headers = array();
- $headers[1] = array(
+ $headers = [];
+ $headers[1] = [
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- );
- $headers[2] = array(
+ ];
+ $headers[2] = [
'name' => ts('Status'),
'sort' => 'civicrm_participant.status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
- $headers[3] = array(
+ ];
+ $headers[3] = [
'name' => ts('Register Date'),
'sort' => 'civicrm_participant.register_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
+ ];
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
diff --git a/CRM/Event/Page/ParticipantListing/Simple.php b/CRM/Event/Page/ParticipantListing/Simple.php
index 3f7f75957e2a..c2db2255ee19 100644
--- a/CRM/Event/Page/ParticipantListing/Simple.php
+++ b/CRM/Event/Page/ParticipantListing/Simple.php
@@ -1,9 +1,9 @@
_id,
'title'
);
- CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Participants', [1 => $this->_eventTitle]));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
@@ -74,7 +74,7 @@ public function run() {
WHERE civicrm_event.id = %1
AND civicrm_participant.is_test = 0
AND civicrm_participant.status_id IN ( 1, 2 )";
- $params = array(1 => array($this->_id, 'Integer'));
+ $params = [1 => [$this->_id, 'Integer']];
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
@@ -91,15 +91,15 @@ public function run() {
ORDER BY $orderBy
LIMIT $offset, $rowCount";
- $rows = array();
+ $rows = [];
$object = CRM_Core_DAO::executeQuery($query, $params);
while ($object->fetch()) {
- $row = array(
+ $row = [
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'email' => $object->email,
- );
+ ];
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
@@ -114,7 +114,7 @@ public function run() {
*/
public function pager($fromClause, $whereClause, $whereParams) {
- $params = array();
+ $params = [];
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
@@ -142,18 +142,18 @@ public function pager($fromClause, $whereClause, $whereParams) {
public function orderBy() {
static $headers = NULL;
if (!$headers) {
- $headers = array();
- $headers[1] = array(
+ $headers = [];
+ $headers[1] = [
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- );
+ ];
if ($this->_participantListingType == 'Name and Email') {
- $headers[2] = array(
+ $headers[2] = [
'name' => ts('Email'),
'sort' => 'civicrm_email.email',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
+ ];
}
}
$sortID = NULL;
diff --git a/CRM/Event/Page/Tab.php b/CRM/Event/Page/Tab.php
index 7dd25d396afb..dadc9244d9e6 100644
--- a/CRM/Event/Page/Tab.php
+++ b/CRM/Event/Page/Tab.php
@@ -1,9 +1,9 @@
assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
- );
+ ];
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
@@ -95,7 +95,7 @@ public function view() {
*/
public function edit() {
// set https for offline cc transaction
- $mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
@@ -118,8 +118,21 @@ public function edit() {
return $controller->run();
}
+ public function delete() {
+ $controller = new CRM_Core_Controller_Simple(
+ 'CRM_Event_Form_Participant',
+ ts('Delete Participant'),
+ $this->_action
+ );
+
+ $controller->setEmbedded(TRUE);
+ $controller->set('id', $this->_id);
+ $controller->set('cid', $this->_contactId);
+ $controller->run();
+ }
+
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -167,13 +180,12 @@ public function run() {
if ($this->_action & CRM_Core_Action::VIEW) {
$this->view();
}
- elseif ($this->_action & (CRM_Core_Action::UPDATE |
- CRM_Core_Action::ADD |
- CRM_Core_Action::DELETE
- )
- ) {
+ elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
$this->edit();
}
+ elseif ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH)) {
+ $this->delete();
+ }
else {
$this->browse();
}
diff --git a/CRM/Event/Page/UserDashboard.php b/CRM/Event/Page/UserDashboard.php
index 23cf548d2675..5658480907ce 100644
--- a/CRM/Event/Page/UserDashboard.php
+++ b/CRM/Event/Page/UserDashboard.php
@@ -1,9 +1,9 @@
ts('Positive'),
'Pending' => ts('Pending'),
'Waiting' => ts('Waiting'),
'Negative' => ts('Negative'),
- );
+ ];
}
/**
@@ -193,13 +193,13 @@ public static function &participantStatusClass() {
* @param int $id
* @param null $cond
*
- * @return array
+ * @return array|string
* array reference of all participant roles if any
*/
public static function &participantRole($id = NULL, $cond = NULL) {
$index = $cond ? $cond : 'No Condition';
if (!CRM_Utils_Array::value($index, self::$participantRole)) {
- self::$participantRole[$index] = array();
+ self::$participantRole[$index] = [];
$condition = NULL;
@@ -224,12 +224,12 @@ public static function &participantRole($id = NULL, $cond = NULL) {
*
* @param int $id
*
- * @return array
+ * @return array|string
* array reference of all participant listings if any
*/
public static function &participantListing($id = NULL) {
if (!self::$participantListing) {
- self::$participantListing = array();
+ self::$participantListing = [];
self::$participantListing = CRM_Core_OptionGroup::values('participant_listing');
}
@@ -245,12 +245,12 @@ public static function &participantListing($id = NULL) {
*
*
* @param int $id
- * @return array
+ * @return array|string
* array reference of all event types.
*/
public static function &eventType($id = NULL) {
if (!self::$eventType) {
- self::$eventType = array();
+ self::$eventType = [];
self::$eventType = CRM_Core_OptionGroup::values('event_type');
}
diff --git a/CRM/Event/Selector/Search.php b/CRM/Event/Selector/Search.php
index bdef479abbdf..b484e7dd06c4 100644
--- a/CRM/Event/Selector/Search.php
+++ b/CRM/Event/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=event' . $extraParams,
'title' => ts('View Participation'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Participation'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Participation'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -313,10 +313,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$this->_eventClause
);
// process the result of the query
- $rows = array();
+ $rows = [];
//lets handle view, edit and delete separately. CRM-4418
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit event participants')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -334,7 +334,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -342,6 +342,12 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
}
+ // Skip registration if event_id is NULL
+ if (empty($row['event_id'])) {
+ Civi::log()->warning('Participant record without event ID. You have invalid data in your database!');
+ continue;
+ }
+
//carry campaign on selectors.
$row['campaign'] = CRM_Utils_Array::value($result->participant_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->participant_campaign_id;
@@ -357,45 +363,59 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['showConfirmUrl'] = ($statusClass == 'Pending') ? TRUE : FALSE;
if (!empty($row['participant_is_test'])) {
- $row['participant_status'] .= ' (' . ts('test') . ')';
+ $row['participant_status'] = CRM_Core_TestEntity::appendTestText($row['participant_status']);
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
$links = self::links($this->_key, $this->_context, $this->_compContext);
if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => ts('Record Payment'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Payment'),
- );
+ ];
if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
- $links[CRM_Core_Action::BASIC] = array(
+ $links[CRM_Core_Action::BASIC] = [
'name' => ts('Submit Credit Card payment'),
'url' => 'civicrm/payment/add',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event&mode=live',
'title' => ts('Submit Credit Card payment'),
- );
+ ];
}
}
if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => ts('Record Refund'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Refund'),
- );
+ ];
+ }
+
+ // CRM-20879: Show 'Transfer or Cancel' action only if logged in user
+ // have 'edit event participants' permission and participant status
+ // is not Cancelled or Transferred
+ if (in_array(CRM_Core_Permission::EDIT, $permissions) &&
+ !in_array($statusTypes[$row['participant_status_id']], ['Cancelled', 'Transferred'])
+ ) {
+ $links[] = [
+ 'name' => ts('Transfer or Cancel'),
+ 'url' => 'civicrm/event/selfsvcupdate',
+ 'qs' => 'reset=1&pid=%%id%%&is_backoffice=1&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($result->contact_id, NULL, 'inf'),
+ 'title' => ts('Transfer or Cancel'),
+ ];
}
$row['action'] = CRM_Core_Action::formLink($links,
$mask,
- array(
+ [
'id' => $result->participant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'participant.selector.row',
@@ -418,7 +438,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
if (!empty($row['participant_role_id'])) {
- $viewRoles = array();
+ $viewRoles = [];
foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
@@ -452,54 +472,54 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Event'),
'sort' => 'event_title',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Fee Level'),
'sort' => 'participant_fee_level',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Amount'),
'sort' => 'participant_fee_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Registered'),
'sort' => 'participant_register_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Event Date(s)'),
'sort' => 'event_start_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'participant_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Role'),
'sort' => 'participant_role_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Participant'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
@@ -510,7 +530,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Event/StateMachine/Registration.php b/CRM/Event/StateMachine/Registration.php
index 0df4e4925d2b..d3120fb61c34 100644
--- a/CRM/Event/StateMachine/Registration.php
+++ b/CRM/Event/StateMachine/Registration.php
@@ -1,9 +1,9 @@
NULL);
+ $pages = ['CRM_Event_Form_Registration_Register' => NULL];
//handle additional participant scenario, where we need to insert participant pages on runtime
$additionalParticipant = NULL;
@@ -83,10 +83,10 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
$pages = array_merge($pages, $extraPages);
}
- $additionalPages = array(
+ $additionalPages = [
'CRM_Event_Form_Registration_Confirm' => NULL,
'CRM_Event_Form_Registration_ThankYou' => NULL,
- );
+ ];
$pages = array_merge($pages, $additionalPages);
diff --git a/CRM/Event/StateMachine/Search.php b/CRM/Event/StateMachine/Search.php
index c4ca4e7d5be9..f31b006fbadc 100644
--- a/CRM/Event/StateMachine/Search.php
+++ b/CRM/Event/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Event_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -82,7 +82,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Event/Task.php b/CRM/Event/Task.php
index 4bc04bf7bd55..82afc9194757 100644
--- a/CRM/Event/Task.php
+++ b/CRM/Event/Task.php
@@ -1,9 +1,9 @@
The Task title,
+ * 'class' => The Task Form class name,
+ * 'result => Boolean. FIXME: Not sure what this is for
+ * ]
*/
- public static function &tasks() {
- if (!(self::$_tasks)) {
- self::$_tasks = array(
- 1 => array(
+ public static function tasks() {
+ if (!self::$_tasks) {
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete participants from event'),
'class' => 'CRM_Event_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Event_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export participants'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple participants'),
- 'class' => array(
+ 'class' => [
'CRM_Event_Form_Task_PickProfile',
'CRM_Event_Form_Task_Batch',
- ),
+ ],
'result' => TRUE,
- ),
- 5 => array(
+ ],
+ self::CANCEL_REGISTRATION => [
'title' => ts('Cancel registration'),
'class' => 'CRM_Event_Form_Task_Cancel',
'result' => FALSE,
- ),
- 6 => array(
- 'title' => ts('Email - send now'),
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
'class' => 'CRM_Event_Form_Task_Email',
'result' => TRUE,
- ),
- 13 => array(
+ ],
+ self::SAVE_SEARCH => [
'title' => ts('Group - create smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch',
'result' => TRUE,
- ),
- 14 => array(
+ ],
+ self::SAVE_SEARCH_UPDATE => [
'title' => ts('Group - update smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch_Update',
'result' => TRUE,
- ),
- 15 => array(
+ ],
+ self::PARTICIPANT_STATUS => [
'title' => ts('Participant status - change'),
'class' => 'CRM_Event_Form_Task_ParticipantStatus',
'result' => TRUE,
- ),
- 16 => array(
+ ],
+ self::LABEL_CONTACTS => [
'title' => ts('Name badges - print'),
'class' => 'CRM_Event_Form_Task_Badge',
'result' => FALSE,
- ),
- 17 => array(
+ ],
+ self::PDF_LETTER => [
'title' => ts('PDF letter - print for participants'),
'class' => 'CRM_Event_Form_Task_PDF',
'result' => TRUE,
- ),
- 20 => array(
+ ],
+ self::GROUP_ADD => [
'title' => ts('Group - add contacts'),
'class' => 'CRM_Event_Form_Task_AddToGroup',
'result' => FALSE,
- ),
- );
+ ],
+ ];
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviEvent')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit event participants')) {
- unset(self::$_tasks[4], self::$_tasks[5], self::$_tasks[15]);
+ unset(self::$_tasks[self::BATCH_UPDATE], self::$_tasks[self::CANCEL_REGISTRATION], self::$_tasks[self::PARTICIPANT_STATUS]);
}
- CRM_Utils_Hook::searchTasks('event', self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- * for participants
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- // skip Update Smart Group task
- if ($id != self::SAVE_SEARCH_UPDATE) {
- $titles[$id] = $value['title'];
- }
- }
- return $titles;
- }
-
- /**
- * These tasks get added based on the context the user is in.
- *
- * @return array
- * the set of optional tasks for a group of contacts
- */
- public static function &optionalTaskTitle() {
- $tasks = array(
- 14 => self::$_tasks[14]['title'],
- );
- return $tasks;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit event participants')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- 6 => self::$_tasks[6]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ self::TASK_EMAIL => self::$_tasks[self::TASK_EMAIL]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviEvent')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -227,13 +195,9 @@ public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
- $value = 2;
+ $value = self::TASK_PRINT;
}
- asort(self::$_tasks);
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Event/Tokens.php b/CRM/Event/Tokens.php
index e947ade45f79..1f1b1f716e68 100644
--- a/CRM/Event/Tokens.php
+++ b/CRM/Event/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -45,7 +45,7 @@ class CRM_Event_Tokens extends \Civi\Token\AbstractTokenSubscriber {
*/
public function __construct() {
parent::__construct('event', array_merge(
- array(
+ [
'event_type' => ts('Event Type'),
'title' => ts('Event Title'),
'event_id' => ts('Event ID'),
@@ -60,8 +60,8 @@ public function __construct() {
'contact_email' => ts('Event Contact (Email)'),
'contact_phone' => ts('Event Contact (Phone)'),
'balance' => ts('Event Balance'),
- ),
- $this->getCustomTokens('Event')
+ ],
+ CRM_Utils_Token::getCustomFieldTokens('Event')
));
}
@@ -70,8 +70,7 @@ public function __construct() {
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_participant';
}
@@ -85,7 +84,8 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
return;
}
- $e->query->select('e.*'); // FIXME: seems too broad.
+ // FIXME: seems too broad.
+ $e->query->select('e.*');
$e->query->select('ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone');
$e->query->join('participant_stuff', "
!casMailingJoinType civicrm_event ev ON e.event_id = ev.id
@@ -105,7 +105,7 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
$actionSearchResult = $row->context['actionSearchResult'];
if ($field == 'location') {
- $loc = array();
+ $loc = [];
$stateProvince = \CRM_Core_PseudoConstant::stateProvince();
$loc['street_address'] = $actionSearchResult->street_address;
$loc['city'] = $actionSearchResult->city;
@@ -122,7 +122,7 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
$row
->tokens($entity, $field, \CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $actionSearchResult->event_id, TRUE, NULL, FALSE));
}
- elseif (in_array($field, array('start_date', 'end_date'))) {
+ elseif (in_array($field, ['start_date', 'end_date'])) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
elseif ($field == 'balance') {
diff --git a/CRM/Event/xml/Menu/Event.xml b/CRM/Event/xml/Menu/Event.xml
index f9d1d464eff6..c9cc60728751 100644
--- a/CRM/Event/xml/Menu/Event.xml
+++ b/CRM/Event/xml/Menu/Event.xml
@@ -138,7 +138,7 @@
');
$this->addElement('select', 'additional_group', ts('Additional Group for Export'),
- array('' => ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup(),
- array('class' => 'crm-select2 huge')
+ ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup(),
+ ['class' => 'crm-select2 huge']
);
}
$this->buildMapping();
- $this->setDefaults(array(
+ $this->setDefaults([
'exportOption' => self::EXPORT_ALL,
'mergeOption' => self::EXPORT_MERGE_DO_NOT_MERGE,
- ));
-
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Export_Form_Select', 'formRule'), $this);
+ ]);
+
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Export_Form_Select', 'formRule'], $this);
}
/**
@@ -349,16 +344,16 @@ public function buildQuickForm() {
* @return bool|array
* mixed true or array of errors
*/
- static public function formRule($params, $files, $self) {
- $errors = array();
+ public static function formRule($params, $files, $self) {
+ $errors = [];
if (CRM_Utils_Array::value('mergeOption', $params) == self::EXPORT_MERGE_SAME_ADDRESS &&
$self->_matchingContacts
) {
- $greetings = array(
+ $greetings = [
'postal_greeting' => 'postal_greeting_other',
'addressee' => 'addressee_other',
- );
+ ];
foreach ($greetings as $key => $value) {
$otherOption = CRM_Utils_Array::value($key, $params);
@@ -366,7 +361,7 @@ static public function formRule($params, $files, $self) {
if ((CRM_Utils_Array::value($otherOption, $self->_greetingOptions[$key]) == ts('Other')) && empty($params[$value])) {
$label = ucwords(str_replace('_', ' ', $key));
- $errors[$value] = ts('Please enter a value for %1 (merging > 2 contacts), or select a pre-configured option from the list.', array(1 => $label));
+ $errors[$value] = ts('Please enter a value for %1 (when merging contacts), or select a pre-configured option from the list.', [1 => $label]);
}
}
}
@@ -377,7 +372,7 @@ static public function formRule($params, $files, $self) {
/**
* Process the uploaded file.
*
- * @return void
+ * @throws \CRM_Core_Exception
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
@@ -393,22 +388,6 @@ public function postProcess() {
// all submitted options or any other argument
$exportParams = $params;
- if (!empty($this->_greetingOptions)) {
- foreach ($this->_greetingOptions as $key => $value) {
- if ($option = CRM_Utils_Array::value($key, $exportParams)) {
- if ($this->_greetingOptions[$key][$option] == ts('Other')) {
- $exportParams[$key] = $exportParams["{$key}_other"];
- }
- elseif ($this->_greetingOptions[$key][$option] == ts('List of names')) {
- $exportParams[$key] = '';
- }
- else {
- $exportParams[$key] = $this->_greetingOptions[$key][$option];
- }
- }
- }
- }
-
$mappingId = CRM_Utils_Array::value('mapping', $params);
if ($mappingId) {
$this->set('mappingId', $mappingId);
@@ -420,7 +399,7 @@ public function postProcess() {
if ($exportOption == self::EXPORT_ALL) {
CRM_Export_BAO_Export::exportComponents($this->_selectAll,
$this->_componentIds,
- $this->get('queryParams'),
+ (array) $this->get('queryParams'),
$this->get(CRM_Utils_Sort::SORT_ORDER),
NULL,
$this->get('returnProperties'),
@@ -485,12 +464,11 @@ public function buildMapping() {
break;
}
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', $exportType, 'name');
- $this->set('mappingTypeId', $mappingTypeId);
+ $this->set('mappingTypeId', CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', $exportType));
- $mappings = CRM_Core_BAO_Mapping::getMappings($mappingTypeId);
+ $mappings = CRM_Core_BAO_Mapping::getMappings($exportType, TRUE);
if (!empty($mappings)) {
- $this->add('select', 'mapping', ts('Use Saved Field Mapping'), array('' => '-select-') + $mappings);
+ $this->add('select2', 'mapping', ts('Use Saved Field Mapping'), $mappings, FALSE, ['placeholder' => ts('- select -')]);
}
}
@@ -498,22 +476,22 @@ public function buildMapping() {
* @return array
*/
public static function getGreetingOptions() {
- $options = array();
- $greetings = array(
+ $options = [];
+ $greetings = [
'postal_greeting' => 'postal_greeting_other',
'addressee' => 'addressee_other',
- );
+ ];
foreach ($greetings as $key => $value) {
- $params = array();
+ $params = [];
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $key, 'id', 'name');
CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_OptionValue', 'option_group_id', $optionGroupId,
- $params, array('label', 'filter')
+ $params, ['label', 'filter']
);
$greetingCount = 1;
- $options[$key] = array("$greetingCount" => ts('List of names'));
+ $options[$key] = ["$greetingCount" => ts('List of names')];
foreach ($params as $id => $field) {
if (CRM_Utils_Array::value('filter', $field) == 4) {
@@ -527,4 +505,13 @@ public static function getGreetingOptions() {
return $options;
}
+ /**
+ * Get the query mode (eg. CRM_Core_BAO_Query::MODE_CASE)
+ *
+ * @return int
+ */
+ public function getQueryMode() {
+ return (int) ($this->queryMode ?: $this->controller->get('component_mode'));
+ }
+
}
diff --git a/CRM/Export/Form/Select/Case.php b/CRM/Export/Form/Select/Case.php
new file mode 100644
index 000000000000..3c09b2645197
--- /dev/null
+++ b/CRM/Export/Form/Select/Case.php
@@ -0,0 +1,53 @@
+_pages = [
+ 'CRM_Export_Form_Select' => NULL,
+ 'CRM_Export_Form_Map' => NULL,
+ ];
+
+ $this->addSequentialPages($this->_pages, $action);
+ }
+
+ /**
+ * @todo So far does nothing.
+ *
+ * @return string
+ */
+ public function getTaskFormName() {
+ return '';
+ }
+
+ /**
+ * @todo not sure if this is needed
+ */
+ public function shouldReset() {
+ return FALSE;
+ }
+
+}
diff --git a/CRM/Extension/Browser.php b/CRM/Extension/Browser.php
index 82d8f47606ba..15b5a84c558f 100644
--- a/CRM/Extension/Browser.php
+++ b/CRM/Extension/Browser.php
@@ -1,9 +1,9 @@
buildClassLoader()->register();
}
@@ -114,7 +114,7 @@ public function buildClassLoader() {
foreach ($info->classloader as $mapping) {
switch ($mapping['type']) {
case 'psr4':
- $loader->setPsr4($mapping['prefix'], $path . '/' . $mapping['path']);
+ $loader->addPsr4($mapping['prefix'], $path . '/' . $mapping['path']);
break;
}
$result[] = $mapping;
@@ -146,7 +146,7 @@ public function refresh() {
*/
protected function getCacheFile() {
$envId = \CRM_Core_Config_Runtime::getId();
- $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedExtLoader.{$envId}.php";
+ $file = \Civi::paths()->getPath("[civicrm.compile]/CachedExtLoader.{$envId}.php");
return $file;
}
diff --git a/CRM/Extension/Container/Basic.php b/CRM/Extension/Container/Basic.php
index 1988de4ad587..3251722565e7 100644
--- a/CRM/Extension/Container/Basic.php
+++ b/CRM/Extension/Container/Basic.php
@@ -1,9 +1,9 @@
baseDir) || !is_dir($this->baseDir)) {
- $errors[] = array(
+ $errors[] = [
'title' => ts('Invalid Base Directory'),
'message' => ts('An extension container has been defined with a blank directory.'),
- );
+ ];
}
if (empty($this->baseUrl)) {
- $errors[] = array(
+ $errors[] = [
'title' => ts('Invalid Base URL'),
'message' => ts('An extension container has been defined with a blank URL.'),
- );
+ ];
}
return $errors;
@@ -146,10 +154,10 @@ public function getResUrl($key) {
if (!$this->baseUrl) {
CRM_Core_Session::setStatus(
ts('Failed to determine URL for extension (%1). Please update Resource URLs.',
- array(
+ [
1 => $key,
2 => CRM_Utils_System::url('civicrm/admin/setting/url', 'reset=1'),
- )
+ ]
)
);
}
@@ -202,7 +210,7 @@ protected function getRelPaths() {
$this->relPaths = $this->cache->get($this->cacheKey);
}
if (!is_array($this->relPaths)) {
- $this->relPaths = array();
+ $this->relPaths = [];
$infoPaths = CRM_Utils_File::findFiles($this->baseDir, 'info.xml');
foreach ($infoPaths as $infoPath) {
$relPath = CRM_Utils_File::relativize(dirname($infoPath), $this->baseDir);
@@ -210,13 +218,22 @@ protected function getRelPaths() {
$info = CRM_Extension_Info::loadFromFile($infoPath);
}
catch (CRM_Extension_Exception_ParseException $e) {
- CRM_Core_Session::setStatus(ts('Parse error in extension: %1', array(
+ CRM_Core_Session::setStatus(ts('Parse error in extension: %1', [
1 => $e->getMessage(),
- )), '', 'error');
+ ]), '', 'error');
CRM_Core_Error::debug_log_message("Parse error in extension: " . $e->getMessage());
continue;
}
- $this->relPaths[$info->key] = $relPath;
+ $visible = TRUE;
+ foreach ($this->filters as $filter) {
+ if (!$filter($info)) {
+ $visible = FALSE;
+ break;
+ }
+ }
+ if ($visible) {
+ $this->relPaths[$info->key] = $relPath;
+ }
}
if ($this->cache) {
$this->cache->set($this->cacheKey, $this->relPaths);
@@ -259,6 +276,20 @@ protected function getRelUrls() {
return $this->relUrls;
}
+ /**
+ * Register a filter which determine whether a copy of an extension
+ * appears as available.
+ *
+ * @param callable $callable
+ * function(CRM_Extension_Info $info): bool
+ * Each function returns TRUE if the extension should be visible.
+ * @return $this
+ */
+ public function addFilter($callable) {
+ $this->filters[] = $callable;
+ return $this;
+ }
+
/**
* Convert a list of relative paths to relative URLs.
*
@@ -272,7 +303,7 @@ protected function getRelUrls() {
* Array($key => $relUrl).
*/
public static function convertPathsToUrls($dirSep, $relPaths) {
- $relUrls = array();
+ $relUrls = [];
foreach ($relPaths as $key => $relPath) {
$relUrls[$key] = str_replace($dirSep, '/', $relPath);
}
diff --git a/CRM/Extension/Container/Collection.php b/CRM/Extension/Container/Collection.php
index 91169296052f..898361cc3e1a 100644
--- a/CRM/Extension/Container/Collection.php
+++ b/CRM/Extension/Container/Collection.php
@@ -1,9 +1,9 @@
CRM_Extension_Container_Interface)
+ * Containers.
+ *
+ * Format is [$name => CRM_Extension_Container_Interface]
+ *
+ * @var array
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $containers;
/**
- * @var CRM_Utils_Cache_Interface|NULL
+ * @var CRM_Utils_Cache_Interface|null
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $cache;
/**
- * @var string the cache key used for any data stored by this container
+ * The cache key used for any data stored by this container.
+ *
+ * @var string
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $cacheKey;
/**
- * @var array ($key => $containerName)
+ * K2C ....
+ *
+ * Format is ($key => $containerName).
+ *
+ * @var array
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $k2c;
/**
+ * Class constructor.
+ *
* @param array $containers
* Array($name => CRM_Extension_Container_Interface) in order from highest
* priority (winners) to lowest priority (losers).
@@ -85,7 +97,7 @@ public function __construct($containers, CRM_Utils_Cache_Interface $cache = NULL
* @return array
*/
public function checkRequirements() {
- $errors = array();
+ $errors = [];
foreach ($this->containers as $container) {
$errors = array_merge($errors, $container->checkRequirements());
}
@@ -95,7 +107,7 @@ public function checkRequirements() {
/**
* @inheritDoc
*
- * @return array_keys
+ * @return array
*/
public function getKeys() {
$k2c = $this->getKeysToContainer();
@@ -106,6 +118,8 @@ public function getKeys() {
* @inheritDoc
*
* @param string $key
+ *
+ * @throws \CRM_Extension_Exception_MissingException
*/
public function getPath($key) {
return $this->getContainer($key)->getPath($key);
@@ -115,6 +129,8 @@ public function getPath($key) {
* @inheritDoc
*
* @param string $key
+ *
+ * @throws \CRM_Extension_Exception_MissingException
*/
public function getResUrl($key) {
return $this->getContainer($key)->getResUrl($key);
@@ -163,7 +179,7 @@ public function getKeysToContainer() {
$k2c = $this->cache->get($this->cacheKey);
}
if (!isset($k2c) || !is_array($k2c)) {
- $k2c = array();
+ $k2c = [];
$containerNames = array_reverse(array_keys($this->containers));
foreach ($containerNames as $name) {
$keys = $this->containers[$name]->getKeys();
diff --git a/CRM/Extension/Container/Default.php b/CRM/Extension/Container/Default.php
index 4b3f2be9a446..674e46584df0 100644
--- a/CRM/Extension/Container/Default.php
+++ b/CRM/Extension/Container/Default.php
@@ -1,9 +1,9 @@
array $spec) List of extensions.
@@ -47,7 +48,7 @@ public function __construct($exts) {
* @inheritDoc
*/
public function checkRequirements() {
- return array();
+ return [];
}
/**
diff --git a/CRM/Extension/Downloader.php b/CRM/Extension/Downloader.php
index e071841ee6f7..2e5a19060ac4 100644
--- a/CRM/Extension/Downloader.php
+++ b/CRM/Extension/Downloader.php
@@ -1,9 +1,9 @@
containerDir || !is_dir($this->containerDir) || !is_writable($this->containerDir)) {
@@ -88,6 +90,18 @@ public function checkRequirements() {
CRM_Core_Error::debug_log_message('WARNING: The downloader may be unable to download files which require HTTP redirection. This may be a configuration issue with PHP\'s open_basedir or safe_mode.');
}
+ if ($extensionInfo) {
+ $requiredExtensions = CRM_Extension_System::singleton()->getManager()->findInstallRequirements([$extensionInfo->key], $extensionInfo);
+ foreach ($requiredExtensions as $extension) {
+ if (CRM_Extension_System::singleton()->getManager()->getStatus($extension) !== CRM_Extension_Manager::STATUS_INSTALLED && $extension !== $extensionInfo->key) {
+ $errors[] = [
+ 'title' => ts('Missing Requirement: %1', [1 => $extension]),
+ 'message' => ts('You will not be able to install/upgrade %1 until you have installed the %2 extension.', [1 => $extensionInfo->key, 2 => $extension]),
+ ];
+ }
+ }
+ }
+
return $errors;
}
diff --git a/CRM/Extension/Exception.php b/CRM/Extension/Exception.php
index e037e810f6db..0a59514976e6 100644
--- a/CRM/Extension/Exception.php
+++ b/CRM/Extension/Exception.php
@@ -1,9 +1,9 @@
'psr4', 'namespace'=>'Foo\Bar', 'path'=>'/foo/bar').
*/
- public $classloader = array();
+ public $classloader = [];
+
+ /**
+ * @var array
+ * Each item is they key-name of an extension required by this extension.
+ */
+ public $requires = [];
/**
* Load extension info an XML file.
@@ -90,6 +99,27 @@ public static function loadFromString($string) {
return $instance;
}
+ /**
+ * Build a reverse-dependency map.
+ *
+ * @param array $infos
+ * The universe of available extensions.
+ * Ex: $infos['org.civicrm.foobar'] = new CRM_Extension_Info().
+ * @return array
+ * If "org.civicrm.api" is required by "org.civicrm.foo", then return
+ * array('org.civicrm.api' => array(CRM_Extension_Info[org.civicrm.foo])).
+ * Array(string $key => array $requiredBys).
+ */
+ public static function buildReverseMap($infos) {
+ $revMap = [];
+ foreach ($infos as $info) {
+ foreach ($info->requires as $key) {
+ $revMap[$key][] = $info;
+ }
+ }
+ return $revMap;
+ }
+
/**
* @param null $key
* @param null $type
@@ -124,7 +154,7 @@ public function parse($info) {
$this->$attr = (string) $val;
}
elseif ($attr === 'urls') {
- $this->urls = array();
+ $this->urls = [];
foreach ($val->url as $url) {
$urlAttr = (string) $url->attributes()->desc;
$this->urls[$urlAttr] = (string) $url;
@@ -132,19 +162,40 @@ public function parse($info) {
ksort($this->urls);
}
elseif ($attr === 'classloader') {
- $this->classloader = array();
+ $this->classloader = [];
foreach ($val->psr4 as $psr4) {
- $this->classloader[] = array(
+ $this->classloader[] = [
'type' => 'psr4',
'prefix' => (string) $psr4->attributes()->prefix,
'path' => (string) $psr4->attributes()->path,
- );
+ ];
}
}
+ elseif ($attr === 'requires') {
+ $this->requires = $this->filterRequirements($val);
+ }
else {
$this->$attr = CRM_Utils_XML::xmlObjToArray($val);
}
}
}
+ /**
+ * Filter out invalid requirements, e.g. extensions that have been moved to core.
+ *
+ * @param SimpleXMLElement $requirements
+ * @return array
+ */
+ public function filterRequirements($requirements) {
+ $filtered = [];
+ $compatInfo = CRM_Extension_System::getCompatibilityInfo();
+ foreach ($requirements->ext as $ext) {
+ $ext = (string) $ext;
+ if (empty($compatInfo[$ext]['obsolete'])) {
+ $filtered[] = $ext;
+ }
+ }
+ return $filtered;
+ }
+
}
diff --git a/CRM/Extension/Manager.php b/CRM/Extension/Manager.php
index 6ef8c6e55fb2..c313c9d900d3 100644
--- a/CRM/Extension/Manager.php
+++ b/CRM/Extension/Manager.php
@@ -1,9 +1,9 @@
CRM_Extension_Manager_Interface)
+ * Type managers.
+ *
+ * @var array
+ *
+ * Format is (typeName => CRM_Extension_Manager_Interface)
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $typeManagers;
/**
- * @var array (extensionKey => statusConstant)
+ * Statuses.
+ *
+ * @var array
+ *
+ * Format is (extensionKey => statusConstant)
*
* Note: Treat as private. This is only public to facilitate debugging.
*/
public $statuses;
/**
+ * Class constructor.
+ *
* @param CRM_Extension_Container_Interface $fullContainer
* @param CRM_Extension_Container_Basic|FALSE $defaultContainer
* @param CRM_Extension_Mapper $mapper
- * @param $typeManagers
+ * @param array $typeManagers
*/
public function __construct(CRM_Extension_Container_Interface $fullContainer, $defaultContainer, CRM_Extension_Mapper $mapper, $typeManagers) {
$this->fullContainer = $fullContainer;
@@ -135,16 +149,17 @@ public function replace($tmpCodeDir) {
case self::STATUS_INSTALLED:
case self::STATUS_DISABLED:
// There is an old copy of the extension. Try to install in the same place -- but it must go somewhere in the default-container
- list ($oldInfo, $typeManager) = $this->_getInfoTypeHandler($newInfo->key); // throws Exception
+ // throws Exception
+ list ($oldInfo, $typeManager) = $this->_getInfoTypeHandler($newInfo->key);
$tgtPath = $this->fullContainer->getPath($newInfo->key);
if (!CRM_Utils_File::isChildPath($this->defaultContainer->getBaseDir(), $tgtPath)) {
// force installation in the default-container
$oldPath = $tgtPath;
$tgtPath = $this->defaultContainer->getBaseDir() . DIRECTORY_SEPARATOR . $newInfo->key;
- CRM_Core_Session::setStatus(ts('A copy of the extension (%1) is in a system folder (%2). The system copy will be preserved, but the new copy will be used.', array(
+ CRM_Core_Session::setStatus(ts('A copy of the extension (%1) is in a system folder (%2). The system copy will be preserved, but the new copy will be used.', [
1 => $newInfo->key,
2 => $oldPath,
- )));
+ ]));
}
break;
@@ -152,7 +167,8 @@ public function replace($tmpCodeDir) {
case self::STATUS_DISABLED_MISSING:
// the extension does not exist in any container; we're free to put it anywhere
$tgtPath = $this->defaultContainer->getBaseDir() . DIRECTORY_SEPARATOR . $newInfo->key;
- list ($oldInfo, $typeManager) = $this->_getMissingInfoTypeHandler($newInfo->key); // throws Exception
+ // throws Exception
+ list ($oldInfo, $typeManager) = $this->_getMissingInfoTypeHandler($newInfo->key);
break;
case self::STATUS_UNKNOWN:
@@ -199,18 +215,32 @@ public function replace($tmpCodeDir) {
/**
* Add records of the extension to the database -- and enable it
*
- * @param array $keys
- * List of extension keys.
+ * @param string|array $keys
+ * One or more extension keys.
* @throws CRM_Extension_Exception
*/
public function install($keys) {
+ $keys = (array) $keys;
$origStatuses = $this->getStatuses();
// TODO: to mitigate the risk of crashing during installation, scan
// keys/statuses/types before doing anything
+ // Check compatibility
+ $incompatible = [];
foreach ($keys as $key) {
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ if ($this->isIncompatible($key)) {
+ $incompatible[] = $key;
+ }
+ }
+ if ($incompatible) {
+ throw new CRM_Extension_Exception('Cannot install incompatible extension: ' . implode(', ', $incompatible));
+ }
+
+ foreach ($keys as $key) {
+ /** @var CRM_Extension_Info $info */
+ /** @var CRM_Extension_Manager_Base $typeManager */
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
@@ -222,6 +252,11 @@ public function install($keys) {
$typeManager->onPreEnable($info);
$this->_setExtensionActive($info, 1);
$typeManager->onPostEnable($info);
+
+ // A full refresh would be preferrable but very slow. This at least allows
+ // later extensions to access classes from earlier extensions.
+ $this->statuses = NULL;
+ $this->mapper->refresh();
break;
case self::STATUS_UNINSTALLED:
@@ -229,6 +264,11 @@ public function install($keys) {
$typeManager->onPreInstall($info);
$this->_createExtensionEntry($info);
$typeManager->onPostInstall($info);
+
+ // A full refresh would be preferrable but very slow. This at least allows
+ // later extensions to access classes from earlier extensions.
+ $this->statuses = NULL;
+ $this->mapper->refresh();
break;
case self::STATUS_UNKNOWN:
@@ -244,7 +284,8 @@ public function install($keys) {
$schema->fixSchemaDifferences();
foreach ($keys as $key) {
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
@@ -280,29 +321,40 @@ public function enable($keys) {
}
/**
- * Add records of the extension to the database -- and enable it
+ * Disable extension without removing record from db.
*
- * @param array $keys
- * List of extension keys.
+ * @param string|array $keys
+ * One or more extension keys.
* @throws CRM_Extension_Exception
*/
public function disable($keys) {
+ $keys = (array) $keys;
$origStatuses = $this->getStatuses();
// TODO: to mitigate the risk of crashing during installation, scan
// keys/statuses/types before doing anything
+ sort($keys);
+ $disableRequirements = $this->findDisableRequirements($keys);
+ // This munges order, but makes it comparable.
+ sort($disableRequirements);
+ if ($keys !== $disableRequirements) {
+ throw new CRM_Extension_Exception_DependencyException("Cannot disable extension due to dependencies. Consider disabling all these: " . implode(',', $disableRequirements));
+ }
+
foreach ($keys as $key) {
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
$typeManager->onPreDisable($info);
$this->_setExtensionActive($info, 0);
$typeManager->onPostDisable($info);
break;
case self::STATUS_INSTALLED_MISSING:
- list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key);
$typeManager->onPreDisable($info);
$this->_setExtensionActive($info, 0);
$typeManager->onPostDisable($info);
@@ -328,13 +380,12 @@ public function disable($keys) {
/**
* Remove all database references to an extension.
*
- * Add records of the extension to the database -- and enable it
- *
- * @param array $keys
- * List of extension keys.
+ * @param string|array $keys
+ * One or more extension keys.
* @throws CRM_Extension_Exception
*/
public function uninstall($keys) {
+ $keys = (array) $keys;
$origStatuses = $this->getStatuses();
// TODO: to mitigate the risk of crashing during installation, scan
@@ -347,14 +398,16 @@ public function uninstall($keys) {
throw new CRM_Extension_Exception("Cannot uninstall extension; disable it first: $key");
case self::STATUS_DISABLED:
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
$typeManager->onPreUninstall($info);
$this->_removeExtensionEntry($info);
$typeManager->onPostUninstall($info);
break;
case self::STATUS_DISABLED_MISSING:
- list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key);
$typeManager->onPreUninstall($info);
$this->_removeExtensionEntry($info);
$typeManager->onPostUninstall($info);
@@ -381,7 +434,7 @@ public function uninstall($keys) {
* @param $key
*
* @return string
- * constant (STATUS_INSTALLED, STATUS_DISABLED, STATUS_UNINSTALLED, STATUS_UNKNOWN)
+ * constant self::STATUS_*
*/
public function getStatus($key) {
$statuses = $this->getStatuses();
@@ -393,6 +446,17 @@ public function getStatus($key) {
}
}
+ /**
+ * Check if a given extension is incompatible with this version of CiviCRM
+ *
+ * @param $key
+ * @return bool|array
+ */
+ public function isIncompatible($key) {
+ $info = CRM_Extension_System::getCompatibilityInfo();
+ return $info[$key] ?? FALSE;
+ }
+
/**
* Determine the status of all extensions.
*
@@ -401,7 +465,9 @@ public function getStatus($key) {
*/
public function getStatuses() {
if (!is_array($this->statuses)) {
- $this->statuses = array();
+ $compat = CRM_Extension_System::getCompatibilityInfo();
+
+ $this->statuses = [];
foreach ($this->fullContainer->getKeys() as $key) {
$this->statuses[$key] = self::STATUS_UNINSTALLED;
@@ -420,7 +486,10 @@ public function getStatuses() {
catch (CRM_Extension_Exception $e) {
$codeExists = FALSE;
}
- if ($dao->is_active) {
+ if (!empty($compat[$dao->full_name]['force-uninstall'])) {
+ $this->statuses[$dao->full_name] = self::STATUS_UNINSTALLED;
+ }
+ elseif ($dao->is_active) {
$this->statuses[$dao->full_name] = $codeExists ? self::STATUS_INSTALLED : self::STATUS_INSTALLED_MISSING;
}
else {
@@ -433,7 +502,8 @@ public function getStatuses() {
public function refresh() {
$this->statuses = NULL;
- $this->fullContainer->refresh(); // and, indirectly, defaultContainer
+ // and, indirectly, defaultContainer
+ $this->fullContainer->refresh();
$this->mapper->refresh();
}
@@ -446,12 +516,13 @@ public function refresh() {
*
* @throws CRM_Extension_Exception
* @return array
- * (0 => CRM_Extension_Info, 1 => CRM_Extension_Manager_Interface)
+ * [CRM_Extension_Info, CRM_Extension_Manager_Interface]
*/
private function _getInfoTypeHandler($key) {
- $info = $this->mapper->keyToInfo($key); // throws Exception
+ // throws Exception
+ $info = $this->mapper->keyToInfo($key);
if (array_key_exists($info->type, $this->typeManagers)) {
- return array($info, $this->typeManagers[$info->type]);
+ return [$info, $this->typeManagers[$info->type]];
}
else {
throw new CRM_Extension_Exception("Unrecognized extension type: " . $info->type);
@@ -465,13 +536,13 @@ private function _getInfoTypeHandler($key) {
*
* @throws CRM_Extension_Exception
* @return array
- * (0 => CRM_Extension_Info, 1 => CRM_Extension_Manager_Interface)
+ * [CRM_Extension_Info, CRM_Extension_Manager_Interface]
*/
private function _getMissingInfoTypeHandler($key) {
$info = $this->createInfoFromDB($key);
if ($info) {
if (array_key_exists($info->type, $this->typeManagers)) {
- return array($info, $this->typeManagers[$info->type]);
+ return [$info, $this->typeManagers[$info->type]];
}
else {
throw new CRM_Extension_Exception("Unrecognized extension type: " . $info->type);
@@ -543,10 +614,10 @@ private function _removeExtensionEntry(CRM_Extension_Info $info) {
* @param $isActive
*/
private function _setExtensionActive(CRM_Extension_Info $info, $isActive) {
- CRM_Core_DAO::executeQuery('UPDATE civicrm_extension SET is_active = %1 where full_name = %2', array(
- 1 => array($isActive, 'Integer'),
- 2 => array($info->key, 'String'),
- ));
+ CRM_Core_DAO::executeQuery('UPDATE civicrm_extension SET is_active = %1 where full_name = %2', [
+ 1 => [$isActive, 'Integer'],
+ 2 => [$info->key, 'String'],
+ ]);
}
/**
@@ -568,4 +639,107 @@ public function createInfoFromDB($key) {
}
}
+ /**
+ * Build a list of extensions to install, in an order that will satisfy dependencies.
+ *
+ * @param array $keys
+ * List of extensions to install.
+ * @param \CRM_Extension_Info $info
+ * An extension info object that we should use instead of our local versions (eg. when checking for upgradeability).
+ *
+ * @return array
+ * List of extension keys, including dependencies, in order of installation.
+ * @throws \CRM_Extension_Exception
+ * @throws \MJS\TopSort\CircularDependencyException
+ * @throws \MJS\TopSort\ElementNotFoundException
+ */
+ public function findInstallRequirements($keys, $info = NULL) {
+ // Use our passed in info, or get the local versions
+ if ($info) {
+ $infos[$info->key] = $info;
+ }
+ else {
+ $infos = $this->mapper->getAllInfos();
+ }
+ // array(string $key).
+ $todoKeys = array_unique($keys);
+ // array(string $key => 1);
+ $doneKeys = [];
+ $sorter = new \MJS\TopSort\Implementations\FixedArraySort();
+
+ while (!empty($todoKeys)) {
+ $key = array_shift($todoKeys);
+ if (isset($doneKeys[$key])) {
+ continue;
+ }
+ $doneKeys[$key] = 1;
+
+ /** @var CRM_Extension_Info $info */
+ $info = @$infos[$key];
+
+ if ($info && $info->requires) {
+ $sorter->add($key, $info->requires);
+ $todoKeys = array_merge($todoKeys, $info->requires);
+ }
+ else {
+ $sorter->add($key, []);
+ }
+ }
+ return $sorter->sort();
+ }
+
+ /**
+ * Build a list of extensions to remove, in an order that will satisfy dependencies.
+ *
+ * @param array $keys
+ * List of extensions to install.
+ * @return array
+ * List of extension keys, including dependencies, in order of removal.
+ */
+ public function findDisableRequirements($keys) {
+ $INSTALLED = [
+ self::STATUS_INSTALLED,
+ self::STATUS_INSTALLED_MISSING,
+ ];
+ $installedInfos = $this->filterInfosByStatus($this->mapper->getAllInfos(), $INSTALLED);
+ $revMap = CRM_Extension_Info::buildReverseMap($installedInfos);
+ $todoKeys = array_unique($keys);
+ $doneKeys = [];
+ $sorter = new \MJS\TopSort\Implementations\FixedArraySort();
+
+ while (!empty($todoKeys)) {
+ $key = array_shift($todoKeys);
+ if (isset($doneKeys[$key])) {
+ continue;
+ }
+ $doneKeys[$key] = 1;
+
+ if (isset($revMap[$key])) {
+ $requiredBys = CRM_Utils_Array::collect('key',
+ $this->filterInfosByStatus($revMap[$key], $INSTALLED));
+ $sorter->add($key, $requiredBys);
+ $todoKeys = array_merge($todoKeys, $requiredBys);
+ }
+ else {
+ $sorter->add($key, []);
+ }
+ }
+ return $sorter->sort();
+ }
+
+ /**
+ * @param $infos
+ * @param $filterStatuses
+ * @return array
+ */
+ protected function filterInfosByStatus($infos, $filterStatuses) {
+ $matches = [];
+ foreach ($infos as $k => $v) {
+ if (in_array($this->getStatus($v->key), $filterStatuses)) {
+ $matches[$k] = $v;
+ }
+ }
+ return $matches;
+ }
+
}
diff --git a/CRM/Extension/Manager/Base.php b/CRM/Extension/Manager/Base.php
index 6d2509e77b70..b3fc0d928264 100644
--- a/CRM/Extension/Manager/Base.php
+++ b/CRM/Extension/Manager/Base.php
@@ -1,9 +1,9 @@
$id)
*/
private function _getAllPaymentProcessorTypes($attr) {
- $ppt = array();
+ $ppt = [];
$dao = new CRM_Financial_DAO_PaymentProcessorType();
$dao->find();
while ($dao->fetch()) {
@@ -204,11 +204,11 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
$paymentClass = $this->mapper->keyToClass($info->key, 'payment');
$file = $this->mapper->classToPath($paymentClass);
if (!file_exists($file)) {
- CRM_Core_Session::setStatus(ts('Failed to load file (%3) for payment processor (%1) while running "%2"', array(
- 1 => $info->key,
- 2 => $method,
- 3 => $file,
- )), '', 'error');
+ CRM_Core_Session::setStatus(ts('Failed to load file (%3) for payment processor (%1) while running "%2"', [
+ 1 => $info->key,
+ 2 => $method,
+ 3 => $file,
+ ]), '', 'error');
return;
}
else {
@@ -216,10 +216,10 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
}
}
catch (CRM_Extension_Exception $e) {
- CRM_Core_Session::setStatus(ts('Failed to determine file path for payment processor (%1) while running "%2"', array(
- 1 => $info->key,
- 2 => $method,
- )), '', 'error');
+ CRM_Core_Session::setStatus(ts('Failed to determine file path for payment processor (%1) while running "%2"', [
+ 1 => $info->key,
+ 2 => $method,
+ ]), '', 'error');
return;
}
@@ -233,9 +233,9 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
WHERE ext.type = 'payment'
AND ext.full_name = %1
",
- array(
- 1 => array($info->key, 'String'),
- )
+ [
+ 1 => [$info->key, 'String'],
+ ]
);
while ($processorDAO->fetch()) {
@@ -262,11 +262,10 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
$processorInstance = Civi\Payment\System::singleton()->getByClass($class_name);
// Does PP implement this method, and can we call it?
- if (method_exists($processorInstance, $method) && is_callable(array(
- $processorInstance,
- $method,
- ))
- ) {
+ if (method_exists($processorInstance, $method) && is_callable([
+ $processorInstance,
+ $method,
+ ])) {
// If so, call it ...
$processorInstance->$method();
}
@@ -274,7 +273,7 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
default:
CRM_Core_Session::setStatus(ts("Unrecognized payment hook (%1) in %2::%3",
- array(1 => $method, 2 => __CLASS__, 3 => __METHOD__)),
+ [1 => $method, 2 => __CLASS__, 3 => __METHOD__]),
'', 'error');
}
}
diff --git a/CRM/Extension/Manager/Report.php b/CRM/Extension/Manager/Report.php
index 8f92b9a7cdf9..3302ec291824 100644
--- a/CRM/Extension/Manager/Report.php
+++ b/CRM/Extension/Manager/Report.php
@@ -1,9 +1,9 @@
typeInfo['component'] . ") is currently disabled.");
}
$weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
- array('option_group_id' => $this->groupId)
+ ['option_group_id' => $this->groupId]
);
- $ids = array();
- $params = array(
+ $ids = [];
+ $params = [
'label' => $info->label . ' (' . $info->key . ')',
'value' => $info->typeInfo['reportUrl'],
'name' => $info->key,
@@ -79,7 +79,7 @@ public function onPreInstall(CRM_Extension_Info $info) {
'component_id' => $compId,
'option_group_id' => $this->groupId,
'is_active' => 1,
- );
+ ];
$optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
}
diff --git a/CRM/Extension/Manager/Search.php b/CRM/Extension/Manager/Search.php
index 684d1027ca38..1f0b291bf80c 100644
--- a/CRM/Extension/Manager/Search.php
+++ b/CRM/Extension/Manager/Search.php
@@ -1,9 +1,9 @@
$this->groupId)
+ ['option_group_id' => $this->groupId]
);
- $params = array(
+ $params = [
'option_group_id' => $this->groupId,
'weight' => $weight,
'description' => $info->label . ' (' . $info->key . ')',
@@ -69,9 +69,9 @@ public function onPreInstall(CRM_Extension_Info $info) {
'value' => max($customSearchesByName) + 1,
'label' => $info->key,
'is_active' => 1,
- );
+ ];
- $ids = array();
+ $ids = [];
$optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
return $optionValue ? TRUE : FALSE;
diff --git a/CRM/Extension/Mapper.php b/CRM/Extension/Mapper.php
index de31e82d9198..fd828e4fe771 100644
--- a/CRM/Extension/Mapper.php
+++ b/CRM/Extension/Mapper.php
@@ -1,9 +1,9 @@
CRM_Extension_Info)
*/
- protected $infos = array();
+ protected $infos = [];
/**
* @var array
@@ -275,19 +275,21 @@ public function keyToUrl($key) {
* array(array('prefix' => $, 'file' => $))
*/
public function getActiveModuleFiles($fresh = FALSE) {
- $config = CRM_Core_Config::singleton();
- if ($config->isUpgradeMode() || !defined('CIVICRM_DSN')) {
- return array(); // hmm, ok
+ if (!defined('CIVICRM_DSN')) {
+ // hmm, ok
+ return [];
}
$moduleExtensions = NULL;
if ($this->cache && !$fresh) {
- $moduleExtensions = $this->cache->get($this->cacheKey . '/moduleFiles');
+ $moduleExtensions = $this->cache->get($this->cacheKey . '_moduleFiles');
}
if (!is_array($moduleExtensions)) {
+ $compat = CRM_Extension_System::getCompatibilityInfo();
+
// Check canonical module list
- $moduleExtensions = array();
+ $moduleExtensions = [];
$sql = '
SELECT full_name, file
FROM civicrm_extension
@@ -296,26 +298,29 @@ public function getActiveModuleFiles($fresh = FALSE) {
';
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
+ if (!empty($compat[$dao->full_name]['force-uninstall'])) {
+ continue;
+ }
try {
- $moduleExtensions[] = array(
+ $moduleExtensions[] = [
'prefix' => $dao->file,
'filePath' => $this->keyToPath($dao->full_name),
- );
+ ];
}
catch (CRM_Extension_Exception $e) {
// Putting a stub here provides more consistency
// in how getActiveModuleFiles when racing between
// dirty file-removals and cache-clears.
CRM_Core_Session::setStatus($e->getMessage(), '', 'error');
- $moduleExtensions[] = array(
+ $moduleExtensions[] = [
'prefix' => $dao->file,
'filePath' => NULL,
- );
+ ];
}
}
if ($this->cache) {
- $this->cache->set($this->cacheKey . '/moduleFiles', $moduleExtensions);
+ $this->cache->set($this->cacheKey . '_moduleFiles', $moduleExtensions);
}
}
return $moduleExtensions;
@@ -329,7 +334,7 @@ public function getActiveModuleFiles($fresh = FALSE) {
*/
public function getActiveModuleUrls() {
// TODO optimization/caching
- $urls = array();
+ $urls = [];
$urls['civicrm'] = $this->keyToUrl('civicrm');
foreach ($this->getModules() as $module) {
/** @var $module CRM_Core_Module */
@@ -340,6 +345,54 @@ public function getActiveModuleUrls() {
return $urls;
}
+ /**
+ * Get a list of extension keys, filtered by the corresponding file path.
+ *
+ * @param string $pattern
+ * A file path. To search subdirectories, append "*".
+ * Ex: "/var/www/extensions/*"
+ * Ex: "/var/www/extensions/org.foo.bar"
+ * @return array
+ * Array(string $key).
+ * Ex: array("org.foo.bar").
+ */
+ public function getKeysByPath($pattern) {
+ $keys = [];
+
+ if (CRM_Utils_String::endsWith($pattern, '*')) {
+ $prefix = rtrim($pattern, '*');
+ foreach ($this->container->getKeys() as $key) {
+ $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
+ if (realpath($prefix) == realpath($path) || CRM_Utils_File::isChildPath($prefix, $path)) {
+ $keys[] = $key;
+ }
+ }
+ }
+ else {
+ foreach ($this->container->getKeys() as $key) {
+ $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
+ if (realpath($pattern) == realpath($path)) {
+ $keys[] = $key;
+ }
+ }
+ }
+
+ return $keys;
+ }
+
+ /**
+ * @return array
+ * Ex: $result['org.civicrm.foobar'] = new CRM_Extension_Info(...).
+ * @throws \CRM_Extension_Exception
+ * @throws \Exception
+ */
+ public function getAllInfos() {
+ foreach ($this->container->getKeys() as $key) {
+ $this->keyToInfo($key);
+ }
+ return $this->infos;
+ }
+
/**
* @param string $name
*
@@ -362,7 +415,7 @@ public function isActiveModule($name) {
* CRM_Core_Module
*/
public function getModules() {
- $result = array();
+ $result = [];
$dao = new CRM_Core_DAO_Extension();
$dao->type = 'module';
$dao->find();
@@ -410,10 +463,10 @@ public function getTemplateName($clazz) {
}
public function refresh() {
- $this->infos = array();
+ $this->infos = [];
$this->moduleExtensions = NULL;
if ($this->cache) {
- $this->cache->delete($this->cacheKey . '/moduleFiles');
+ $this->cache->delete($this->cacheKey . '_moduleFiles');
}
// FIXME: How can code so code wrong be so right?
CRM_Extension_System::singleton()->getClassLoader()->refresh();
diff --git a/CRM/Extension/System.php b/CRM/Extension/System.php
index 060193985500..a45cbfbadfb7 100644
--- a/CRM/Extension/System.php
+++ b/CRM/Extension/System.php
@@ -1,9 +1,9 @@
extensionsDir);
$parameters['extensionsURL'] = CRM_Utils_Array::value('extensionsURL', $parameters, $config->extensionsURL);
$parameters['resourceBase'] = CRM_Utils_Array::value('resourceBase', $parameters, $config->resourceBase);
+ $parameters['uploadDir'] = CRM_Utils_Array::value('uploadDir', $parameters, $config->uploadDir);
$parameters['userFrameworkBaseURL'] = CRM_Utils_Array::value('userFrameworkBaseURL', $parameters, $config->userFrameworkBaseURL);
if (!array_key_exists('civicrm_root', $parameters)) {
$parameters['civicrm_root'] = $GLOBALS['civicrm_root'];
@@ -108,7 +111,8 @@ public function __construct($parameters = array()) {
if (!array_key_exists('domain_id', $parameters)) {
$parameters['domain_id'] = CRM_Core_Config::domainID();
}
- ksort($parameters); // guaranteed ordering - useful for md5(serialize($parameters))
+ // guaranteed ordering - useful for md5(serialize($parameters))
+ ksort($parameters);
$this->parameters = $parameters;
}
@@ -120,7 +124,7 @@ public function __construct($parameters = array()) {
*/
public function getFullContainer() {
if ($this->fullContainer === NULL) {
- $containers = array();
+ $containers = [];
if ($this->getDefaultContainer()) {
$containers['default'] = $this->getDefaultContainer();
@@ -151,6 +155,12 @@ public function getFullContainer() {
}
}
+ if (!defined('CIVICRM_TEST')) {
+ foreach ($containers as $container) {
+ $container->addFilter([__CLASS__, 'isNotTestExtension']);
+ }
+ }
+
$this->fullContainer = new CRM_Extension_Container_Collection($containers, $this->getCache(), 'full');
}
return $this->fullContainer;
@@ -204,12 +214,12 @@ public function getClassLoader() {
*/
public function getManager() {
if ($this->manager === NULL) {
- $typeManagers = array(
+ $typeManagers = [
'payment' => new CRM_Extension_Manager_Payment($this->getMapper()),
'report' => new CRM_Extension_Manager_Report(),
'search' => new CRM_Extension_Manager_Search(),
'module' => new CRM_Extension_Manager_Module($this->getMapper()),
- );
+ ];
$this->manager = new CRM_Extension_Manager($this->getFullContainer(), $this->getDefaultContainer(), $this->getMapper(), $typeManagers);
}
return $this->manager;
@@ -223,8 +233,8 @@ public function getManager() {
public function getBrowser() {
if ($this->browser === NULL) {
$cacheDir = NULL;
- if ($this->getDefaultContainer()) {
- $cacheDir = $this->getDefaultContainer()->getBaseDir() . DIRECTORY_SEPARATOR . 'cache';
+ if (!empty($this->parameters['uploadDir'])) {
+ $cacheDir = CRM_Utils_File::addTrailingSlash($this->parameters['uploadDir']) . 'cache';
}
$this->browser = new CRM_Extension_Browser($this->getRepositoryUrl(), '', $cacheDir);
}
@@ -242,7 +252,8 @@ public function getDownloader() {
$this->downloader = new CRM_Extension_Downloader(
$this->getManager(),
$basedir,
- CRM_Utils_File::tempdir() // WAS: $config->extensionsDir . DIRECTORY_SEPARATOR . 'tmp';
+ // WAS: $config->extensionsDir . DIRECTORY_SEPARATOR . 'tmp';
+ CRM_Utils_File::tempdir()
);
}
return $this->downloader;
@@ -253,13 +264,13 @@ public function getDownloader() {
*/
public function getCache() {
if ($this->cache === NULL) {
- $cacheGroup = md5(serialize(array('ext', $this->parameters)));
+ $cacheGroup = md5(serialize(['ext', $this->parameters, CRM_Utils_System::version()]));
// Extension system starts before container. Manage our own cache.
- $this->cache = CRM_Utils_Cache::create(array(
+ $this->cache = CRM_Utils_Cache::create([
'name' => $cacheGroup,
- 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
+ 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
'prefetch' => TRUE,
- ));
+ ]);
}
return $this->cache;
}
@@ -285,6 +296,22 @@ public function getRepositoryUrl() {
return $this->_repoUrl;
}
+ /**
+ * Returns a list keyed by extension key
+ *
+ * @return array
+ */
+ public static function getCompatibilityInfo() {
+ if (!isset(Civi::$statics[__CLASS__]['compatibility'])) {
+ Civi::$statics[__CLASS__]['compatibility'] = json_decode(file_get_contents(Civi::paths()->getPath('[civicrm.root]/extension-compatibility.json')), TRUE);
+ }
+ return Civi::$statics[__CLASS__]['compatibility'];
+ }
+
+ public static function isNotTestExtension(CRM_Extension_Info $info) {
+ return (bool) !preg_match('/^test\./', $info->key);
+ }
+
/**
* Take an extension's raw XML info and add information about the
* extension's status on the local system.
@@ -310,7 +337,8 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
switch ($extensionRow['status']) {
case CRM_Extension_Manager::STATUS_UNINSTALLED:
- $extensionRow['statusLabel'] = ''; // ts('Uninstalled');
+ // ts('Uninstalled');
+ $extensionRow['statusLabel'] = '';
break;
case CRM_Extension_Manager::STATUS_DISABLED:
@@ -318,7 +346,8 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
break;
case CRM_Extension_Manager::STATUS_INSTALLED:
- $extensionRow['statusLabel'] = ts('Enabled'); // ts('Installed');
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled');
break;
case CRM_Extension_Manager::STATUS_DISABLED_MISSING:
@@ -326,12 +355,16 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
break;
case CRM_Extension_Manager::STATUS_INSTALLED_MISSING:
- $extensionRow['statusLabel'] = ts('Enabled (Missing)'); // ts('Installed');
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled (Missing)');
break;
default:
$extensionRow['statusLabel'] = '(' . $extensionRow['status'] . ')';
}
+ if ($manager->isIncompatible($obj->key)) {
+ $extensionRow['statusLabel'] = ts('Obsolete') . ($extensionRow['statusLabel'] ? (' - ' . $extensionRow['statusLabel']) : '');
+ }
return $extensionRow;
}
diff --git a/CRM/Extension/Upgrades.php b/CRM/Extension/Upgrades.php
index 7e020578cbe5..a81a5b65f768 100644
--- a/CRM/Extension/Upgrades.php
+++ b/CRM/Extension/Upgrades.php
@@ -1,9 +1,9 @@
create(array(
+ $queue = CRM_Queue_Service::singleton()->create([
'type' => 'Sql',
'name' => self::QUEUE_NAME,
'reset' => TRUE,
- ));
+ ]);
CRM_Utils_Hook::upgrade('enqueue', $queue);
diff --git a/CRM/Financial/BAO/ExportFormat.php b/CRM/Financial/BAO/ExportFormat.php
index 438efb682f60..cf4111509608 100644
--- a/CRM/Financial/BAO/ExportFormat.php
+++ b/CRM/Financial/BAO/ExportFormat.php
@@ -1,9 +1,9 @@
_isDownloadFile) {
+ return NULL;
+ }
$config = CRM_Core_Config::singleton();
// zip files if more than one.
if (count($this->_downloadFile) > 1) {
@@ -153,7 +163,8 @@ public function initiateDownload() {
ob_clean();
flush();
readfile($config->customFileUploadDir . CRM_Utils_File::cleanFileName(basename($zip)));
- unlink($zip); //delete the zip to avoid clutter.
+ //delete the zip to avoid clutter.
+ unlink($zip);
CRM_Utils_System::civiExit();
}
}
@@ -176,8 +187,8 @@ public function initiateDownload() {
*/
public static function createActivityExport($batchIds, $fileName) {
$session = CRM_Core_Session::singleton();
- $values = array();
- $params = array('id' => $batchIds);
+ $values = [];
+ $params = ['id' => $batchIds];
CRM_Batch_BAO_Batch::retrieve($params, $values);
$createdBy = CRM_Contact_BAO_Contact::displayName($values['created_id']);
$modifiedBy = CRM_Contact_BAO_Contact::displayName($values['modified_id']);
@@ -198,25 +209,23 @@ public static function createActivityExport($batchIds, $fileName) {
// create activity.
$subject .= ' ' . ts('Batch') . '[' . $values['title'] . ']';
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
- $activityParams = array(
- 'activity_type_id' => array_search('Export Accounting Batch', $activityTypes),
+ $activityParams = [
+ 'activity_type_id' => 'Export Accounting Batch',
'subject' => $subject,
- 'status_id' => 2,
+ 'status_id' => 'Completed',
'activity_date_time' => date('YmdHis'),
'source_contact_id' => $session->get('userID'),
'source_record_id' => $values['id'],
'target_contact_id' => $session->get('userID'),
'details' => $details,
- 'attachFile_1' => array(
+ 'attachFile_1' => [
'uri' => $fileName,
'type' => 'text/csv',
'location' => $fileName,
'upload_date' => date('YmdHis'),
- ),
- );
-
- CRM_Activity_BAO_Activity::create($activityParams);
+ ],
+ ];
+ civicrm_api3('Activity', 'create', $activityParams);
}
/**
@@ -226,12 +235,12 @@ public static function createActivityExport($batchIds, $fileName) {
*
* @return bool
*/
- public function createZip($files = array(), $destination = NULL, $overwrite = FALSE) {
+ public function createZip($files = [], $destination = NULL, $overwrite = FALSE) {
// if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return FALSE;
}
- $valid_files = array();
+ $valid_files = [];
if (is_array($files)) {
foreach ($files as $file) {
// make sure the file exists
@@ -242,7 +251,7 @@ public function createZip($files = array(), $destination = NULL, $overwrite = FA
}
if (count($validFiles)) {
$zip = new ZipArchive();
- if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) {
+ if ($zip->open($destination, $overwrite ? ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) {
return FALSE;
}
foreach ($validFiles as $file) {
diff --git a/CRM/Financial/BAO/ExportFormat/CSV.php b/CRM/Financial/BAO/ExportFormat/CSV.php
index 20ed7a03eb65..c38c11ca9b84 100644
--- a/CRM/Financial/BAO/ExportFormat/CSV.php
+++ b/CRM/Financial/BAO/ExportFormat/CSV.php
@@ -1,9 +1,9 @@
array($batchId, 'String'));
+ $params = [1 => [$batchId, 'String']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
return $dao;
@@ -139,7 +140,9 @@ public function putFile($export) {
$fileName = $config->uploadDir . 'Financial_Transactions_' . $this->_batchIds . '_' . date('YmdHis') . '.' . $this->getFileExtension();
$this->_downloadFile[] = $config->customFileUploadDir . CRM_Utils_File::cleanFileName(basename($fileName));
$out = fopen($fileName, 'w');
- fputcsv($out, $export['headers']);
+ if (!empty($export['headers'])) {
+ fputcsv($out, $export['headers']);
+ }
unset($export['headers']);
if (!empty($export)) {
foreach ($export as $fields) {
@@ -158,7 +161,7 @@ public function putFile($export) {
*/
public function formatHeaders($values) {
$arrayKeys = array_keys($values);
- $headers = '';
+ $headers = [];
if (!empty($arrayKeys)) {
foreach ($values[$arrayKeys[0]] as $title => $value) {
$headers[] = $title;
@@ -177,11 +180,10 @@ public function makeExport($export) {
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
foreach ($export as $batchId => $dao) {
- $financialItems = array();
+ $financialItems = [];
$this->_batchIds = $batchId;
- $batchItems = array();
- $queryResults = array();
+ $queryResults = [];
while ($dao->fetch()) {
$creditAccountName = $creditAccountType = $creditAccount = NULL;
@@ -198,7 +200,7 @@ public function makeExport($export) {
$invoiceNo = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $dao->contribution_id;
- $financialItems[] = array(
+ $financialItems[] = [
'Batch ID' => $dao->batch_id,
'Invoice No' => $invoiceNo,
'Contact ID' => $dao->contact_id,
@@ -220,14 +222,13 @@ public function makeExport($export) {
'Credit Account Name' => $creditAccountName,
'Credit Account Type' => $creditAccountType,
'Item Description' => $dao->item_description,
- );
+ ];
end($financialItems);
- $batchItems[] = &$financialItems[key($financialItems)];
$queryResults[] = get_object_vars($dao);
}
- CRM_Utils_Hook::batchItems($queryResults, $batchItems);
+ CRM_Utils_Hook::batchItems($queryResults, $financialItems);
$financialItems['headers'] = self::formatHeaders($financialItems);
self::export($financialItems);
diff --git a/CRM/Financial/BAO/ExportFormat/IIF.php b/CRM/Financial/BAO/ExportFormat/IIF.php
index b6ab465cf889..71c615394899 100644
--- a/CRM/Financial/BAO/ExportFormat/IIF.php
+++ b/CRM/Financial/BAO/ExportFormat/IIF.php
@@ -1,9 +1,9 @@
array($batchId, 'String'));
+ $params = [1 => [$batchId, 'String']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
return $dao;
@@ -165,47 +167,47 @@ public function makeExport($export) {
// include those in the output. Only want to include ones used in the batch, not everything in the db,
// since would increase the chance of messing up user's existing Quickbooks entries.
foreach ($export as $batchId => $dao) {
- $accounts = $contacts = $journalEntries = $exportParams = array();
+ $accounts = $contacts = $journalEntries = $exportParams = [];
$this->_batchIds = $batchId;
while ($dao->fetch()) {
// add to running list of accounts
if (!empty($dao->from_account_id) && !isset($accounts[$dao->from_account_id])) {
- $accounts[$dao->from_account_id] = array(
+ $accounts[$dao->from_account_id] = [
'name' => $this->format($dao->from_account_name),
'account_code' => $this->format($dao->from_account_code),
'description' => $this->format($dao->from_account_description),
'type' => $this->format($dao->from_account_type_code),
- );
+ ];
}
if (!empty($dao->to_account_id) && !isset($accounts[$dao->to_account_id])) {
- $accounts[$dao->to_account_id] = array(
+ $accounts[$dao->to_account_id] = [
'name' => $this->format($dao->to_account_name),
'account_code' => $this->format($dao->to_account_code),
'description' => $this->format($dao->to_account_description),
'type' => $this->format($dao->to_account_type_code),
- );
+ ];
}
// add to running list of contacts
if (!empty($dao->contact_from_id) && !isset($contacts[$dao->contact_from_id])) {
- $contacts[$dao->contact_from_id] = array(
+ $contacts[$dao->contact_from_id] = [
'name' => $this->format($dao->contact_from_name),
'first_name' => $this->format($dao->contact_from_first_name),
'last_name' => $this->format($dao->contact_from_last_name),
- );
+ ];
}
if (!empty($dao->contact_to_id) && !isset($contacts[$dao->contact_to_id])) {
- $contacts[$dao->contact_to_id] = array(
+ $contacts[$dao->contact_to_id] = [
'name' => $this->format($dao->contact_to_name),
'first_name' => $this->format($dao->contact_to_first_name),
'last_name' => $this->format($dao->contact_to_last_name),
- );
+ ];
}
// set up the journal entries for this financial trxn
- $journalEntries[$dao->financial_trxn_id] = array(
- 'to_account' => array(
+ $journalEntries[$dao->financial_trxn_id] = [
+ 'to_account' => [
'trxn_date' => $this->format($dao->trxn_date, 'date'),
'trxn_id' => $this->format($dao->trxn_id),
'account_name' => $this->format($dao->to_account_name),
@@ -213,9 +215,9 @@ public function makeExport($export) {
'contact_name' => $this->format($dao->contact_to_name),
'payment_instrument' => $this->format($dao->payment_instrument),
'check_number' => $this->format($dao->check_number),
- ),
- 'splits' => array(),
- );
+ ],
+ 'splits' => [],
+ ];
/*
* splits has two possibilities depending on FROM account
@@ -249,30 +251,30 @@ public function makeExport($export) {
WHERE eft.entity_table = 'civicrm_financial_item'
AND eft.financial_trxn_id = %1";
- $itemParams = array(1 => array($dao->financial_trxn_id, 'Integer'));
+ $itemParams = [1 => [$dao->financial_trxn_id, 'Integer']];
$itemDAO = CRM_Core_DAO::executeQuery($item_sql, $itemParams);
while ($itemDAO->fetch()) {
// add to running list of accounts
if (!empty($itemDAO->account_id) && !isset($accounts[$itemDAO->account_id])) {
- $accounts[$itemDAO->account_id] = array(
+ $accounts[$itemDAO->account_id] = [
'name' => $this->format($itemDAO->account_name),
'account_code' => $this->format($itemDAO->account_code),
'description' => $this->format($itemDAO->account_description),
'type' => $this->format($itemDAO->account_type_code),
- );
+ ];
}
if (!empty($itemDAO->contact_id) && !isset($contacts[$itemDAO->contact_id])) {
- $contacts[$itemDAO->contact_id] = array(
+ $contacts[$itemDAO->contact_id] = [
'name' => $this->format($itemDAO->contact_name),
'first_name' => $this->format($itemDAO->contact_first_name),
'last_name' => $this->format($itemDAO->contact_last_name),
- );
+ ];
}
// add split line for this item
- $journalEntries[$dao->financial_trxn_id]['splits'][$itemDAO->financial_item_id] = array(
+ $journalEntries[$dao->financial_trxn_id]['splits'][$itemDAO->financial_item_id] = [
'trxn_date' => $this->format($itemDAO->transaction_date, 'date'),
'spl_id' => $this->format($itemDAO->financial_item_id),
'account_name' => $this->format($itemDAO->account_name),
@@ -282,13 +284,12 @@ public function makeExport($export) {
'description' => $this->format($itemDAO->description),
'check_number' => $this->format($itemDAO->check_number),
'currency' => $this->format($itemDAO->currency),
- );
+ ];
} // end items loop
- $itemDAO->free();
}
else {
// In this case, split record just uses the FROM account from the trxn, and there's only one record here
- $journalEntries[$dao->financial_trxn_id]['splits'][] = array(
+ $journalEntries[$dao->financial_trxn_id]['splits'][] = [
'trxn_date' => $this->format($dao->trxn_date, 'date'),
'spl_id' => $this->format($dao->financial_trxn_id),
'account_name' => $this->format($dao->from_account_name),
@@ -298,14 +299,14 @@ public function makeExport($export) {
'payment_instrument' => $this->format($dao->payment_instrument),
'check_number' => $this->format($dao->check_number),
'currency' => $this->format($dao->currency),
- );
+ ];
}
}
- $exportParams = array(
+ $exportParams = [
'accounts' => $accounts,
'contacts' => $contacts,
'journalEntries' => $journalEntries,
- );
+ ];
self::export($exportParams);
}
parent::initiateDownload();
diff --git a/CRM/Financial/BAO/FinancialAccount.php b/CRM/Financial/BAO/FinancialAccount.php
index 5b321634d8ce..af012f8c9836 100644
--- a/CRM/Financial/BAO/FinancialAccount.php
+++ b/CRM/Financial/BAO/FinancialAccount.php
@@ -1,9 +1,9 @@
copyValues($params);
if ($financialAccount->find(TRUE)) {
@@ -72,8 +67,8 @@ public static function retrieve(&$params, &$defaults) {
* @param bool $is_active
* Value we want to set the is_active field.
*
- * @return CRM_Core_DAO|null
- * DAO object on success, null otherwise
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
@@ -106,7 +101,7 @@ public static function add(&$params) {
}
if (!empty($params['is_default'])) {
$query = 'UPDATE civicrm_financial_account SET is_default = 0 WHERE financial_account_type_id = %1';
- $queryParams = array(1 => array($params['financial_account_type_id'], 'Integer'));
+ $queryParams = [1 => [$params['financial_account_type_id'], 'Integer']];
CRM_Core_DAO::executeQuery($query, $queryParams);
}
@@ -148,11 +143,11 @@ public static function del($financialAccountId) {
$check = FALSE;
//check dependencies
- $dependency = array(
- array('Core', 'FinancialTrxn', 'to_financial_account_id'),
- array('Financial', 'FinancialTypeAccount', 'financial_account_id'),
- array('Financial', 'FinancialItem', 'financial_account_id'),
- );
+ $dependency = [
+ ['Core', 'FinancialTrxn', 'to_financial_account_id'],
+ ['Financial', 'FinancialTypeAccount', 'financial_account_id'],
+ ['Financial', 'FinancialItem', 'financial_account_id'],
+ ];
foreach ($dependency as $name) {
require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
$className = "CRM_{$name[0]}_BAO_{$name[1]}";
@@ -191,10 +186,10 @@ public static function getAccountingCode($financialTypeId) {
LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
WHERE cft.id = %1
AND account_relationship = %2";
- $params = array(
- 1 => array($financialTypeId, 'Integer'),
- 2 => array($relationTypeId, 'Integer'),
- );
+ $params = [
+ 1 => [$financialTypeId, 'Integer'],
+ 2 => [$relationTypeId, 'Integer'],
+ ];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -219,11 +214,11 @@ public static function getARAccounts($financialAccountId, $financialAccountTypeI
}
$query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
AND id != %3 AND is_active = 1;";
- $params = array(
- 1 => array($financialAccountTypeId, 'Integer'),
- 2 => array(strtolower($accountTypeCode), 'String'),
- 3 => array($financialAccountId, 'Integer'),
- );
+ $params = [
+ 1 => [$financialAccountTypeId, 'Integer'],
+ 2 => [strtolower($accountTypeCode), 'String'],
+ 3 => [$financialAccountId, 'Integer'],
+ ];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -247,10 +242,10 @@ public static function getFinancialAccountForFinancialTypeByRelationship($financ
$relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationshipType}' "));
if (!isset(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
- $accounts = civicrm_api3('EntityFinancialAccount', 'get', array(
+ $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
'entity_id' => $financialTypeID,
'entity_table' => 'civicrm_financial_type',
- ));
+ ]);
foreach ($accounts['values'] as $account) {
Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
@@ -261,18 +256,33 @@ public static function getFinancialAccountForFinancialTypeByRelationship($financ
$incomeAccountRelationshipID = array_search('Income Account is', $accountRelationships);
$incomeAccountFinancialAccountID = Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
- foreach (array('Chargeback Account is', 'Credit/Contra Revenue Account is') as $optionalAccountRelationship) {
+ foreach (['Chargeback Account is', 'Credit/Contra Revenue Account is'] as $optionalAccountRelationship) {
$accountRelationshipID = array_search($optionalAccountRelationship, $accountRelationships);
if (empty(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
}
}
-
+ if (!isset(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
+ Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId] = NULL;
+ }
}
return Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId];
}
+ /**
+ * Get the sales tax financial account id for the financial type id.
+ *
+ * This is a helper wrapper to make the function name more readable.
+ *
+ * @param int $financialAccountID
+ *
+ * @return int
+ */
+ public static function getSalesTaxFinancialAccount($financialAccountID) {
+ return self::getFinancialAccountForFinancialTypeByRelationship($financialAccountID, 'Sales Tax Account is');
+ }
+
/**
* Get Financial Account type relations.
*
@@ -282,10 +292,10 @@ public static function getFinancialAccountForFinancialTypeByRelationship($financ
*
*/
public static function getfinancialAccountRelations($flip = FALSE) {
- $params = array('labelColumn' => 'name');
+ $params = ['labelColumn' => 'name'];
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
$accountRelationships = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
- $Links = array(
+ $Links = [
'Expense Account is' => 'Expenses',
'Accounts Receivable Account is' => 'Asset',
'Income Account is' => 'Revenue',
@@ -295,7 +305,7 @@ public static function getfinancialAccountRelations($flip = FALSE) {
'Discounts Account is' => 'Revenue',
'Sales Tax Account is' => 'Liability',
'Deferred Revenue Account is' => 'Liability',
- );
+ ];
if (!$flip) {
foreach ($Links as $accountRelation => $accountType) {
$financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
@@ -316,12 +326,12 @@ public static function getfinancialAccountRelations($flip = FALSE) {
*
*/
public static function getDeferredFinancialType() {
- $deferredFinancialType = array();
+ $deferredFinancialType = [];
$query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
WHERE ce.entity_table = 'civicrm_financial_type' AND ce.account_relationship = %1 AND cft.is_active = 1";
$deferredAccountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
- $queryParams = array(1 => array($deferredAccountRel, 'Integer'));
+ $queryParams = [1 => [$deferredAccountRel, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
while ($dao->fetch()) {
$deferredFinancialType[$dao->entity_id] = $dao->name;
@@ -344,20 +354,20 @@ public static function validateFinancialAccount($financialAccountId, $financialA
INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
LIMIT 1";
- $params = array('labelColumn' => 'name');
+ $params = ['labelColumn' => 'name'];
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
- $params = array(
- 1 => array($financialAccountId, 'Integer'),
- 2 => array(
+ $params = [
+ 1 => [$financialAccountId, 'Integer'],
+ 2 => [
implode(',',
- array(
+ [
array_search('Revenue', $financialAccountType),
array_search('Liability', $financialAccountType),
- )
+ ]
),
'Text',
- ),
- );
+ ],
+ ];
$result = CRM_Core_DAO::singleValueQuery($sql, $params);
if ($result && $result != $financialAccountTypeID) {
return TRUE;
@@ -382,13 +392,13 @@ public static function validateFinancialAccount($financialAccountId, $financialA
*
*/
public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $priceSetFields = NULL) {
- if (!CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
+ if (!Civi::settings()->get('deferred_revenue_enabled')) {
return FALSE;
}
$recognitionDate = CRM_Utils_Array::value('revenue_recognition_date', $params);
if (!(!CRM_Utils_System::isNull($recognitionDate)
|| ($contributionID && isset($params['prevContribution'])
- && !CRM_Utils_System::isNull($params['prevContribution']->revenue_recognition_date)))
+ && !CRM_Utils_System::isNull($params['prevContribution']->revenue_recognition_date)))
) {
return FALSE;
}
@@ -401,7 +411,7 @@ public static function checkFinancialTypeHasDeferred($params, $contributionID =
if (($contributionID || !empty($params['price_set_id'])) && empty($lineItems)) {
if (!$contributionID) {
CRM_Price_BAO_PriceSet::processAmount($priceSetFields,
- $params, $items);
+ $params, $items);
}
else {
$items = CRM_Price_BAO_LineItem::getLineItems($contributionID, 'contribution', TRUE, TRUE, TRUE);
@@ -440,13 +450,13 @@ public static function checkFinancialTypeHasDeferred($params, $contributionID =
*
*/
public static function getAllDeferredFinancialAccount() {
- $financialAccount = array();
- $result = civicrm_api3('EntityFinancialAccount', 'get', array(
+ $financialAccount = [];
+ $result = civicrm_api3('EntityFinancialAccount', 'get', [
'sequential' => 1,
- 'return' => array("financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"),
+ 'return' => ["financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"],
'entity_table' => "civicrm_financial_type",
'account_relationship' => "Deferred Revenue Account is",
- ));
+ ]);
if ($result['count'] > 0) {
foreach ($result['values'] as $key => $value) {
$financialAccount[$value['financial_account_id.id']] = $value['financial_account_id.name'] . ' (' . $value['financial_account_id.accounting_code'] . ')';
@@ -464,13 +474,13 @@ public static function getAllDeferredFinancialAccount() {
*
*/
public static function getOrganizationNames($checkPermissions = TRUE) {
- $result = civicrm_api3('FinancialAccount', 'get', array(
- 'return' => array("contact_id.organization_name", "contact_id"),
+ $result = civicrm_api3('FinancialAccount', 'get', [
+ 'return' => ["contact_id.organization_name", "contact_id"],
'contact_id.is_deleted' => 0,
- 'options' => array('limit' => 0),
+ 'options' => ['limit' => 0],
'check_permissions' => $checkPermissions,
- ));
- $organizationNames = array();
+ ]);
+ $organizationNames = [];
foreach ($result['values'] as $values) {
$organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
}
diff --git a/CRM/Financial/BAO/FinancialItem.php b/CRM/Financial/BAO/FinancialItem.php
index 2425628cc19d..4e5ff50bbcf5 100644
--- a/CRM/Financial/BAO/FinancialItem.php
+++ b/CRM/Financial/BAO/FinancialItem.php
@@ -1,9 +1,9 @@
contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
$itemStatus = array_search('Partially paid', $financialItemStatus);
}
- $params = array(
+ $params = [
'transaction_date' => CRM_Utils_Date::isoToMysql($contribution->receive_date),
'contact_id' => $contribution->contact_id,
'amount' => $lineItem->line_total,
@@ -98,32 +98,26 @@ public static function add($lineItem, $contribution, $taxTrxnID = FALSE, $trxnId
'entity_id' => $lineItem->id,
'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . $lineItem->label,
'status_id' => $itemStatus,
- );
+ ];
if ($taxTrxnID) {
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
$params['amount'] = $lineItem->tax_amount;
$params['description'] = $taxTerm;
- $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
+ $accountRelName = 'Sales Tax Account is';
}
else {
$accountRelName = 'Income Account is';
if (property_exists($contribution, 'revenue_recognition_date') && !CRM_Utils_System::isNull($contribution->revenue_recognition_date)) {
$accountRelName = 'Deferred Revenue Account is';
}
- $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$accountRelName}' "));
}
if ($lineItem->financial_type_id) {
- $searchParams = array(
- 'entity_table' => 'civicrm_financial_type',
- 'entity_id' => $lineItem->financial_type_id,
- 'account_relationship' => $accountRel,
+ $params['financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
+ $lineItem->financial_type_id,
+ $accountRelName
);
-
- $result = array();
- CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
- $params['financial_account_id'] = CRM_Utils_Array::value('financial_account_id', $result);
}
if (empty($trxnId)) {
$trxnId['id'] = CRM_Contribute_BAO_Contribution::$_trxnIDs;
@@ -167,15 +161,15 @@ public static function create(&$params, $ids = NULL, $trxnIds = NULL) {
$financialtrxnIDS = CRM_Utils_Array::value('id', $trxnIds);
if (!empty($financialtrxnIDS)) {
if (!is_array($financialtrxnIDS)) {
- $financialtrxnIDS = array($financialtrxnIDS);
+ $financialtrxnIDS = [$financialtrxnIDS];
}
foreach ($financialtrxnIDS as $tID) {
- $entity_financial_trxn_params = array(
+ $entity_financial_trxn_params = [
'entity_table' => "civicrm_financial_item",
'entity_id' => $financialItem->id,
'financial_trxn_id' => $tID,
'amount' => $params['amount'],
- );
+ ];
if (!empty($ids['entityFinancialTrxnId'])) {
$entity_financial_trxn_params['id'] = $ids['entityFinancialTrxnId'];
}
@@ -195,9 +189,9 @@ public static function create(&$params, $ids = NULL, $trxnIds = NULL) {
* Takes an associative array and creates a entity financial transaction object.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * an assoc array of name/value pairs.
*
- * @return CRM_Core_BAO_FinancialTrxn
+ * @return CRM_Financial_DAO_EntityFinancialTrxn
*/
public static function createEntityTrxn($params) {
$entity_trxn = new CRM_Financial_DAO_EntityFinancialTrxn();
@@ -210,9 +204,9 @@ public static function createEntityTrxn($params) {
* Retrive entity financial trxn details.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * an assoc array of name/value pairs.
* @param bool $maxId
- * To retrive max id.
+ * To retrieve max id.
*
* @return array
*/
@@ -226,13 +220,13 @@ public static function retrieveEntityFinancialTrxn($params, $maxId = FALSE) {
}
$financialItem->find();
while ($financialItem->fetch()) {
- $financialItems[$financialItem->id] = array(
+ $financialItems[$financialItem->id] = [
'id' => $financialItem->id,
'entity_table' => $financialItem->entity_table,
'entity_id' => $financialItem->entity_id,
'financial_trxn_id' => $financialItem->financial_trxn_id,
'amount' => $financialItem->amount,
- );
+ ];
}
if (!empty($financialItems)) {
return $financialItems;
@@ -253,7 +247,7 @@ public static function retrieveEntityFinancialTrxn($params, $maxId = FALSE) {
* @param array $error
* Error to display.
*
- * @return array
+ * @return array|bool
*/
public static function checkContactPresent($contactIds, &$error) {
if (empty($contactIds)) {
@@ -292,17 +286,17 @@ public static function checkContactPresent($contactIds, &$error) {
*
* @param int $entityId
*
- * @return object CRM_Core_DAO
+ * @return array
*/
public static function getPreviousFinancialItem($entityId) {
- $params = array(
+ $params = [
'entity_id' => $entityId,
'entity_table' => 'civicrm_line_item',
- 'options' => array('limit' => 1, 'sort' => 'id DESC'),
- );
- $salesTaxFinancialAccounts = civicrm_api3('FinancialAccount', 'get', array('is_tax' => 1));
+ 'options' => ['limit' => 1, 'sort' => 'id DESC'],
+ ];
+ $salesTaxFinancialAccounts = civicrm_api3('FinancialAccount', 'get', ['is_tax' => 1]);
if ($salesTaxFinancialAccounts['count']) {
- $params['financial_account_id'] = array('NOT IN' => array_keys($salesTaxFinancialAccounts['values']));
+ $params['financial_account_id'] = ['NOT IN' => array_keys($salesTaxFinancialAccounts['values'])];
}
return civicrm_api3('FinancialItem', 'getsingle', $params);
}
diff --git a/CRM/Financial/BAO/FinancialType.php b/CRM/Financial/BAO/FinancialType.php
index 919b221707d6..618bec0d1941 100644
--- a/CRM/Financial/BAO/FinancialType.php
+++ b/CRM/Financial/BAO/FinancialType.php
@@ -1,9 +1,9 @@
id = $financialTypeId;
$financialType->find(TRUE);
- // tables to ingore checks for financial_type_id
- $ignoreTables = array('CRM_Financial_DAO_EntityFinancialAccount');
+ // tables to ignore checks for financial_type_id
+ $ignoreTables = ['CRM_Financial_DAO_EntityFinancialAccount'];
// TODO: if (!$financialType->find(true)) {
// ensure that we have no objects that have an FK to this financial type id TODO: that cannot be null
$occurrences = $financialType->findReferences();
if ($occurrences) {
- $tables = array();
+ $tables = [];
foreach ($occurrences as $occurrence) {
$className = get_class($occurrence);
if (!in_array($className, $tables) && !in_array($className, $ignoreTables)) {
@@ -155,9 +153,9 @@ public static function del($financialTypeId) {
}
}
if (!empty($tables)) {
- $message = ts('The following tables have an entry for this financial type: %1', array('%1' => implode(', ', $tables)));
+ $message = ts('The following tables have an entry for this financial type: %1', [1 => implode(', ', $tables)]);
- $errors = array();
+ $errors = [];
$errors['is_error'] = 1;
$errors['error_message'] = $message;
return $errors;
@@ -184,7 +182,7 @@ public static function del($financialTypeId) {
public static function getIncomeFinancialType() {
// Financial Type
$financialType = CRM_Contribute_PseudoConstant::financialType();
- $revenueFinancialType = array();
+ $revenueFinancialType = [];
$relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
CRM_Core_PseudoConstant::populate(
$revenueFinancialType,
@@ -219,32 +217,69 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
return FALSE;
}
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
- $prefix = ts('CiviCRM') . ': ';
- $actions = array('add', 'view', 'edit', 'delete');
+ $actions = [
+ 'add' => ts('add'),
+ 'view' => ts('view'),
+ 'edit' => ts('edit'),
+ 'delete' => ts('delete'),
+ ];
+
foreach ($financialTypes as $id => $type) {
- foreach ($actions as $action) {
+ foreach ($actions as $action => $action_ts) {
if ($descriptions) {
- $permissions[$action . ' contributions of type ' . $type] = array(
- $prefix . ts($action . ' contributions of type ') . $type,
- ts(ucfirst($action) . ' contributions of type ') . $type,
- );
+ $permissions[$action . ' contributions of type ' . $type] = [
+ ts("CiviCRM: %1 contributions of type %2", [1 => $action_ts, 2 => $type]),
+ ts('%1 contributions of type %2', [1 => $action_ts, 2 => $type]),
+ ];
}
else {
- $permissions[$action . ' contributions of type ' . $type] = $prefix . ts($action . ' contributions of type ') . $type;
+ $permissions[$action . ' contributions of type ' . $type] = ts("CiviCRM: %1 contributions of type %2", [1 => $action_ts, 2 => $type]);
}
}
}
if (!$descriptions) {
- $permissions['administer CiviCRM Financial Types'] = $prefix . ts('administer CiviCRM Financial Types');
+ $permissions['administer CiviCRM Financial Types'] = ts('CiviCRM: administer CiviCRM Financial Types');
}
else {
- $permissions['administer CiviCRM Financial Types'] = array(
- $prefix . ts('administer CiviCRM Financial Types'),
+ $permissions['administer CiviCRM Financial Types'] = [
+ ts('CiviCRM: administer CiviCRM Financial Types'),
ts('Administer access to Financial Types'),
- );
+ ];
}
}
+ /**
+ * Wrapper aroung getAvailableFinancialTypes to get all including disabled FinancialTypes
+ * @param int|string $action
+ * the type of action, can be add, view, edit, delete
+ * @param bool $resetCache
+ * load values from static cache
+ *
+ * @return array
+ */
+ public static function getAllAvailableFinancialTypes($action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
+ // Flush pseudoconstant cache
+ CRM_Contribute_PseudoConstant::flush('financialType');
+ $thisIsAUselessVariableButSolvesPHPError = NULL;
+ $financialTypes = self::getAvailableFinancialTypes($thisIsAUselessVariableButSolvesPHPError, $action, $resetCache, TRUE);
+ return $financialTypes;
+ }
+
+ /**
+ * Wrapper aroung getAvailableFinancialTypes to get all FinancialTypes Excluding Disabled ones.
+ * @param int|string $action
+ * the type of action, can be add, view, edit, delete
+ * @param bool $resetCache
+ * load values from static cache
+ *
+ * @return array
+ */
+ public static function getAllEnabledAvailableFinancialTypes($action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
+ $thisIsAUselessVariableButSolvesPHPError = NULL;
+ $financialTypes = self::getAvailableFinancialTypes($thisIsAUselessVariableButSolvesPHPError, $action, $resetCache);
+ return $financialTypes;
+ }
+
/**
* Get available Financial Types.
*
@@ -254,34 +289,35 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
* the type of action, can be add, view, edit, delete
* @param bool $resetCache
* load values from static cache
+ * @param bool $includeDisabled
+ * Whether we should load in disabled FinancialTypes or Not
*
* @return array
*/
- public static function getAvailableFinancialTypes(&$financialTypes = NULL, $action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
+ public static function getAvailableFinancialTypes(&$financialTypes = NULL, $action = CRM_Core_Action::VIEW, $resetCache = FALSE, $includeDisabled = FALSE) {
if (empty($financialTypes)) {
- $financialTypes = CRM_Contribute_PseudoConstant::financialType();
+ $financialTypes = CRM_Contribute_PseudoConstant::financialType(NULL, $includeDisabled);
}
if (!self::isACLFinancialTypeStatus()) {
return $financialTypes;
}
- $actions = array(
+ $actions = [
CRM_Core_Action::VIEW => 'view',
CRM_Core_Action::UPDATE => 'edit',
CRM_Core_Action::ADD => 'add',
CRM_Core_Action::DELETE => 'delete',
- );
- // check cached value
- if (CRM_Utils_Array::value($action, self::$_availableFinancialTypes) && !$resetCache) {
- $financialTypes = self::$_availableFinancialTypes[$action];
- return self::$_availableFinancialTypes[$action];
- }
- foreach ($financialTypes as $finTypeId => $type) {
- if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
- unset($financialTypes[$finTypeId]);
+ ];
+
+ if (!isset(\Civi::$statics[__CLASS__]['available_types_' . $action])) {
+ foreach ($financialTypes as $finTypeId => $type) {
+ if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
+ unset($financialTypes[$finTypeId]);
+ }
}
+ \Civi::$statics[__CLASS__]['available_types_' . $action] = $financialTypes;
}
- self::$_availableFinancialTypes[$action] = $financialTypes;
- return $financialTypes;
+ $financialTypes = \Civi::$statics[__CLASS__]['available_types_' . $action];
+ return \Civi::$statics[__CLASS__]['available_types_' . $action];
}
/**
@@ -301,12 +337,12 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
if (!self::isACLFinancialTypeStatus()) {
return $membershipTypes;
}
- $actions = array(
+ $actions = [
CRM_Core_Action::VIEW => 'view',
CRM_Core_Action::UPDATE => 'edit',
CRM_Core_Action::ADD => 'add',
CRM_Core_Action::DELETE => 'delete',
- );
+ ];
foreach ($membershipTypes as $memTypeId => $type) {
$finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memTypeId, 'financial_type_id');
$finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
@@ -317,6 +353,26 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
return $membershipTypes;
}
+ /**
+ * This function adds the Financial ACL clauses to the where clause.
+ *
+ * This is currently somewhat mocking the native hook implementation
+ * for the acls that are in core. If the financialaclreport extension is installed
+ * core acls are not applied as that would result in them being applied twice.
+ *
+ * Long term we should either consolidate the financial acls in core or use only the extension.
+ * Both require substantial clean up before implementing and by the time the code is clean enough to
+ * take the final step we should
+ * be able to implement by removing one half of the other of this function.
+ *
+ * @param array $whereClauses
+ */
+ public static function addACLClausesToWhereClauses(&$whereClauses) {
+ $contributionBAO = new CRM_Contribute_BAO_Contribution();
+ $whereClauses = array_merge($whereClauses, $contributionBAO->addSelectWhereClause());
+
+ }
+
/**
* Function to build a permissioned sql where clause based on available financial types.
*
@@ -329,11 +385,12 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
*
*/
public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
+ // @todo the relevant addSelectWhere clause should be called.
if (!self::isACLFinancialTypeStatus()) {
return FALSE;
}
if (is_array($whereClauses)) {
- self::getAvailableFinancialTypes($types);
+ $types = self::getAllEnabledAvailableFinancialTypes();
if (empty($types)) {
$whereClauses[] = ' ' . $alias . '.financial_type_id IN (0)';
}
@@ -343,7 +400,7 @@ public static function buildPermissionedClause(&$whereClauses, $component = NULL
}
else {
if ($component == 'contribution') {
- self::getAvailableFinancialTypes($types);
+ $types = self::getAllEnabledAvailableFinancialTypes();
$column = "financial_type_id";
}
if ($component == 'membership') {
@@ -413,8 +470,7 @@ public static function checkPermissionToEditFinancialType($financialTypeID) {
if (!self::isACLFinancialTypeStatus()) {
return TRUE;
}
- // @todo consider adding back in disabled types here.
- CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::UPDATE);
+ $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(CRM_Core_Action::UPDATE);
return isset($financialTypes[$financialTypeID]);
}
@@ -426,15 +482,17 @@ public static function checkPermissionToEditFinancialType($financialTypeID) {
* @return bool
*/
public static function isACLFinancialTypeStatus() {
- if (array_key_exists('acl_financial_type', self::$_statusACLFt)) {
- return self::$_statusACLFt['acl_financial_type'];
- }
- $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
- self::$_statusACLFt['acl_financial_type'] = FALSE;
- if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
- self::$_statusACLFt['acl_financial_type'] = TRUE;
+ if (!isset(\Civi::$statics[__CLASS__]['is_acl_enabled'])) {
+ \Civi::$statics[__CLASS__]['is_acl_enabled'] = FALSE;
+ $realSetting = \Civi::$statics[__CLASS__]['is_acl_enabled'] = Civi::settings()->get('acl_financial_type');
+ if (!$realSetting) {
+ $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
+ if (!empty($contributeSettings['acl_financial_type'])) {
+ \Civi::$statics[__CLASS__]['is_acl_enabled'] = TRUE;
+ }
+ }
}
- return self::$_statusACLFt['acl_financial_type'];
+ return \Civi::$statics[__CLASS__]['is_acl_enabled'];
}
}
diff --git a/CRM/Financial/BAO/FinancialTypeAccount.php b/CRM/Financial/BAO/FinancialTypeAccount.php
index 92b8aa8d6199..be81d888e154 100644
--- a/CRM/Financial/BAO/FinancialTypeAccount.php
+++ b/CRM/Financial/BAO/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
copyValues($params);
$financialTypeAccount->find();
@@ -111,16 +105,16 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'entity_id');
// check dependencies
// FIXME more table containing financial_type_id to come
- $dependency = array(
- array('Contribute', 'Contribution'),
- array('Contribute', 'ContributionPage'),
- array('Member', 'MembershipType'),
- array('Price', 'PriceFieldValue'),
- array('Grant', 'Grant'),
- array('Contribute', 'PremiumsProduct'),
- array('Contribute', 'Product'),
- array('Price', 'LineItem'),
- );
+ $dependency = [
+ ['Contribute', 'Contribution'],
+ ['Contribute', 'ContributionPage'],
+ ['Member', 'MembershipType'],
+ ['Price', 'PriceFieldValue'],
+ ['Grant', 'Grant'],
+ ['Contribute', 'PremiumsProduct'],
+ ['Contribute', 'Product'],
+ ['Price', 'LineItem'],
+ ];
foreach ($dependency as $name) {
$daoString = 'CRM_' . $name[0] . '_DAO_' . $name[1];
@@ -134,11 +128,11 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
if ($check) {
if ($name[1] == 'PremiumsProduct' || $name[1] == 'Product') {
- CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship while the Financial Type is used for a Premium.', array(1 => $relationValues[$financialTypeAccountId])));
+ CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship while the Financial Type is used for a Premium.', [1 => $relationValues[$financialTypeAccountId]]));
}
else {
$accountRelationShipId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'account_relationship');
- CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship because it is being referenced by one or more of the following types of records: Contributions, Contribution Pages, or Membership Types. Consider disabling this type instead if you no longer want it used.', array(1 => $relationValues[$accountRelationShipId])), NULL, 'error');
+ CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship because it is being referenced by one or more of the following types of records: Contributions, Contribution Pages, or Membership Types. Consider disabling this type instead if you no longer want it used.', [1 => $relationValues[$accountRelationShipId]]), NULL, 'error');
}
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=browse&aid={$accountId}"));
}
@@ -148,7 +142,7 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
$financialType->id = $financialTypeAccountId;
$financialType->find(TRUE);
$financialType->delete();
- CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', array(1 => $relationValues[$financialType->account_relationship])));
+ CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', [1 => $relationValues[$financialType->account_relationship]]));
}
/**
@@ -157,30 +151,30 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
* @param int $paymentInstrumentValue
* Payment instrument value.
*
- * @return array|null|string
+ * @return null|int
*/
- public static function getInstrumentFinancialAccount($paymentInstrumentValue = NULL) {
- if (!self::$financialAccount) {
- $query = "SELECT ceft.financial_account_id, cov.value
-FROM civicrm_entity_financial_account ceft
-INNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'
-INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
-WHERE cog.name = 'payment_instrument' ";
-
- if ($paymentInstrumentValue) {
- $query .= " AND cov.value = '{$paymentInstrumentValue}' ";
- return CRM_Core_DAO::singleValueQuery($query);
+ public static function getInstrumentFinancialAccount($paymentInstrumentValue) {
+ if (!isset(\Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue])) {
+ $paymentInstrumentID = civicrm_api3('OptionValue', 'getvalue', [
+ 'return' => 'id',
+ 'value' => $paymentInstrumentValue,
+ 'option_group_id' => "payment_instrument",
+ ]);
+ $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
+ 'return' => 'financial_account_id',
+ 'entity_table' => 'civicrm_option_value',
+ 'entity_id' => $paymentInstrumentID,
+ 'options' => ['limit' => 1],
+ 'sequential' => 1,
+ ])['values'];
+ if (empty($accounts)) {
+ \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue] = NULL;
}
else {
- $result = CRM_Core_DAO::executeQuery($query);
- while ($result->fetch()) {
- self::$financialAccount[$result->value] = $result->financial_account_id;
- }
- return self::$financialAccount;
+ \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue] = $accounts[0]['financial_account_id'];
}
}
-
- return $paymentInstrumentValue ? self::$financialAccount[$paymentInstrumentValue] : self::$financialAccount;
+ return \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue];
}
/**
@@ -193,40 +187,40 @@ public static function getInstrumentFinancialAccount($paymentInstrumentValue = N
* @return array
*/
public static function createDefaultFinancialAccounts($financialType) {
- $titles = array();
+ $titles = [];
$financialAccountTypeID = CRM_Core_OptionGroup::values('financial_account_type', FALSE, FALSE, FALSE, NULL, 'name');
$accountRelationship = CRM_Core_OptionGroup::values('account_relationship', FALSE, FALSE, FALSE, NULL, 'name');
- $relationships = array(
+ $relationships = [
array_search('Accounts Receivable Account is', $accountRelationship) => array_search('Asset', $financialAccountTypeID),
array_search('Expense Account is', $accountRelationship) => array_search('Expenses', $financialAccountTypeID),
array_search('Cost of Sales Account is', $accountRelationship) => array_search('Cost of Sales', $financialAccountTypeID),
array_search('Income Account is', $accountRelationship) => array_search('Revenue', $financialAccountTypeID),
- );
+ ];
$dao = CRM_Core_DAO::executeQuery('SELECT id, financial_account_type_id FROM civicrm_financial_account WHERE name LIKE %1',
- array(1 => array($financialType->name, 'String'))
+ [1 => [$financialType->name, 'String']]
);
$dao->fetch();
- $existingFinancialAccount = array();
+ $existingFinancialAccount = [];
if (!$dao->N) {
- $params = array(
+ $params = [
'name' => $financialType->name,
'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id'),
'financial_account_type_id' => array_search('Revenue', $financialAccountTypeID),
'description' => $financialType->description,
'account_type_code' => 'INC',
'is_active' => 1,
- );
+ ];
$financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
}
else {
$existingFinancialAccount[$dao->financial_account_type_id] = $dao->id;
}
- $params = array(
+ $params = [
'entity_table' => 'civicrm_financial_type',
'entity_id' => $financialType->id,
- );
+ ];
foreach ($relationships as $key => $value) {
if (!array_key_exists($value, $existingFinancialAccount)) {
if ($accountRelationship[$key] == 'Accounts Receivable Account is') {
@@ -263,7 +257,7 @@ public static function createDefaultFinancialAccounts($financialType) {
self::add($params);
}
if (!empty($existingFinancialAccount)) {
- $titles = array();
+ $titles = [];
}
return $titles;
}
@@ -273,16 +267,17 @@ public static function createDefaultFinancialAccounts($financialType) {
*
* @param obj $financialTypeAccount of CRM_Financial_DAO_EntityFinancialAccount
*
+ * @throws CRM_Core_Exception
*/
public static function validateRelationship($financialTypeAccount) {
$financialAccountLinks = CRM_Financial_BAO_FinancialAccount::getfinancialAccountRelations();
$financialAccountType = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $financialTypeAccount->financial_account_id, 'financial_account_type_id');
if (CRM_Utils_Array::value($financialTypeAccount->account_relationship, $financialAccountLinks) != $financialAccountType) {
$accountRelationships = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
- $params = array(
+ $params = [
1 => $accountRelationships[$financialTypeAccount->account_relationship],
- );
- throw new Exception(ts("This financial account cannot have '%1' relationship.", $params));
+ ];
+ throw new CRM_Core_Exception(ts("This financial account cannot have '%1' relationship.", $params));
}
}
diff --git a/CRM/Financial/BAO/Payment.php b/CRM/Financial/BAO/Payment.php
new file mode 100644
index 000000000000..db3c92a60d0e
--- /dev/null
+++ b/CRM/Financial/BAO/Payment.php
@@ -0,0 +1,592 @@
+ $params['contribution_id']]);
+ $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($contribution['contribution_status_id'], 'name');
+
+ $isPaymentCompletesContribution = self::isPaymentCompletesContribution($params['contribution_id'], $params['total_amount']);
+
+ $whiteList = ['check_number', 'payment_processor_id', 'fee_amount', 'total_amount', 'contribution_id', 'net_amount', 'card_type_id', 'pan_truncation', 'trxn_result_code', 'payment_instrument_id', 'trxn_id'];
+ $paymentTrxnParams = array_intersect_key($params, array_fill_keys($whiteList, 1));
+ $paymentTrxnParams['is_payment'] = 1;
+ if (!empty($params['payment_processor'])) {
+ // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see getToFinancialAccount
+ // also anticipates it.
+ CRM_Core_Error::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
+ $paymentTrxnParams['payment_processor_id'] = $params['payment_processor'];
+ }
+ if (isset($paymentTrxnParams['payment_processor_id']) && empty($paymentTrxnParams['payment_processor_id'])) {
+ // Don't pass 0 - ie the Pay Later processor as it is a pseudo-processor.
+ unset($paymentTrxnParams['payment_processor_id']);
+ }
+ if (empty($paymentTrxnParams['payment_instrument_id'])) {
+ if (!empty($params['payment_processor_id'])) {
+ $paymentTrxnParams['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', ['return' => 'payment_instrument_id', 'id' => $paymentTrxnParams['payment_processor_id']]);
+ }
+ else {
+ // Fall back on the payment instrument already used - should we deprecate this?
+ $paymentTrxnParams['payment_instrument_id'] = $contribution['payment_instrument_id'];
+ }
+ }
+ if (empty($paymentTrxnParams['trxn_id']) && !empty($paymentTrxnParams['contribution_trxn_id'])) {
+ CRM_Core_Error::deprecatedFunctionWarning('contribution_trxn_id is deprecated - use trxn_id');
+ $paymentTrxnParams['trxn_id'] = $paymentTrxnParams['contribution_trxn_id'];
+ }
+
+ if ($params['total_amount'] > 0) {
+ $paymentTrxnParams['to_financial_account_id'] = CRM_Contribute_BAO_Contribution::getToFinancialAccount($contribution, $params);
+ $paymentTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
+ $paymentTrxnParams['trxn_date'] = CRM_Utils_Array::value('trxn_date', $params, CRM_Utils_Array::value('contribution_receive_date', $params, date('YmdHis')));
+ $paymentTrxnParams['currency'] = $contribution['currency'];
+ $paymentTrxnParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
+
+ $trxn = CRM_Core_BAO_FinancialTrxn::create($paymentTrxnParams);
+
+ // @todo - this is just weird & historical & inconsistent - why 2 tracks?
+ if (!empty($params['line_item']) && !empty($trxn)) {
+ foreach ($params['line_item'] as $values) {
+ foreach ($values as $id => $amount) {
+ $p = ['id' => $id];
+ $check = CRM_Price_BAO_LineItem::retrieve($p, $defaults);
+ if (empty($check)) {
+ throw new API_Exception('Please specify a valid Line Item.');
+ }
+ // get financial item
+ $sql = "SELECT fi.id
+ FROM civicrm_financial_item fi
+ INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
+ WHERE li.contribution_id = %1 AND li.id = %2";
+ $sqlParams = [
+ 1 => [$params['contribution_id'], 'Integer'],
+ 2 => [$id, 'Integer'],
+ ];
+ $fid = CRM_Core_DAO::singleValueQuery($sql, $sqlParams);
+ // Record Entity Financial Trxn
+ $eftParams = [
+ 'entity_table' => 'civicrm_financial_item',
+ 'financial_trxn_id' => $trxn->id,
+ 'amount' => $amount,
+ 'entity_id' => $fid,
+ ];
+ civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
+ }
+ }
+ }
+ elseif (!empty($trxn)) {
+ $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
+ if (!empty($lineItems)) {
+ // get financial item
+ list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution::getLastFinancialItemIds($params['contribution_id']);
+ $entityParams = [
+ 'contribution_total_amount' => $contribution['total_amount'],
+ 'trxn_total_amount' => $params['total_amount'],
+ 'trxn_id' => $trxn->id,
+ ];
+ $eftParams = [
+ 'entity_table' => 'civicrm_financial_item',
+ 'financial_trxn_id' => $entityParams['trxn_id'],
+ ];
+ foreach ($lineItems as $key => $value) {
+ if ($value['qty'] == 0) {
+ continue;
+ }
+ $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
+ $entityParams['line_item_amount'] = $value['line_total'];
+ CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
+ if (array_key_exists($value['price_field_value_id'], $taxItems)) {
+ $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
+ $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
+ CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
+ }
+ }
+ }
+ }
+ }
+ elseif ($params['total_amount'] < 0) {
+ $trxn = self::recordRefundPayment($params['contribution_id'], $params, FALSE);
+ }
+
+ if ($isPaymentCompletesContribution) {
+ if ($contributionStatus == 'Pending refund') {
+ // Ideally we could still call completetransaction as non-payment related actions should
+ // be outside this class. However, for now we just update the contribution here.
+ // Unit test cover in CRM_Event_BAO_AdditionalPaymentTest::testTransactionInfo.
+ civicrm_api3('Contribution', 'create',
+ [
+ 'id' => $contribution['id'],
+ 'contribution_status_id' => 'Completed',
+ ]
+ );
+ }
+ else {
+ civicrm_api3('Contribution', 'completetransaction', [
+ 'id' => $contribution['id'],
+ 'is_post_payment_create' => TRUE,
+ 'is_email_receipt' => $params['is_send_contribution_notification'],
+ ]);
+ // Get the trxn
+ $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
+ $ftParams = ['id' => $trxnId['financialTrxnId']];
+ $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams);
+ }
+ }
+ elseif ($contributionStatus === 'Pending') {
+ self::updateContributionStatus($contribution['id'], 'Partially Paid');
+ }
+ CRM_Contribute_BAO_Contribution::recordPaymentActivity($params['contribution_id'], CRM_Utils_Array::value('participant_id', $params), $params['total_amount'], $trxn->currency, $trxn->trxn_date);
+ return $trxn;
+ }
+
+ /**
+ * Send an email confirming a payment that has been received.
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ public static function sendConfirmation($params) {
+
+ $entities = self::loadRelatedEntities($params['id']);
+ $sendTemplateParams = [
+ 'groupName' => 'msg_tpl_workflow_contribution',
+ 'valueName' => 'payment_or_refund_notification',
+ 'PDFFilename' => ts('notification') . '.pdf',
+ 'contactId' => $entities['contact']['id'],
+ 'toName' => $entities['contact']['display_name'],
+ 'toEmail' => $entities['contact']['email'],
+ 'tplParams' => self::getConfirmationTemplateParameters($entities),
+ ];
+ if (!empty($params['from']) && !empty($params['check_permissions'])) {
+ // Filter from against permitted emails.
+ $validEmails = self::getValidFromEmailsForPayment($entities['event']['id'] ?? NULL);
+ if (!isset($validEmails[$params['from']])) {
+ // Ignore unpermitted parameter.
+ unset($params['from']);
+ }
+ }
+ $sendTemplateParams['from'] = $params['from'] ?? key(CRM_Core_BAO_Email::domainEmails());
+ return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
+ }
+
+ /**
+ * Get valid from emails for payment.
+ *
+ * @param int $eventID
+ *
+ * @return array
+ */
+ public static function getValidFromEmailsForPayment($eventID = NULL) {
+ if ($eventID) {
+ $emails = CRM_Event_BAO_Event::getFromEmailIds($eventID);
+ }
+ else {
+ $emails['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
+ }
+ return $emails['from_email_id'];
+ }
+
+ /**
+ * Load entities related to the current payment id.
+ *
+ * This gives us all the data we need to send an email confirmation but avoiding
+ * getting anything not tested for the confirmations. We retrieve the 'full' event as
+ * it has been traditionally assigned in full.
+ *
+ * @param int $id
+ *
+ * @return array
+ * - contact = ['id' => x, 'display_name' => y, 'email' => z]
+ * - event = [.... full event details......]
+ * - contribution = ['id' => x],
+ * - payment = [payment info + payment summary info]
+ * @throws \CiviCRM_API3_Exception
+ */
+ protected static function loadRelatedEntities($id) {
+ $entities = [];
+ $contributionID = (int) civicrm_api3('EntityFinancialTrxn', 'getvalue', [
+ 'financial_trxn_id' => $id,
+ 'entity_table' => 'civicrm_contribution',
+ 'return' => 'entity_id',
+ ]);
+ $entities['contribution'] = ['id' => $contributionID];
+ $entities['payment'] = array_merge(civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $id]),
+ CRM_Contribute_BAO_Contribution::getPaymentInfo($contributionID)
+ );
+
+ $contactID = self::getPaymentContactID($contributionID);
+ list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
+ $entities['contact'] = ['id' => $contactID, 'display_name' => $displayName, 'email' => $email];
+ $contact = civicrm_api3('Contact', 'getsingle', ['id' => $contactID, 'return' => 'email_greeting']);
+ $entities['contact']['email_greeting'] = $contact['email_greeting_display'];
+
+ $participantRecords = civicrm_api3('ParticipantPayment', 'get', [
+ 'contribution_id' => $contributionID,
+ 'api.Participant.get' => ['return' => 'event_id'],
+ 'sequential' => 1,
+ ])['values'];
+ if (!empty($participantRecords)) {
+ $entities['event'] = civicrm_api3('Event', 'getsingle', ['id' => $participantRecords[0]['api.Participant.get']['values'][0]['event_id']]);
+ if (!empty($entities['event']['is_show_location'])) {
+ $locationParams = [
+ 'entity_id' => $entities['event']['id'],
+ 'entity_table' => 'civicrm_event',
+ ];
+ $entities['location'] = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
+ }
+ }
+
+ return $entities;
+ }
+
+ /**
+ * @param int $contributionID
+ *
+ * @return int
+ */
+ public static function getPaymentContactID($contributionID) {
+ $contribution = civicrm_api3('Contribution', 'getsingle', [
+ 'id' => $contributionID ,
+ 'return' => ['contact_id'],
+ ]);
+ return (int) $contribution['contact_id'];
+ }
+
+ /**
+ * @param array $entities
+ * Related entities as an array keyed by the various entities.
+ *
+ * @return array
+ * Values required for the notification
+ * - contact_id
+ * - template_variables
+ * - event (DAO of event if relevant)
+ */
+ public static function getConfirmationTemplateParameters($entities) {
+ $templateVariables = [
+ 'contactDisplayName' => $entities['contact']['display_name'],
+ 'emailGreeting' => $entities['contact']['email_greeting'],
+ 'totalAmount' => $entities['payment']['total'],
+ 'amountOwed' => $entities['payment']['balance'],
+ 'totalPaid' => $entities['payment']['paid'],
+ 'paymentAmount' => $entities['payment']['total_amount'],
+ 'checkNumber' => CRM_Utils_Array::value('check_number', $entities['payment']),
+ 'receive_date' => $entities['payment']['trxn_date'],
+ 'paidBy' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $entities['payment']['payment_instrument_id']),
+ 'isShowLocation' => (!empty($entities['event']) ? $entities['event']['is_show_location'] : FALSE),
+ 'location' => CRM_Utils_Array::value('location', $entities),
+ 'event' => CRM_Utils_Array::value('event', $entities),
+ 'component' => (!empty($entities['event']) ? 'event' : 'contribution'),
+ 'isRefund' => $entities['payment']['total_amount'] < 0,
+ 'isAmountzero' => $entities['payment']['total_amount'] === 0,
+ 'refundAmount' => ($entities['payment']['total_amount'] < 0 ? $entities['payment']['total_amount'] : NULL),
+ 'paymentsComplete' => ($entities['payment']['balance'] == 0),
+ ];
+
+ return self::filterUntestedTemplateVariables($templateVariables);
+ }
+
+ /**
+ * Filter out any untested variables.
+ *
+ * This just serves to highlight if any variables are added without a unit test also being added.
+ *
+ * (if hit then add a unit test for the param & add to this array).
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ public static function filterUntestedTemplateVariables($params) {
+ $testedTemplateVariables = [
+ 'contactDisplayName',
+ 'totalAmount',
+ 'amountOwed',
+ 'paymentAmount',
+ 'event',
+ 'component',
+ 'checkNumber',
+ 'receive_date',
+ 'paidBy',
+ 'isShowLocation',
+ 'location',
+ 'isRefund',
+ 'isAmountzero',
+ 'refundAmount',
+ 'totalPaid',
+ 'paymentsComplete',
+ 'emailGreeting',
+ ];
+ // These are assigned by the payment form - they still 'get through' from the
+ // form for now without being in here but we should ideally load
+ // and assign. Note we should update the tpl to use {if $billingName}
+ // and ditch contributeMode - although it might need to be deprecated rather than removed.
+ $todoParams = [
+ 'contributeMode',
+ 'billingName',
+ 'address',
+ 'credit_card_type',
+ 'credit_card_number',
+ 'credit_card_exp_date',
+ ];
+ $filteredParams = [];
+ foreach ($testedTemplateVariables as $templateVariable) {
+ // This will cause an a-notice if any are NOT set - by design. Ensuring
+ // they are set prevents leakage.
+ $filteredParams[$templateVariable] = $params[$templateVariable];
+ }
+ return $filteredParams;
+ }
+
+ /**
+ * @param $contributionId
+ * @param $trxnData
+ * @param $updateStatus
+ * - deprecate this param
+ *
+ * @return CRM_Financial_DAO_FinancialTrxn
+ */
+ protected static function recordRefundPayment($contributionId, $trxnData, $updateStatus) {
+ list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
+
+ $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
+
+ $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
+ $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
+ $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+
+ $trxnData['total_amount'] = $trxnData['net_amount'] = $trxnData['total_amount'];
+ $trxnData['from_financial_account_id'] = $arAccountId;
+ $trxnData['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
+ // record the entry
+ $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
+
+ // note : not using the self::add method,
+ // the reason because it performs 'status change' related code execution for financial records
+ // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
+ // are coded below i.e. just updating financial_item status to 'Paid'
+ if ($updateStatus) {
+ CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
+ }
+ return $financialTrxn;
+ }
+
+ /**
+ * @param int $contributionId
+ * @param array $trxnData
+ * @param int $participantId
+ *
+ * @return \CRM_Core_BAO_FinancialTrxn
+ */
+ public static function recordPayment($contributionId, $trxnData, $participantId) {
+ list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
+
+ $trxnData['trxn_date'] = !empty($trxnData['trxn_date']) ? $trxnData['trxn_date'] : date('YmdHis');
+ $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
+
+ $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
+ $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
+ $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+
+ $params['partial_payment_total'] = $contributionDAO->total_amount;
+ $params['partial_amount_to_pay'] = $trxnData['total_amount'];
+ $trxnData['net_amount'] = !empty($trxnData['net_amount']) ? $trxnData['net_amount'] : $trxnData['total_amount'];
+ $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $trxnData);
+ $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $trxnData);
+ $params['check_number'] = CRM_Utils_Array::value('check_number', $trxnData);
+
+ // record the entry
+ $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
+ $toFinancialAccount = $arAccountId;
+ $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
+ if (!empty($trxnId)) {
+ $trxnId = $trxnId['trxn_id'];
+ }
+ elseif (!empty($contributionDAO->payment_instrument_id)) {
+ $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
+ }
+ else {
+ $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
+ $queryParams = [1 => [$relationTypeId, 'Integer']];
+ $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
+ }
+
+ // update statuses
+ // criteria for updates contribution total_amount == financial_trxns of partial_payments
+ $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
+FROM civicrm_financial_trxn ft
+LEFT JOIN civicrm_entity_financial_trxn eft
+ ON (ft.id = eft.financial_trxn_id)
+WHERE eft.entity_table = 'civicrm_contribution'
+ AND eft.entity_id = {$contributionId}
+ AND ft.to_financial_account_id != {$toFinancialAccount}
+ AND ft.status_id = {$completedStatusId}
+";
+ $query = CRM_Core_DAO::executeQuery($sql);
+ $query->fetch();
+ $sumOfPayments = $query->sum_of_payments;
+
+ // update statuses
+ if ($contributionDAO->total_amount == $sumOfPayments) {
+ // update contribution status and
+ // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
+ $contributionDAO->contribution_status_id = $completedStatusId;
+ $contributionDAO->cancel_date = 'null';
+ $contributionDAO->cancel_reason = NULL;
+ $netAmount = !empty($trxnData['net_amount']) ? NULL : $trxnData['total_amount'];
+ $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
+ $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
+ $contributionDAO->save();
+
+ //Change status of financial record too
+ $financialTrxn->status_id = $completedStatusId;
+ $financialTrxn->save();
+
+ // note : not using the self::add method,
+ // the reason because it performs 'status change' related code execution for financial records
+ // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
+ // are coded below i.e. just updating financial_item status to 'Paid'
+
+ if (!$participantId) {
+ $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
+ }
+ if ($participantId) {
+ // update participant status
+ $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
+ $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
+ foreach ($ids as $val) {
+ $participantUpdate['id'] = $val;
+ $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
+ CRM_Event_BAO_Participant::add($participantUpdate);
+ }
+ }
+
+ // Remove this - completeOrder does it.
+ CRM_Contribute_BAO_Contribution::updateMembershipBasedOnCompletionOfContribution(
+ $contributionDAO,
+ $contributionId,
+ $trxnData['trxn_date']
+ );
+
+ // update financial item statuses
+ $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
+ $sqlFinancialItemUpdate = "
+UPDATE civicrm_financial_item fi
+ LEFT JOIN civicrm_entity_financial_trxn eft
+ ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
+SET status_id = {$paidStatus}
+WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
+";
+ CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
+ }
+ return $financialTrxn;
+ }
+
+ /**
+ * The recordFinancialTransactions function has capricious requirements for input parameters - load them.
+ *
+ * The function needs rework but for now we need to give it what it wants.
+ *
+ * @param int $contributionId
+ *
+ * @return array
+ */
+ protected static function getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId) {
+ $getInfoOf['id'] = $contributionId;
+ $defaults = [];
+ $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults);
+
+ // build params for recording financial trxn entry
+ $params['contribution'] = $contributionDAO;
+ $params = array_merge($defaults, $params);
+ $params['skipLineItem'] = TRUE;
+ return [$contributionDAO, $params];
+ }
+
+ /**
+ * Does this payment complete the contribution
+ *
+ * @param int $contributionID
+ * @param float $paymentAmount
+ *
+ * @return bool
+ */
+ protected static function isPaymentCompletesContribution($contributionID, $paymentAmount) {
+ $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
+ $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
+ return ($cmp == 0 || $cmp == 1);
+ }
+
+ /**
+ * Update the status of the contribution.
+ *
+ * We pass the is_post_payment_create as we have already created the line items
+ *
+ * @param int $contributionID
+ * @param string $status
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ private static function updateContributionStatus(int $contributionID, string $status) {
+ civicrm_api3('Contribution', 'create',
+ [
+ 'id' => $contributionID,
+ 'is_post_payment_create' => TRUE,
+ 'contribution_status_id' => $status,
+ ]
+ );
+ }
+
+}
diff --git a/CRM/Financial/BAO/PaymentProcessor.php b/CRM/Financial/BAO/PaymentProcessor.php
index a3b89b4caaf0..27f563d5f1cd 100644
--- a/CRM/Financial/BAO/PaymentProcessor.php
+++ b/CRM/Financial/BAO/PaymentProcessor.php
@@ -1,9 +1,9 @@
copyValues($params);
- $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
- $ppTypeDAO->id = $params['payment_processor_type_id'];
- if (!$ppTypeDAO->find(TRUE)) {
- CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
- }
+ if (empty($params['id'])) {
+ $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
+ $ppTypeDAO->id = $params['payment_processor_type_id'];
+ if (!$ppTypeDAO->find(TRUE)) {
+ CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
+ }
- // also copy meta fields from the info DAO
- $processor->is_recur = $ppTypeDAO->is_recur;
- $processor->billing_mode = $ppTypeDAO->billing_mode;
- $processor->class_name = $ppTypeDAO->class_name;
- $processor->payment_type = $ppTypeDAO->payment_type;
+ // also copy meta fields from the info DAO
+ $processor->is_recur = $ppTypeDAO->is_recur;
+ $processor->billing_mode = $ppTypeDAO->billing_mode;
+ $processor->class_name = $ppTypeDAO->class_name;
+ $processor->payment_type = $ppTypeDAO->payment_type;
+ }
$processor->save();
// CRM-11826, add entry in civicrm_entity_financial_account
// if financial_account_id is not NULL
if (!empty($params['financial_account_id'])) {
$relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
- $values = array(
+ $values = [
'entity_table' => 'civicrm_payment_processor',
'entity_id' => $processor->id,
'account_relationship' => $relationTypeId,
'financial_account_id' => $params['financial_account_id'],
- );
+ ];
CRM_Financial_BAO_FinancialTypeAccount::add($values);
}
@@ -114,7 +117,7 @@ public static function getCreditCards($paymentProcessorID = NULL) {
$cards = json_decode($processor->accepted_credit_cards, TRUE);
return $cards;
}
- return array();
+ return [];
}
/**
@@ -148,9 +151,8 @@ public static function retrieve(&$params, &$defaults) {
* @param bool $is_active
* Value we want to set the is_active field.
*
- * @return CRM_Financial_DAO_PaymentProcessor|null
- * DAO object on success, null otherwise
- *
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
@@ -165,8 +167,8 @@ public static function setIsActive($id, $is_active) {
*/
public static function &getDefault() {
if (self::$_defaultPaymentProcessor == NULL) {
- $params = array('is_default' => 1);
- $defaults = array();
+ $params = ['is_default' => 1];
+ $defaults = [];
self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
}
return self::$_defaultPaymentProcessor;
@@ -214,36 +216,8 @@ public static function del($paymentProcessorID) {
* associated array with payment processor related fields
*/
public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
- $capabilities = ($mode == 'test') ? array('TestMode') : array();
- $processors = self::getPaymentProcessors($capabilities, array($paymentProcessorID));
- $processor = $processors[$paymentProcessorID];
- $fields = array(
- 'id',
- 'name',
- 'payment_processor_type_id',
- 'user_name',
- 'password',
- 'signature',
- 'url_site',
- 'url_api',
- 'url_recur',
- 'url_button',
- 'subject',
- 'class_name',
- 'is_recur',
- 'billing_mode',
- 'is_test',
- 'payment_type',
- 'is_default',
- );
- // Just to prevent e-Notices elsewhere we set all fields.
- foreach ($fields as $name) {
- if (!isset($processor)) {
- $processor[$name] = NULL;
- }
- }
- $processor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE,
- $processor['payment_processor_type_id'], 'name');
+ $capabilities = ($mode == 'test') ? ['TestMode'] : [];
+ $processors = self::getPaymentProcessors($capabilities, [$paymentProcessorID]);
return $processors[$paymentProcessorID];
}
@@ -256,16 +230,16 @@ public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
* Test payment processor ID.
*/
public static function getTestProcessorId($id) {
- $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', array(
+ $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
'id' => $id,
'return' => 'name',
- ));
- return civicrm_api3('payment_processor', 'getvalue', array(
+ ]);
+ return civicrm_api3('payment_processor', 'getvalue', [
'return' => 'id',
'name' => $liveProcessorName,
'is_test' => 1,
'domain_id' => CRM_Core_Config::domainID(),
- ));
+ ]);
}
/**
@@ -299,7 +273,7 @@ public static function defaultComparison($processor1, $processor2) {
*/
public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE) {
- $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . CRM_Core_Config::domainID();
+ $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config::domainID();
if (!$reset) {
$processors = CRM_Utils_Cache::singleton()->get($cacheKey);
if (!empty($processors)) {
@@ -307,11 +281,11 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
}
}
- $retrievalParameters = array(
+ $retrievalParameters = [
'is_active' => TRUE,
- 'options' => array('sort' => 'is_default DESC, name', 'limit' => 0),
+ 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
'api.payment_processor_type.getsingle' => 1,
- );
+ ];
if ($isCurrentDomainOnly) {
$retrievalParameters['domain_id'] = CRM_Core_Config::domainID();
}
@@ -324,7 +298,25 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
$processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
foreach ($processors['values'] as $processor) {
- $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur');
+ $fieldsToProvide = [
+ 'id',
+ 'name',
+ 'payment_processor_type_id',
+ 'user_name',
+ 'password',
+ 'signature',
+ 'url_site',
+ 'url_api',
+ 'url_recur',
+ 'url_button',
+ 'subject',
+ 'class_name',
+ 'is_recur',
+ 'billing_mode',
+ 'is_test',
+ 'payment_type',
+ 'is_default',
+ ];
foreach ($fieldsToProvide as $field) {
// Prevent e-notices in processor classes when not configured.
if (!isset($processor[$field])) {
@@ -336,7 +328,7 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
}
// Add the pay-later pseudo-processor.
- $processors['values'][0] = array(
+ $processors['values'][0] = [
'object' => new CRM_Core_Payment_Manual(),
'id' => 0,
'payment_processor_type_id' => 0,
@@ -351,7 +343,7 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
// be a row in the payment processor table before we do that.
'is_recur' => FALSE,
'is_test' => FALSE,
- );
+ ];
CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
@@ -375,27 +367,26 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
* @return array
* available processors
*/
- public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
- $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
+ public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
+ $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : [];
if (is_array($ids)) {
- $processors = self::getAllPaymentProcessors('all', TRUE, FALSE);
- }
- else {
- $processors = self::getAllPaymentProcessors('all', TRUE);
- }
-
- if (in_array('TestMode', $capabilities) && is_array($ids)) {
- $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
- foreach ($possibleLiveIDs as $possibleLiveID) {
- if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
- foreach ($testProcessors as $index => $testProcessor) {
- if ($testProcessor['name'] == $liveProcessorName) {
- $ids[] = $testProcessor['id'];
+ $processors = self::getAllPaymentProcessors('all', FALSE, FALSE);
+ if (in_array('TestMode', $capabilities)) {
+ $possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
+ foreach ($possibleLiveIDs as $possibleLiveID) {
+ if (isset($processors[$possibleLiveID]) && ($liveProcessorName = $processors[$possibleLiveID]['name']) != FALSE) {
+ foreach ($testProcessors as $index => $testProcessor) {
+ if ($testProcessor['name'] == $liveProcessorName) {
+ $ids[] = $testProcessor['id'];
+ }
}
}
}
+ $processors = $testProcessors;
}
- $processors = $testProcessors;
+ }
+ else {
+ $processors = self::getAllPaymentProcessors('all');
}
foreach ($processors as $index => $processor) {
@@ -430,6 +421,7 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
* - supportsBackOffice
* - supportsLiveMode
* - supportsFutureRecurDate
+ * - supportsRecurring
* - supportsCancelRecurring
* - supportsRecurContributionsForPledges
*
@@ -441,9 +433,13 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
*
* @return bool
*/
- public static function hasPaymentProcessorSupporting($capabilities = array()) {
- $result = self::getPaymentProcessors($capabilities);
- return (!empty($result)) ? TRUE : FALSE;
+ public static function hasPaymentProcessorSupporting($capabilities = []) {
+ $capabilitiesString = implode('', $capabilities);
+ if (!isset(\Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString])) {
+ $result = self::getPaymentProcessors($capabilities);
+ \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]) ? TRUE : FALSE;
+ }
+ return \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString];
}
/**
@@ -478,11 +474,11 @@ public static function hasPaymentProcessorSupporting($capabilities = array()) {
*/
public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
$result = NULL;
- if (!in_array($component, array(
+ if (!in_array($component, [
'membership',
'contribute',
'recur',
- ))
+ ])
) {
return $result;
}
@@ -506,6 +502,7 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
WHERE con.id = %1";
}
elseif ($component == 'recur') {
+ // @deprecated - use getPaymentProcessorForRecurringContribution.
$sql = "
SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
FROM civicrm_contribution_recur cr
@@ -515,7 +512,7 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
// We are interested in a single record.
$sql .= ' LIMIT 1';
- $params = array(1 => array($entityID, 'Integer'));
+ $params = [1 => [$entityID, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if (!$dao->fetch()) {
@@ -534,16 +531,82 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
}
elseif ($type == 'obj' && is_numeric($ppID)) {
try {
- $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', array('id' => $ppID));
+ $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
}
catch (API_Exception $e) {
// Unable to load the processor because this function uses an unreliable method to derive it.
// The function looks to load the payment processor ID from the contribution page, which
// can support multiple processors.
}
+
+ $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
$result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
}
return $result;
}
+ /**
+ * Get the payment processor associated with a recurring contribution series.
+ *
+ * @param int $contributionRecurID
+ *
+ * @return \CRM_Core_Payment
+ */
+ public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
+ $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
+ 'id' => $contributionRecurID,
+ 'return' => 'payment_processor_id',
+ ]);
+ return Civi\Payment\System::singleton()->getById($paymentProcessorId);
+ }
+
+ /**
+ * Get the name of the payment processor
+ *
+ * @param $paymentProcessorId
+ *
+ * @return null|string
+ */
+ public static function getPaymentProcessorName($paymentProcessorId) {
+ try {
+ $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
+ 'return' => ['name'],
+ 'id' => $paymentProcessorId,
+ ]);
+ return $paymentProcessor['name'];
+ }
+ catch (Exception $e) {
+ return ts('Unknown') . ' (' . $paymentProcessorId . ')';
+ }
+ }
+
+ /**
+ * Generate and assign an arbitrary value to a field of a test object.
+ *
+ * @param string $fieldName
+ * @param array $fieldDef
+ * @param int $counter
+ * The globally-unique ID of the test object.
+ */
+ protected function assignTestValue($fieldName, &$fieldDef, $counter) {
+ if ($fieldName === 'class_name') {
+ $this->class_name = 'Payment_Dummy';
+ }
+ else {
+ parent::assignTestValue($fieldName, $fieldDef, $counter);
+ }
+ }
+
+ /**
+ * Get the default financial account id for payment processor accounts.
+ *
+ * Note that there is only a 'name' field & no label field. If people customise
+ * name then this won't work. This is new best-effort functionality so that's non-regressive.
+ *
+ * The fix for that is to add a label value to the financial account table.
+ */
+ public static function getDefaultFinancialAccountID() {
+ return CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');
+ }
+
}
diff --git a/CRM/Financial/BAO/PaymentProcessorType.php b/CRM/Financial/BAO/PaymentProcessorType.php
index 2afcc0f8a65e..2a8f7ba0429a 100644
--- a/CRM/Financial/BAO/PaymentProcessorType.php
+++ b/CRM/Financial/BAO/PaymentProcessorType.php
@@ -1,9 +1,9 @@
1);
- $defaults = array();
+ $params = ['is_default' => 1];
+ $defaults = [];
self::$_defaultPaymentProcessorType = self::retrieve($params, $defaults);
}
return self::$_defaultPaymentProcessorType;
@@ -179,7 +179,7 @@ public static function del($paymentProcessorTypeId) {
FROM civicrm_payment_processor pp, civicrm_payment_processor_type ppt
WHERE pp.payment_processor_type_id = ppt.id AND ppt.id = %1";
- $params = array(1 => array($paymentProcessorTypeId, 'Integer'));
+ $params = [1 => [$paymentProcessorTypeId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
@@ -200,8 +200,8 @@ public static function del($paymentProcessorTypeId) {
*
* @return array
*/
- static private function getAllPaymentProcessorTypes($attr) {
- $ppt = array();
+ private static function getAllPaymentProcessorTypes($attr) {
+ $ppt = [];
$dao = new CRM_Financial_DAO_PaymentProcessorType();
$dao->find();
while ($dao->fetch()) {
diff --git a/CRM/Financial/DAO/Currency.php b/CRM/Financial/DAO/Currency.php
index 52cf12bedcf7..eac4ba014921 100644
--- a/CRM/Financial/DAO/Currency.php
+++ b/CRM/Financial/DAO/Currency.php
@@ -1,211 +1,198 @@
__table = 'civicrm_currency';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Currency ID') ,
- 'description' => 'Currency Id',
- 'required' => true,
+ 'title' => ts('Currency ID'),
+ 'description' => ts('Currency Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_currency.id',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => 'Currency Name',
+ 'title' => ts('Currency'),
+ 'description' => ts('Currency Name'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_currency.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'symbol' => array(
+ ],
+ ],
+ 'symbol' => [
'name' => 'symbol',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency Symbol') ,
- 'description' => 'Currency Symbol',
+ 'title' => ts('Currency Symbol'),
+ 'description' => ts('Currency Symbol'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_currency.symbol',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'numeric_code' => array(
+ ],
+ ],
+ 'numeric_code' => [
'name' => 'numeric_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency Numeric Code') ,
- 'description' => 'Numeric currency code',
+ 'title' => ts('Currency Numeric Code'),
+ 'description' => ts('Numeric currency code'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_currency.numeric_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- ) ,
- 'full_name' => array(
+ ],
+ 'full_name' => [
'name' => 'full_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Full Currency Name') ,
- 'description' => 'Full currency name',
+ 'title' => ts('Full Currency Name'),
+ 'description' => ts('Full currency name'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_currency.full_name',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -213,10 +200,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'currency', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'currency', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -224,15 +212,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'currency', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'currency', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/EntityFinancialAccount.php b/CRM/Financial/DAO/EntityFinancialAccount.php
index 338a68afd38e..b9abd0804aa9 100644
--- a/CRM/Financial/DAO/EntityFinancialAccount.php
+++ b/CRM/Financial/DAO/EntityFinancialAccount.php
@@ -1,226 +1,217 @@
__table = 'civicrm_entity_financial_account';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Financial Account ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Entity Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Links to an entity_table like civicrm_financial_type',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Links to an entity_table like civicrm_financial_type'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_account.entity_table',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'Links to an id in the entity_table, such as vid in civicrm_financial_type',
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Links to an id in the entity_table, such as vid in civicrm_financial_type'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.entity_id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'account_relationship' => array(
+ ],
+ 'account_relationship' => [
'name' => 'account_relationship',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Account Relationship') ,
- 'description' => 'FK to a new civicrm_option_value (account_relationship)',
- 'required' => true,
+ 'title' => ts('Account Relationship'),
+ 'description' => ts('FK to a new civicrm_option_value (account_relationship)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.account_relationship',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'account_relationship',
'optionEditPath' => 'civicrm/admin/options/account_relationship',
- )
- ) ,
- 'financial_account_id' => array(
+ ],
+ ],
+ 'financial_account_id' => [
'name' => 'financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account') ,
- 'description' => 'FK to the financial_account_id',
- 'required' => true,
+ 'title' => ts('Financial Account'),
+ 'description' => ts('FK to the financial_account_id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.financial_account_id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -228,10 +219,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_account', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -239,27 +231,33 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_account', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity_id_entity_table_account_relationship' => array(
+ $indices = [
+ 'index_entity_id_entity_table_account_relationship' => [
'name' => 'index_entity_id_entity_table_account_relationship',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
1 => 'entity_table',
2 => 'account_relationship',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_entity_financial_account::1::entity_id::entity_table::account_relationship',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/EntityFinancialTrxn.php b/CRM/Financial/DAO/EntityFinancialTrxn.php
index dc94113815e8..c14ad58b4ed8 100644
--- a/CRM/Financial/DAO/EntityFinancialTrxn.php
+++ b/CRM/Financial/DAO/EntityFinancialTrxn.php
@@ -1,215 +1,203 @@
__table = 'civicrm_entity_financial_trxn';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_trxn_id', 'civicrm_financial_trxn', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_trxn_id', 'civicrm_financial_trxn', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Financial Transaction ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Entity Financial Transaction ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_trxn.id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'May contain civicrm_financial_item, civicrm_contribution, civicrm_financial_trxn, civicrm_grant, etc',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('May contain civicrm_financial_item, civicrm_contribution, civicrm_financial_trxn, civicrm_grant, etc'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_trxn.entity_table',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_trxn.entity_id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'financial_trxn_id' => array(
+ ],
+ 'financial_trxn_id' => [
'name' => 'financial_trxn_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction Id') ,
+ 'title' => ts('Financial Transaction Id'),
+ 'where' => 'civicrm_entity_financial_trxn.financial_trxn_id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialTrxn',
- ) ,
- 'amount' => array(
+ ],
+ 'amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount') ,
- 'description' => 'allocated amount of transaction to this entity',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Amount'),
+ 'description' => ts('allocated amount of transaction to this entity'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_trxn.amount',
'headerPattern' => '/amount/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -217,10 +205,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_trxn', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -228,32 +217,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_trxn', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_entity_financial_trxn_entity_table' => array(
+ $indices = [
+ 'UI_entity_financial_trxn_entity_table' => [
'name' => 'UI_entity_financial_trxn_entity_table',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_entity_financial_trxn::0::entity_table',
- ) ,
- 'UI_entity_financial_trxn_entity_id' => array(
+ ],
+ 'UI_entity_financial_trxn_entity_id' => [
'name' => 'UI_entity_financial_trxn_entity_id',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_entity_financial_trxn::0::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialAccount.php b/CRM/Financial/DAO/FinancialAccount.php
index ec43d41a2f01..6c3c61988efc 100644
--- a/CRM/Financial/DAO/FinancialAccount.php
+++ b/CRM/Financial/DAO/FinancialAccount.php
@@ -1,392 +1,402 @@
__table = 'civicrm_financial_account';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_financial_account', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_account.id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Account Name') ,
- 'description' => 'Financial Account Name.',
- 'required' => true,
+ 'title' => ts('Financial Account Name'),
+ 'description' => ts('Financial Account Name.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_account.name',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'financial_account_contact_id' => array(
+ ],
+ 'financial_account_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID that is responsible for the funds in this account',
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID that is responsible for the funds in this account'),
+ 'where' => 'civicrm_financial_account.contact_id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'financial_account_type_id' => array(
+ ],
+ 'financial_account_type_id' => [
'name' => 'financial_account_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account Type') ,
- 'description' => 'pseudo FK into civicrm_option_value.',
- 'required' => true,
+ 'title' => ts('Financial Account Type'),
+ 'description' => ts('pseudo FK into civicrm_option_value.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_account.financial_account_type_id',
'default' => '3',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'financial_account_type',
'optionEditPath' => 'civicrm/admin/options/financial_account_type',
- )
- ) ,
- 'accounting_code' => array(
+ ],
+ ],
+ 'accounting_code' => [
'name' => 'accounting_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Accounting Code') ,
- 'description' => 'Optional value for mapping monies owed and received to accounting system codes.',
+ 'title' => ts('Accounting Code'),
+ 'description' => ts('Optional value for mapping monies owed and received to accounting system codes.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'export' => true,
'where' => 'civicrm_financial_account.accounting_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'account_type_code' => array(
+ ],
+ 'account_type_code' => [
'name' => 'account_type_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Account Type Code') ,
- 'description' => 'Optional value for mapping account types to accounting system account categories (QuickBooks Account Type Codes for example).',
+ 'title' => ts('Account Type Code'),
+ 'description' => ts('Optional value for mapping account types to accounting system account categories (QuickBooks Account Type Codes for example).'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'export' => true,
'where' => 'civicrm_financial_account.account_type_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Account Description') ,
- 'description' => 'Financial Type Description.',
+ 'title' => ts('Financial Account Description'),
+ 'description' => ts('Financial Type Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_account.description',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'parent_id' => array(
+ ],
+ 'parent_id' => [
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account Parent') ,
- 'description' => 'Parent ID in account hierarchy',
+ 'title' => ts('Financial Account Parent'),
+ 'description' => ts('Parent ID in account hierarchy'),
+ 'where' => 'civicrm_financial_account.parent_id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- ) ,
- 'is_header_account' => array(
+ ],
+ 'is_header_account' => [
'name' => 'is_header_account',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Header Financial Account?') ,
- 'description' => 'Is this a header account which does not allow transactions to be posted against it directly, but only to its sub-accounts?',
+ 'title' => ts('Header Financial Account?'),
+ 'description' => ts('Is this a header account which does not allow transactions to be posted against it directly, but only to its sub-accounts?'),
+ 'where' => 'civicrm_financial_account.is_header_account',
+ 'default' => '0',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_deductible' => array(
+ ],
+ 'is_deductible' => [
'name' => 'is_deductible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Deductible Financial Account?') ,
- 'description' => 'Is this account tax-deductible?',
+ 'title' => ts('Deductible Financial Account?'),
+ 'description' => ts('Is this account tax-deductible?'),
+ 'where' => 'civicrm_financial_account.is_deductible',
'default' => '1',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_tax' => array(
+ ],
+ 'is_tax' => [
'name' => 'is_tax',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Tax Financial Account?') ,
- 'description' => 'Is this account for taxes?',
+ 'title' => ts('Tax Financial Account?'),
+ 'description' => ts('Is this account for taxes?'),
+ 'where' => 'civicrm_financial_account.is_tax',
+ 'default' => '0',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'tax_rate' => array(
+ ],
+ 'tax_rate' => [
'name' => 'tax_rate',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Account Tax Rate') ,
- 'description' => 'The percentage of the total_amount that is due for this tax.',
- 'precision' => array(
+ 'title' => ts('Financial Account Tax Rate'),
+ 'description' => ts('The percentage of the total_amount that is due for this tax.'),
+ 'precision' => [
10,
- 8
- ) ,
+ 8,
+ ],
+ 'where' => 'civicrm_financial_account.tax_rate',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Reserved Financial Account?') ,
- 'description' => 'Is this a predefined system object?',
+ 'title' => ts('Reserved Financial Account?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'where' => 'civicrm_financial_account.is_reserved',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Account is Active') ,
- 'description' => 'Is this property active?',
+ 'title' => ts('Financial Account is Active'),
+ 'description' => ts('Is this property active?'),
+ 'where' => 'civicrm_financial_account.is_active',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Default Financial Account') ,
- 'description' => 'Is this account the default one (or default tax one) for its financial_account_type?',
+ 'title' => ts('Default Financial Account'),
+ 'description' => ts('Is this account the default one (or default tax one) for its financial_account_type?'),
+ 'where' => 'civicrm_financial_account.is_default',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -394,10 +404,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_account', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -405,25 +416,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_account', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_financial_account::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialItem.php b/CRM/Financial/DAO/FinancialItem.php
index 82d71822af91..2a106ef9237f 100644
--- a/CRM/Financial/DAO/FinancialItem.php
+++ b/CRM/Financial/DAO/FinancialItem.php
@@ -1,347 +1,347 @@
__table = 'civicrm_financial_item';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item ID') ,
- 'required' => true,
+ 'title' => ts('Financial Item ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Financial Item Created Date') ,
- 'description' => 'Date and time the item was created',
- 'required' => true,
+ 'title' => ts('Financial Item Created Date'),
+ 'description' => ts('Date and time the item was created'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.created_date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'transaction_date' => array(
+ ],
+ 'transaction_date' => [
'name' => 'transaction_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Financial Item Transaction Date') ,
- 'description' => 'Date and time of the source transaction',
- 'required' => true,
+ 'title' => ts('Financial Item Transaction Date'),
+ 'description' => ts('Date and time of the source transaction'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.transaction_date',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item Contact ID') ,
- 'description' => 'FK to Contact ID of contact the item is from',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Financial Item Contact ID'),
+ 'description' => ts('FK to Contact ID of contact the item is from'),
+ 'required' => TRUE,
'where' => 'civicrm_financial_item.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Item Description') ,
- 'description' => 'Human readable description of this item, to ease display without lookup of source item.',
+ 'title' => ts('Financial Item Description'),
+ 'description' => ts('Human readable description of this item, to ease display without lookup of source item.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_item.description',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'amount' => array(
+ ],
+ 'amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount') ,
- 'description' => 'Total amount of this item',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Amount'),
+ 'description' => ts('Total amount of this item'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_financial_item.amount',
+ 'headerPattern' => '/unit?.?amoun/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
+ 'default' => '0',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Item Currency') ,
- 'description' => 'Currency for the amount',
+ 'title' => ts('Financial Item Currency'),
+ 'description' => ts('Currency for the amount'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'export' => true,
'where' => 'civicrm_financial_item.currency',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'financial_account_id' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'financial_account_id' => [
'name' => 'financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account ID') ,
- 'description' => 'FK to civicrm_financial_account',
+ 'title' => ts('Financial Account ID'),
+ 'description' => ts('FK to civicrm_financial_account'),
+ 'where' => 'civicrm_financial_item.financial_account_id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'status_id' => array(
+ ],
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item Status ID') ,
- 'description' => 'Payment status: test, paid, part_paid, unpaid (if empty assume unpaid)',
- 'export' => true,
+ 'title' => ts('Financial Item Status ID'),
+ 'description' => ts('Payment status: test, paid, part_paid, unpaid (if empty assume unpaid)'),
'where' => 'civicrm_financial_item.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'financial_item_status',
'optionEditPath' => 'civicrm/admin/options/financial_item_status',
- )
- ) ,
- 'entity_table' => array(
+ ],
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'The table providing the source of this item such as civicrm_line_item',
+ 'title' => ts('Entity Table'),
+ 'description' => ts('The table providing the source of this item such as civicrm_line_item'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_financial_item.entity_table',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'The specific source item that is responsible for the creation of this financial_item',
+ 'title' => ts('Entity ID'),
+ 'description' => ts('The specific source item that is responsible for the creation of this financial_item'),
+ 'where' => 'civicrm_financial_item.entity_id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -349,10 +349,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_item', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -360,41 +361,47 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_item', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'IX_created_date' => array(
+ $indices = [
+ 'IX_created_date' => [
'name' => 'IX_created_date',
- 'field' => array(
+ 'field' => [
0 => 'created_date',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::created_date',
- ) ,
- 'IX_transaction_date' => array(
+ ],
+ 'IX_transaction_date' => [
'name' => 'IX_transaction_date',
- 'field' => array(
+ 'field' => [
0 => 'transaction_date',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::transaction_date',
- ) ,
- 'index_entity_id_entity_table' => array(
+ ],
+ 'index_entity_id_entity_table' => [
'name' => 'index_entity_id_entity_table',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
1 => 'entity_table',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::entity_id::entity_table',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialTrxn.php b/CRM/Financial/DAO/FinancialTrxn.php
index 7555097792ce..837ddd678225 100644
--- a/CRM/Financial/DAO/FinancialTrxn.php
+++ b/CRM/Financial/DAO/FinancialTrxn.php
@@ -1,486 +1,525 @@
__table = 'civicrm_financial_trxn';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'from_financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'to_financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_id', 'civicrm_payment_processor', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'from_financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'to_financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_id', 'civicrm_payment_processor', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction ID') ,
- 'required' => true,
+ 'title' => ts('Financial Transaction ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_trxn.id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'from_financial_account_id' => array(
+ ],
+ 'from_financial_account_id' => [
'name' => 'from_financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction From Account') ,
- 'description' => 'FK to financial_account table.',
+ 'title' => ts('Financial Transaction From Account'),
+ 'description' => ts('FK to financial_account table.'),
+ 'where' => 'civicrm_financial_trxn.from_financial_account_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'to_financial_account_id' => array(
+ ],
+ ],
+ 'to_financial_account_id' => [
'name' => 'to_financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction To Account') ,
- 'description' => 'FK to financial_financial_account table.',
+ 'title' => ts('Financial Transaction To Account'),
+ 'description' => ts('FK to financial_financial_account table.'),
+ 'where' => 'civicrm_financial_trxn.to_financial_account_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'trxn_date' => array(
+ ],
+ ],
+ 'trxn_date' => [
'name' => 'trxn_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Financial Transaction Date') ,
- 'description' => 'date transaction occurred',
+ 'title' => ts('Financial Transaction Date'),
+ 'description' => ts('date transaction occurred'),
+ 'where' => 'civicrm_financial_trxn.trxn_date',
'default' => 'NULL',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'total_amount' => array(
+ ],
+ ],
+ 'total_amount' => [
'name' => 'total_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Total Amount') ,
- 'description' => 'amount of transaction',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Financial Total Amount'),
+ 'description' => ts('amount of transaction'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_financial_trxn.total_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'fee_amount' => array(
+ ],
+ 'fee_amount' => [
'name' => 'fee_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Fee Amount') ,
- 'description' => 'actual processor fee if known - may be 0.',
- 'precision' => array(
+ 'title' => ts('Financial Fee Amount'),
+ 'description' => ts('actual processor fee if known - may be 0.'),
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_financial_trxn.fee_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'net_amount' => array(
+ ],
+ 'net_amount' => [
'name' => 'net_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Net Amount') ,
- 'description' => 'actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.',
- 'precision' => array(
+ 'title' => ts('Financial Net Amount'),
+ 'description' => ts('actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.'),
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_financial_trxn.net_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Financial Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.currency',
'headerPattern' => '/cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_payment' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'is_payment' => [
'name' => 'is_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Payment?') ,
- 'description' => 'Is this entry either a payment or a reversal of a payment?',
- 'import' => true,
+ 'title' => ts('Is Payment?'),
+ 'description' => ts('Is this entry either a payment or a reversal of a payment?'),
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.is_payment',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'trxn_id' => array(
+ ],
+ 'trxn_id' => [
'name' => 'trxn_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Transaction ID') ,
- 'description' => 'Transaction id supplied by external processor. This may not be unique.',
+ 'title' => ts('Transaction ID'),
+ 'description' => ts('Transaction id supplied by external processor. This may not be unique.'),
'maxlength' => 255,
- 'size' => CRM_Utils_Type::HUGE,
+ 'size' => 10,
+ 'where' => 'civicrm_financial_trxn.trxn_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'trxn_result_code' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'trxn_result_code' => [
'name' => 'trxn_result_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Transaction Result Code') ,
- 'description' => 'processor result code',
+ 'title' => ts('Transaction Result Code'),
+ 'description' => ts('processor result code'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_trxn.trxn_result_code',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'status_id' => array(
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction Status Id') ,
- 'description' => 'pseudo FK to civicrm_option_value of contribution_status_id option_group',
- 'import' => true,
+ 'title' => ts('Financial Transaction Status Id'),
+ 'description' => ts('pseudo FK to civicrm_option_value of contribution_status_id option_group'),
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.status_id',
'headerPattern' => '/status/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- 'payment_processor_id' => array(
+ ],
+ ],
+ 'payment_processor_id' => [
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processor for this financial transaction',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processor for this financial transaction'),
+ 'where' => 'civicrm_financial_trxn.payment_processor_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessor',
- ) ,
- 'financial_trxn_payment_instrument_id' => array(
+ ],
+ 'financial_trxn_payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'FK to payment_instrument option group values',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('FK to payment_instrument option group values'),
+ 'where' => 'civicrm_financial_trxn.payment_instrument_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- 'financial_trxn_card_type_id' => array(
+ ],
+ ],
+ 'financial_trxn_card_type_id' => [
'name' => 'card_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Card Type ID') ,
- 'description' => 'FK to accept_creditcard option group values',
+ 'title' => ts('Card Type ID'),
+ 'description' => ts('FK to accept_creditcard option group values'),
+ 'where' => 'civicrm_financial_trxn.card_type_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'accept_creditcard',
'optionEditPath' => 'civicrm/admin/options/accept_creditcard',
- )
- ) ,
- 'financial_trxn_check_number' => array(
+ ],
+ ],
+ 'financial_trxn_check_number' => [
'name' => 'check_number',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Check Number') ,
- 'description' => 'Check number',
+ 'title' => ts('Check Number'),
+ 'description' => ts('Check number'),
'maxlength' => 255,
'size' => 6,
+ 'where' => 'civicrm_financial_trxn.check_number',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'financial_trxn_pan_truncation' => array(
+ ],
+ ],
+ 'financial_trxn_pan_truncation' => [
'name' => 'pan_truncation',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pan Truncation') ,
- 'description' => 'Last 4 digits of credit card',
+ 'title' => ts('Pan Truncation'),
+ 'description' => ts('Last 4 digits of credit card'),
'maxlength' => 4,
'size' => 4,
+ 'where' => 'civicrm_financial_trxn.pan_truncation',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ 'financial_trxn_order_reference' => [
+ 'name' => 'order_reference',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Order Reference'),
+ 'description' => ts('Payment Processor external order reference'),
+ 'maxlength' => 255,
+ 'size' => 25,
+ 'where' => 'civicrm_financial_trxn.order_reference',
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -488,10 +527,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_trxn', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -499,40 +539,46 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_trxn', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_ftrxn_trxn_id' => array(
+ $indices = [
+ 'UI_ftrxn_trxn_id' => [
'name' => 'UI_ftrxn_trxn_id',
- 'field' => array(
+ 'field' => [
0 => 'trxn_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::trxn_id',
- ) ,
- 'UI_ftrxn_payment_instrument_id' => array(
+ ],
+ 'UI_ftrxn_payment_instrument_id' => [
'name' => 'UI_ftrxn_payment_instrument_id',
- 'field' => array(
+ 'field' => [
0 => 'payment_instrument_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::payment_instrument_id',
- ) ,
- 'UI_ftrxn_check_number' => array(
+ ],
+ 'UI_ftrxn_check_number' => [
'name' => 'UI_ftrxn_check_number',
- 'field' => array(
+ 'field' => [
0 => 'check_number',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::check_number',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialType.php b/CRM/Financial/DAO/FinancialType.php
index 3be6e3a6cfc9..28dfaff5e0e0 100644
--- a/CRM/Financial/DAO/FinancialType.php
+++ b/CRM/Financial/DAO/FinancialType.php
@@ -1,211 +1,225 @@
__table = 'civicrm_financial_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type ID') ,
- 'description' => 'ID of original financial_type so you can search this table by the financial_type.id and then select the relevant version based on the timestamp',
- 'required' => true,
+ 'title' => ts('Financial Type ID'),
+ 'description' => ts('ID of original financial_type so you can search this table by the financial_type.id and then select the relevant version based on the timestamp'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_type.id',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'financial_type' => array(
+ ],
+ 'financial_type' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Type') ,
- 'description' => 'Financial Type Name.',
- 'required' => true,
+ 'title' => ts('Financial Type'),
+ 'description' => ts('Financial Type Name.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_financial_type.name',
'headerPattern' => '/(finan(cial)?)?type/i',
'dataPattern' => '/donation|member|campaign/i',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Name"),
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Description') ,
- 'description' => 'Financial Type Description.',
+ 'title' => ts('Description'),
+ 'description' => ts('Financial Type Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_type.description',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_deductible' => array(
+ 'html' => [
+ 'type' => 'TextArea',
+ 'label' => ts("Description"),
+ ],
+ ],
+ 'is_deductible' => [
'name' => 'is_deductible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Tax Deductible?') ,
- 'description' => 'Is this financial type tax-deductible? If true, contributions of this type may be fully OR partially deductible - non-deductible amount is stored in the Contribution record.',
+ 'title' => ts('Is Tax Deductible?'),
+ 'description' => ts('Is this financial type tax-deductible? If true, contributions of this type may be fully OR partially deductible - non-deductible amount is stored in the Contribution record.'),
+ 'where' => 'civicrm_financial_type.is_deductible',
'default' => '1',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Tax-Deductible?"),
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Type is Reserved?') ,
- 'description' => 'Is this a predefined system object?',
+ 'title' => ts('Financial Type is Reserved?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'where' => 'civicrm_financial_type.is_reserved',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Reserved?"),
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Type Is Active?') ,
- 'description' => 'Is this property active?',
+ 'title' => ts('Financial Type Is Active?'),
+ 'description' => ts('Is this property active?'),
+ 'where' => 'civicrm_financial_type.is_active',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Enabled?"),
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -213,10 +227,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -224,25 +239,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_id' => array(
+ $indices = [
+ 'UI_id' => [
'name' => 'UI_id',
- 'field' => array(
+ 'field' => [
0 => 'id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_financial_type::1::id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentProcessor.php b/CRM/Financial/DAO/PaymentProcessor.php
index 7047ecfae31b..48676c59918f 100644
--- a/CRM/Financial/DAO/PaymentProcessor.php
+++ b/CRM/Financial/DAO/PaymentProcessor.php
@@ -1,521 +1,563 @@
__table = 'civicrm_payment_processor';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_type_id', 'civicrm_payment_processor_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_type_id', 'civicrm_payment_processor_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor ID') ,
- 'description' => 'Payment Processor ID',
- 'required' => true,
+ 'title' => ts('Payment Processor ID'),
+ 'description' => ts('Payment Processor ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Domain') ,
- 'description' => 'Which Domain is this match entry for',
- 'required' => true,
+ 'title' => ts('Payment Processor Domain'),
+ 'description' => ts('Which Domain is this match entry for'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.domain_id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'name' => array(
+ ],
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_payment_processor.name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'title' => [
+ 'name' => 'title',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Payment Processor Title'),
+ 'description' => ts('Payment Processor Descriptive Name.'),
+ 'maxlength' => 127,
+ 'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.title',
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Processor Description') ,
- 'description' => 'Payment Processor Description.',
+ 'title' => ts('Processor Description'),
+ 'description' => ts('Payment Processor Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.description',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_processor_type_id' => array(
+ ],
+ 'payment_processor_type_id' => [
'name' => 'payment_processor_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Type ID') ,
+ 'title' => ts('Payment Processor Type ID'),
+ 'where' => 'civicrm_payment_processor.payment_processor_type_id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessorType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_payment_processor_type',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor is Active?') ,
- 'description' => 'Is this processor active?',
+ 'title' => ts('Processor is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'where' => 'civicrm_payment_processor.is_active',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Is Default?') ,
- 'description' => 'Is this processor the default?',
+ 'title' => ts('Processor Is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'where' => 'civicrm_payment_processor.is_default',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_test' => array(
+ ],
+ 'is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Test Processor?') ,
- 'description' => 'Is this processor for a test site?',
+ 'title' => ts('Is Test Processor?'),
+ 'description' => ts('Is this processor for a test site?'),
+ 'where' => 'civicrm_payment_processor.is_test',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'user_name' => array(
+ ],
+ 'user_name' => [
'name' => 'user_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('User Name') ,
+ 'title' => ts('User Name'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.user_name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'password' => array(
+ ],
+ ],
+ 'password' => [
'name' => 'password',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Password') ,
+ 'title' => ts('Password'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.password',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
- 'type' => 'Text',
- ) ,
- ) ,
- 'signature' => array(
+ 'html' => [
+ 'type' => 'Password',
+ ],
+ ],
+ 'signature' => [
'name' => 'signature',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Signature') ,
+ 'title' => ts('Signature'),
'rows' => 4,
'cols' => 40,
+ 'where' => 'civicrm_payment_processor.signature',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'url_site' => array(
+ ],
+ ],
+ 'url_site' => [
'name' => 'url_site',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Site URL') ,
+ 'title' => ts('Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_site',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_api' => array(
+ ],
+ ],
+ 'url_api' => [
'name' => 'url_api',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('API URL') ,
+ 'title' => ts('API URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_api',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_recur' => array(
+ ],
+ ],
+ 'url_recur' => [
'name' => 'url_recur',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Recurring Payments URL') ,
+ 'title' => ts('Recurring Payments URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_recur',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_button' => array(
+ ],
+ ],
+ 'url_button' => [
'name' => 'url_button',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Button URL') ,
+ 'title' => ts('Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_button',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'subject' => array(
+ ],
+ ],
+ 'subject' => [
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
+ 'title' => ts('Subject'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.subject',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'class_name' => array(
+ ],
+ ],
+ 'class_name' => [
'name' => 'class_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Suffix for PHP class name implementation') ,
+ 'title' => ts('Suffix for PHP class name implementation'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.class_name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'billing_mode' => array(
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Processor Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
+ 'title' => ts('Processor Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.billing_mode',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_recur' => array(
+ ],
+ 'is_recur' => [
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Supports Recurring?') ,
- 'description' => 'Can process recurring contributions',
+ 'title' => ts('Processor Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'where' => 'civicrm_payment_processor.is_recur',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_type' => array(
+ ],
+ 'payment_type' => [
'name' => 'payment_type',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Type') ,
- 'description' => 'Payment Type: Credit or Debit (deprecated)',
+ 'title' => ts('Payment Type'),
+ 'description' => ts('Payment Type: Credit or Debit (deprecated)'),
+ 'where' => 'civicrm_payment_processor.payment_type',
'default' => '1',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_instrument_id' => array(
+ ],
+ 'payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'Payment Instrument ID',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('Payment Instrument ID'),
+ 'where' => 'civicrm_payment_processor.payment_instrument_id',
'default' => '1',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- 'accepted_credit_cards' => array(
+ ],
+ ],
+ 'accepted_credit_cards' => [
'name' => 'accepted_credit_cards',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Accepted Credit Cards') ,
- 'description' => 'array of accepted credit card types',
+ 'title' => ts('Accepted Credit Cards'),
+ 'description' => ts('array of accepted credit card types'),
+ 'where' => 'civicrm_payment_processor.accepted_credit_cards',
'default' => 'NULL',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- );
+ 'serialize' => self::SERIALIZE_JSON,
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
- return self::$_tableName;
+ public static function getTableName() {
+ return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -523,10 +565,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -534,27 +577,33 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name_test_domain_id' => array(
+ $indices = [
+ 'UI_name_test_domain_id' => [
'name' => 'UI_name_test_domain_id',
- 'field' => array(
+ 'field' => [
0 => 'name',
1 => 'is_test',
2 => 'domain_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_payment_processor::1::name::is_test::domain_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentProcessorType.php b/CRM/Financial/DAO/PaymentProcessorType.php
index f98f34e9d41d..7230d340df86 100644
--- a/CRM/Financial/DAO/PaymentProcessorType.php
+++ b/CRM/Financial/DAO/PaymentProcessorType.php
@@ -1,491 +1,507 @@
__table = 'civicrm_payment_processor_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Type ID') ,
- 'description' => 'Payment Processor Type ID',
- 'required' => true,
+ 'title' => ts('Payment Processor Type ID'),
+ 'description' => ts('Payment Processor Type ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor_type.id',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor variable name to be used in code') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor variable name to be used in code'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_payment_processor_type.name',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor Title') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor Title'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 127,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.title',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Processor Type Description') ,
- 'description' => 'Payment Processor Description.',
+ 'title' => ts('Processor Type Description'),
+ 'description' => ts('Payment Processor Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.description',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type Is Active?') ,
- 'description' => 'Is this processor active?',
+ 'title' => ts('Processor Type Is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'where' => 'civicrm_payment_processor_type.is_active',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type is Default?') ,
- 'description' => 'Is this processor the default?',
+ 'title' => ts('Processor Type is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'where' => 'civicrm_payment_processor_type.is_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'user_name_label' => array(
+ ],
+ 'user_name_label' => [
'name' => 'user_name_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for User Name if used') ,
+ 'title' => ts('Label for User Name if used'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.user_name_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'password_label' => array(
+ ],
+ 'password_label' => [
'name' => 'password_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for password') ,
+ 'title' => ts('Label for password'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.password_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'signature_label' => array(
+ ],
+ 'signature_label' => [
'name' => 'signature_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for Signature') ,
+ 'title' => ts('Label for Signature'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.signature_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'subject_label' => array(
+ ],
+ 'subject_label' => [
'name' => 'subject_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for Subject') ,
+ 'title' => ts('Label for Subject'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.subject_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'class_name' => array(
+ ],
+ 'class_name' => [
'name' => 'class_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Suffix for PHP class name implementation') ,
+ 'title' => ts('Suffix for PHP class name implementation'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.class_name',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_site_default' => array(
+ ],
+ 'url_site_default' => [
'name' => 'url_site_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Site URL') ,
+ 'title' => ts('Default Live Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_site_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_api_default' => array(
+ ],
+ 'url_api_default' => [
'name' => 'url_api_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default API Site URL') ,
+ 'title' => ts('Default API Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_api_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_recur_default' => array(
+ ],
+ 'url_recur_default' => [
'name' => 'url_recur_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Recurring Payments URL') ,
+ 'title' => ts('Default Live Recurring Payments URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_recur_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_button_default' => array(
+ ],
+ 'url_button_default' => [
'name' => 'url_button_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Button URL') ,
+ 'title' => ts('Default Live Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_button_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_site_test_default' => array(
+ ],
+ 'url_site_test_default' => [
'name' => 'url_site_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Site URL') ,
+ 'title' => ts('Default Test Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_site_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_api_test_default' => array(
+ ],
+ 'url_api_test_default' => [
'name' => 'url_api_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test API URL') ,
+ 'title' => ts('Default Test API URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_api_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_recur_test_default' => array(
+ ],
+ 'url_recur_test_default' => [
'name' => 'url_recur_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Recurring Payment URL') ,
+ 'title' => ts('Default Test Recurring Payment URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_recur_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_button_test_default' => array(
+ ],
+ 'url_button_test_default' => [
'name' => 'url_button_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Button URL') ,
+ 'title' => ts('Default Test Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_button_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'billing_mode' => array(
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
+ 'title' => ts('Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor_type.billing_mode',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::billingMode',
- )
- ) ,
- 'is_recur' => array(
+ ],
+ ],
+ 'is_recur' => [
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type Supports Recurring?') ,
- 'description' => 'Can process recurring contributions',
+ 'title' => ts('Processor Type Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'where' => 'civicrm_payment_processor_type.is_recur',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'payment_type' => array(
+ ],
+ 'payment_type' => [
'name' => 'payment_type',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Processor Type Payment Type') ,
- 'description' => 'Payment Type: Credit or Debit (deprecated)',
+ 'title' => ts('Processor Type Payment Type'),
+ 'description' => ts('Payment Type: Credit or Debit (deprecated)'),
+ 'where' => 'civicrm_payment_processor_type.payment_type',
'default' => '1',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'payment_instrument_id' => array(
+ ],
+ 'payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'Payment Instrument ID',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('Payment Instrument ID'),
+ 'where' => 'civicrm_payment_processor_type.payment_instrument_id',
'default' => '1',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -493,10 +509,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -504,25 +521,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_payment_processor_type::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentToken.php b/CRM/Financial/DAO/PaymentToken.php
index d5fe14b10fcd..981b34fa11d1 100644
--- a/CRM/Financial/DAO/PaymentToken.php
+++ b/CRM/Financial/DAO/PaymentToken.php
@@ -1,347 +1,356 @@
__table = 'civicrm_payment_token';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_id', 'civicrm_payment_processor', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_id', 'civicrm_payment_processor', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'payment_token_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'payment_token_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Token ID') ,
- 'description' => 'Payment Token ID',
- 'required' => true,
+ 'title' => ts('Payment Token ID'),
+ 'description' => ts('Payment Token ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID for the owner of the token',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID for the owner of the token'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.contact_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'payment_processor_id' => array(
+ ],
+ 'payment_processor_id' => [
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor ID') ,
- 'required' => true,
+ 'title' => ts('Payment Processor ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.payment_processor_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessor',
- ) ,
- 'token' => array(
+ ],
+ 'token' => [
'name' => 'token',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Token') ,
- 'description' => 'Externally provided token string',
- 'required' => true,
+ 'title' => ts('Token'),
+ 'description' => ts('Externally provided token string'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.token',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Created Date') ,
- 'description' => 'Date created',
+ 'title' => ts('Created Date'),
+ 'description' => ts('Date created'),
+ 'where' => 'civicrm_payment_token.created_date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'created_id' => array(
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created ID') ,
- 'description' => 'Contact ID of token creator',
+ 'title' => ts('Created ID'),
+ 'description' => ts('Contact ID of token creator'),
+ 'where' => 'civicrm_payment_token.created_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'expiry_date' => array(
+ ],
+ 'expiry_date' => [
'name' => 'expiry_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Expiry Date') ,
- 'description' => 'Date this token expires',
+ 'title' => ts('Expiry Date'),
+ 'description' => ts('Date this token expires'),
+ 'where' => 'civicrm_payment_token.expiry_date',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'email' => array(
+ ],
+ 'email' => [
'name' => 'email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Email') ,
- 'description' => 'Email at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Email'),
+ 'description' => ts('Email at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.email',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_first_name' => array(
+ ],
+ 'billing_first_name' => [
'name' => 'billing_first_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing First Name') ,
- 'description' => 'Billing first name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing First Name'),
+ 'description' => ts('Billing first name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_first_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_middle_name' => array(
+ ],
+ 'billing_middle_name' => [
'name' => 'billing_middle_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing Middle Name') ,
- 'description' => 'Billing middle name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing Middle Name'),
+ 'description' => ts('Billing middle name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_middle_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_last_name' => array(
+ ],
+ 'billing_last_name' => [
'name' => 'billing_last_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing Last Name') ,
- 'description' => 'Billing last name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing Last Name'),
+ 'description' => ts('Billing last name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_last_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'masked_account_number' => array(
+ ],
+ 'masked_account_number' => [
'name' => 'masked_account_number',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Masked Account Number') ,
- 'description' => 'Holds the part of the card number or account details that may be retained or displayed',
+ 'title' => ts('Masked Account Number'),
+ 'description' => ts('Holds the part of the card number or account details that may be retained or displayed'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.masked_account_number',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'ip_address' => array(
+ ],
+ 'ip_address' => [
'name' => 'ip_address',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('IP Address') ,
- 'description' => 'IP used when creating the token. Useful for fraud forensics',
+ 'title' => ts('IP Address'),
+ 'description' => ts('IP used when creating the token. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.ip_address',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -349,10 +358,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_token', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_token', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -360,15 +370,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_token', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_token', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/Form/BatchTransaction.php b/CRM/Financial/Form/BatchTransaction.php
index 457a739b527b..9071828c3257 100644
--- a/CRM/Financial/Form/BatchTransaction.php
+++ b/CRM/Financial/Form/BatchTransaction.php
@@ -1,9 +1,9 @@
addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
- self::$_entityID = CRM_Utils_Request::retrieve('bid', 'Positive') ? CRM_Utils_Request::retrieve('bid', 'Positive') : $_POST['batch_id'];
+ self::$_entityID = CRM_Utils_Request::retrieve('bid', 'Positive') ? CRM_Utils_Request::retrieve('bid', 'Positive') : CRM_Utils_Array::value('batch_id', $_POST);
$this->assign('entityID', self::$_entityID);
if (isset(self::$_entityID)) {
$this->_batchStatusId = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'status_id');
- $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name', 'condition' => " v.value={$this->_batchStatusId}"));
+ $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$this->_batchStatusId}"]);
$this->_batchStatus = $batchStatuses[$this->_batchStatusId];
$this->assign('statusID', $this->_batchStatusId);
$this->assign('batchStatus', $this->_batchStatus);
$validStatus = FALSE;
- if (in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (in_array($this->_batchStatus, ['Open', 'Reopened'])) {
$validStatus = TRUE;
}
$this->assign('validStatus', $validStatus);
-
+ $this->_values = civicrm_api3('Batch', 'getSingle', ['id' => self::$_entityID]);
$batchTitle = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'title');
- CRM_Utils_System::setTitle(ts('Accounting Batch - %1', array(1 => $batchTitle)));
+ CRM_Utils_System::setTitle(ts('Accounting Batch - %1', [1 => $batchTitle]));
- $columnHeaders = array(
+ $columnHeaders = [
'created_by' => ts('Created By'),
'status' => ts('Status'),
'description' => ts('Description'),
'payment_instrument' => ts('Payment Method'),
- 'item_count' => ts('Entered Transactions'),
- 'assigned_item_count' => ts('Assigned Transactions'),
- 'total' => ts('Entered Total'),
- 'assigned_total' => ts('Assigned Total'),
+ 'item_count' => ts('Expected Number of Items'),
+ 'assigned_item_count' => ts('Actual Number of Items'),
+ 'total' => ts('Expected Total Amount'),
+ 'assigned_total' => ts('Actual Total Amount'),
'opened_date' => ts('Opened'),
- );
+ ];
$this->assign('columnHeaders', $columnHeaders);
}
}
@@ -95,75 +95,55 @@ public function buildQuickForm() {
}
// do not build rest of form unless it is open/reopened batch
- if (!in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (!in_array($this->_batchStatus, ['Open', 'Reopened'])) {
return;
}
parent::buildQuickForm();
- $this->add('submit', 'close_batch', ts('Close Batch'));
- $this->add('submit', 'export_batch', ts('Close & Export Batch'));
-
- // text for sort_name
- $this->addElement('text',
- 'sort_name',
- ts('Contributor Name or Email'),
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact',
- 'sort_name'
- )
- );
-
- $this->_group = CRM_Core_PseudoConstant::nestedGroup();
-
- // multiselect for groups
- if ($this->_group) {
- $this->add('select', 'group', ts('Groups'), $this->_group, FALSE,
- array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
- );
+ if (CRM_Batch_BAO_Batch::checkBatchPermission('close', $this->_values['created_id'])) {
+ $this->add('submit', 'close_batch', ts('Close Batch'));
+ if (CRM_Batch_BAO_Batch::checkBatchPermission('export', $this->_values['created_id'])) {
+ $this->add('submit', 'export_batch', ts('Close & Export Batch'));
+ }
}
- $contactTags = CRM_Core_BAO_Tag::getTags();
- if ($contactTags) {
- $this->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE,
- array('id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2')
- );
- }
CRM_Contribute_BAO_Query::buildSearchForm($this);
$this->addElement('checkbox', 'toggleSelects', NULL, NULL);
$this->add('select',
'trans_remove',
ts('Task'),
- array('' => ts('- actions -')) + array('Remove' => ts('Remove from Batch')));
+ ['' => ts('- actions -')] + ['Remove' => ts('Remove from Batch')]);
$this->add('submit', 'rSubmit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'GoRemove',
- ));
+ ]);
self::$_entityID = CRM_Utils_Request::retrieve('bid', 'Positive');
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'submit',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
$this->addElement('checkbox', 'toggleSelect', NULL, NULL);
$this->add('select',
'trans_assign',
ts('Task'),
- array('' => ts('- actions -')) + array('Assign' => ts('Assign to Batch')));
+ ['' => ts('- actions -')] + ['Assign' => ts('Assign to Batch')]);
$this->add('submit', 'submit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'Go',
- ));
+ ]);
$this->applyFilter('__ALL__', 'trim');
$this->addElement('hidden', 'batch_id', self::$_entityID);
@@ -176,12 +156,12 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
// do not setdefault unless it is open/reopened batch
- if (!in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (!in_array($this->_batchStatus, ['Open', 'Reopened'])) {
return;
}
if (isset(self::$_entityID)) {
$paymentInstrumentID = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'payment_instrument_id');
- $defaults['payment_instrument_id'] = $paymentInstrumentID;
+ $defaults['contribution_payment_instrument_id'] = $paymentInstrumentID;
$this->assign('paymentInstrumentID', $paymentInstrumentID);
}
return $defaults;
@@ -194,20 +174,20 @@ public function setDefaultValues() {
*/
public function &links() {
if (!(self::$_links)) {
- self::$_links = array(
- 'view' => array(
+ self::$_links = [
+ 'view' => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&id=%%contid%%&cid=%%cid%%&action=view&context=contribution&selectedChild=contribute',
'title' => ts('View Contribution'),
- ),
- 'assign' => array(
+ ],
+ 'assign' => [
'name' => ts('Assign'),
'ref' => 'disable-action',
'title' => ts('Assign Transaction'),
'extra' => 'onclick = "assignRemove( %%id%%,\'' . 'assign' . '\' );"',
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
diff --git a/CRM/Financial/Form/Export.php b/CRM/Financial/Form/Export.php
index 7267d0469c16..966a179324d6 100644
--- a/CRM/Financial/Form/Export.php
+++ b/CRM/Financial/Form/Export.php
@@ -1,9 +1,9 @@
_batchIds = $this->get('batchIds');
}
- if (!empty($_GET['export_format']) && in_array($_GET['export_format'], array('IIF', 'CSV'))) {
+ if (!empty($_GET['export_format']) && in_array($_GET['export_format'], ['IIF', 'CSV'])) {
$this->_exportFormat = $_GET['export_format'];
}
}
@@ -89,15 +98,15 @@ public function preProcess() {
$this->_batchIds = $this->_id;
}
- $allBatchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
- $this->_exportStatusId = CRM_Utils_Array::key('Exported', $allBatchStatus);
+ $this->_exportStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_DAO_Batch', 'status_id', 'Exported');
// check if batch status is valid, do not allow exported batches to export again
$batchStatus = CRM_Batch_BAO_Batch::getBatchStatuses($this->_batchIds);
foreach ($batchStatus as $batchStatusId) {
if ($batchStatusId == $this->_exportStatusId) {
- CRM_Core_Error::fatal(ts('You cannot exported the batches which were exported earlier.'));
+ $url = CRM_Core_Session::singleton()->readUserContext();
+ CRM_Core_Error::statusBounce(ts('You cannot export batches which have already been exported.'), $url);
}
}
@@ -120,26 +129,26 @@ public function buildQuickForm() {
}
}
- $optionTypes = array(
+ $optionTypes = [
'IIF' => ts('Export to IIF'),
'CSV' => ts('Export to CSV'),
- );
+ ];
$this->addRadio('export_format', NULL, $optionTypes, NULL, '
', TRUE);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'next',
'name' => ts('Export Batch'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
}
@@ -153,7 +162,7 @@ public function postProcess() {
}
if ($this->_id) {
- $batchIds = array($this->_id);
+ $batchIds = [$this->_id];
}
elseif (!empty($this->_batchIds)) {
$batchIds = explode(',', $this->_batchIds);
@@ -167,15 +176,14 @@ public function postProcess() {
$batchParams['modified_id'] = $session->get('userID');
$batchParams['status_id'] = $this->_exportStatusId;
- $ids = array();
foreach ($batchIds as $batchId) {
- $batchParams['id'] = $ids['batchID'] = $batchId;
+ $batchParams['id'] = $batchId;
// Update totals
$batchParams = array_merge($batchParams, $totals[$batchId]);
- CRM_Batch_BAO_Batch::create($batchParams, $ids, 'financialBatch');
+ CRM_Batch_BAO_Batch::create($batchParams);
}
- CRM_Batch_BAO_Batch::exportFinancialBatch($batchIds, $this->_exportFormat);
+ CRM_Batch_BAO_Batch::exportFinancialBatch($batchIds, $this->_exportFormat, $this->_downloadFile);
}
}
diff --git a/CRM/Financial/Form/FinancialAccount.php b/CRM/Financial/Form/FinancialAccount.php
index eff3122f638d..098e9dcb4cc0 100644
--- a/CRM/Financial/Form/FinancialAccount.php
+++ b/CRM/Financial/Form/FinancialAccount.php
@@ -1,9 +1,9 @@
_id) {
- $params = array(
+ $params = [
'id' => $this->_id,
- );
- $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, CRM_Core_DAO::$_nullArray);
+ ];
+ $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params);
$financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
if ($financialAccount->financial_account_type_id == $financialAccountTypeId
&& strtolower($financialAccount->account_type_code) == 'ar'
@@ -84,15 +83,15 @@ public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialAccount');
$this->add('text', 'name', ts('Name'), $attributes['name'], TRUE);
$this->addRule('name', ts('A financial type with this name already exists. Please select another name.'),
- 'objectExists', array('CRM_Financial_DAO_FinancialAccount', $this->_id));
+ 'objectExists', ['CRM_Financial_DAO_FinancialAccount', $this->_id]);
$this->add('text', 'description', ts('Description'), $attributes['description']);
$this->add('text', 'accounting_code', ts('Accounting Code'), $attributes['accounting_code']);
$elementAccounting = $this->add('text', 'account_type_code', ts('Account Type Code'), $attributes['account_type_code']);
- $this->addEntityRef('contact_id', ts('Owner'), array(
- 'api' => array('params' => array('contact_type' => 'Organization')),
+ $this->addEntityRef('contact_id', ts('Owner'), [
+ 'api' => ['params' => ['contact_type' => 'Organization']],
'create' => TRUE,
- ));
+ ]);
$this->add('text', 'tax_rate', ts('Tax Rate'), $attributes['tax_rate']);
$this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'));
$elementActive = $this->add('checkbox', 'is_active', ts('Enabled?'));
@@ -107,7 +106,7 @@ public function buildQuickForm() {
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
if (!empty($financialAccountType)) {
$element = $this->add('select', 'financial_account_type_id', ts('Financial Account Type'),
- array('' => '- select -') + $financialAccountType, TRUE, array('class' => 'crm-select2 huge'));
+ ['' => '- select -'] + $financialAccountType, TRUE, ['class' => 'crm-select2 huge']);
if ($this->_isARFlag) {
$element->freeze();
$elementAccounting->freeze();
@@ -121,9 +120,9 @@ public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::UPDATE &&
CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_reserved')
) {
- $this->freeze(array('name', 'description', 'is_active'));
+ $this->freeze(['name', 'description', 'is_active']);
}
- $this->addFormRule(array('CRM_Financial_Form_FinancialAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_Financial_Form_FinancialAccount', 'formRule'], $this);
}
/**
@@ -138,13 +137,13 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errorMsg = array();
+ $errorMsg = [];
$financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' "));
if (isset($values['is_tax'])) {
if ($values['financial_account_type_id'] != $financialAccountTypeId) {
$errorMsg['financial_account_type_id'] = ts('Taxable accounts should have Financial Account Type set to Liability.');
}
- if (CRM_Utils_Array::value('tax_rate', $values) == NULL) {
+ if (!isset($values['tax_rate'])) {
$errorMsg['tax_rate'] = ts('Please enter value for tax rate');
}
}
@@ -155,11 +154,12 @@ public static function formRule($values, $files, $self) {
}
if ($self->_action & CRM_Core_Action::UPDATE) {
if (!(isset($values['is_tax']))) {
+ // @todo replace with call to CRM_Financial_BAO_FinancialAccount getSalesTaxFinancialAccount
$relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
- $params = array(
+ $params = [
'financial_account_id' => $self->_id,
'account_relationship' => $relationshipId,
- );
+ ];
$result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
if ($result) {
$errorMsg['is_tax'] = ts('Is Tax? must be set for this financial account');
@@ -200,9 +200,16 @@ public function postProcess() {
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
}
-
+ foreach ([
+ 'is_active',
+ 'is_deductible',
+ 'is_tax',
+ 'is_default',
+ ] as $field) {
+ $params[$field] = CRM_Utils_Array::value($field, $params, FALSE);
+ }
$financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
- CRM_Core_Session::setStatus(ts('The Financial Account \'%1\' has been saved.', array(1 => $financialAccount->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The Financial Account \'%1\' has been saved.', [1 => $financialAccount->name]), ts('Saved'), 'success');
}
}
diff --git a/CRM/Financial/Form/FinancialBatch.php b/CRM/Financial/Form/FinancialBatch.php
index c64287de4d13..94574348b2bc 100644
--- a/CRM/Financial/Form/FinancialBatch.php
+++ b/CRM/Financial/Form/FinancialBatch.php
@@ -1,9 +1,9 @@
set("context", $context);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
parent::preProcess();
$session = CRM_Core_Session::singleton();
if ($this->_id) {
- $permissions = array(
- CRM_Core_Action::UPDATE => array(
- 'permission' => array(
+ $permissions = [
+ CRM_Core_Action::UPDATE => [
+ 'permission' => [
'edit own manual batches',
'edit all manual batches',
- ),
+ ],
'actionName' => 'edit',
- ),
- CRM_Core_Action::DELETE => array(
- 'permission' => array(
+ ],
+ CRM_Core_Action::DELETE => [
+ 'permission' => [
'delete own manual batches',
'delete all manual batches',
- ),
+ ],
'actionName' => 'delete',
- ),
- );
+ ],
+ ];
$createdID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
if (!empty($permissions[$this->_action])) {
@@ -83,8 +83,7 @@ public function preProcess() {
public function buildQuickForm() {
parent::buildQuickForm();
$this->setPageTitle(ts('Financial Batch'));
-
- if (isset($this->_id)) {
+ if (!empty($this->_id)) {
$this->_title = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'title');
CRM_Utils_System::setTitle($this->_title . ' - ' . ts('Accounting Batch'));
$this->assign('batchTitle', $this->_title);
@@ -96,32 +95,32 @@ public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_BAO_Batch', 'status_id');
// unset exported status
- $exportedStatusId = CRM_Utils_Array::key('Exported', $batchStatus);
+ $exportedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Exported');
unset($batchStatus[$exportedStatusId]);
- $this->add('select', 'status_id', ts('Batch Status'), array('' => ts('- select -')) + $batchStatus, TRUE);
- $this->freeze(array('status_id'));
+ $this->add('select', 'status_id', ts('Batch Status'), ['' => ts('- select -')] + $batchStatus, TRUE);
+ $this->freeze(['status_id']);
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
@@ -131,14 +130,14 @@ public function buildQuickForm() {
$this->add('textarea', 'description', ts('Description'), $attributes['description']);
$this->add('select', 'payment_instrument_id', ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE
);
$this->add('text', 'total', ts('Total Amount'), $attributes['total']);
$this->add('text', 'item_count', ts('Number of Transactions'), $attributes['item_count']);
- $this->addFormRule(array('CRM_Financial_Form_FinancialBatch', 'formRule'), $this);
+ $this->addFormRule(['CRM_Financial_Form_FinancialBatch', 'formRule'], $this);
}
/**
@@ -171,7 +170,7 @@ public function setDefaultValues() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($values['contact_name']) && !is_numeric($values['created_id'])) {
$errors['contact_name'] = ts('Please select a valid contact.');
}
@@ -196,11 +195,9 @@ public static function formRule($values, $files, $self) {
*/
public function postProcess() {
$session = CRM_Core_Session::singleton();
- $ids = array();
$params = $this->exportValues();
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+ $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
if ($this->_id) {
- $ids['batchID'] = $this->_id;
$params['id'] = $this->_id;
}
@@ -212,37 +209,42 @@ public function postProcess() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- $batchMode = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'mode_id', array('labelColumn' => 'name'));
- $params['mode_id'] = CRM_Utils_Array::key('Manual Batch', $batchMode);
- $params['status_id'] = CRM_Utils_Array::key('Open', $batchStatus);
+ $params['mode_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'mode_id', 'Manual Batch');
+ $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Open');
$params['created_date'] = date('YmdHis');
- $params['created_id'] = $session->get('userID');
+ if (empty($params['created_id'])) {
+ $params['created_id'] = $session->get('userID');
+ }
$details = "{$params['title']} batch has been created by this contact.";
$activityTypeName = 'Create Batch';
}
elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
$details = "{$params['title']} batch has been edited by this contact.";
- if (CRM_Utils_Array::value($params['status_id'], $batchStatus) == 'Closed') {
+ if ($params['status_id'] === $closedStatusId) {
$details = "{$params['title']} batch has been closed by this contact.";
}
$activityTypeName = 'Edit Batch';
}
- $batch = CRM_Batch_BAO_Batch::create($params, $ids, 'financialBatch');
+ // FIXME: What happens if we get to here and no activityType is defined?
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
+ $batch = CRM_Batch_BAO_Batch::create($params);
+
+ //set batch id
+ $this->_id = $batch->id;
// create activity.
- $activityParams = array(
- 'activity_type_id' => array_search($activityTypeName, $activityTypes),
+ $activityParams = [
+ // activityTypeName - dev/core#1116-unknown-if-ok
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
'subject' => $batch->title . "- Batch",
- 'status_id' => 2,
- 'priority_id' => 2,
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed'),
+ 'priority_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'priority_id', 'Normal'),
'activity_date_time' => date('YmdHis'),
'source_contact_id' => $session->get('userID'),
'source_contact_qid' => $session->get('userID'),
'details' => $details,
- );
+ ];
CRM_Activity_BAO_Activity::create($activityParams);
@@ -250,7 +252,7 @@ public function postProcess() {
$context = $this->get("context");
if ($batch->title) {
- CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", array(1 => $batch->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", [1 => $batch->title]), ts('Saved'), 'success');
}
if ($buttonName == $this->getButtonName('next', 'new') & $this->_action == CRM_Core_Action::UPDATE) {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
@@ -260,7 +262,7 @@ public function postProcess() {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
"reset=1&action=add"));
}
- elseif (CRM_Utils_Array::value($batch->status_id, $batchStatus) == 'Closed') {
+ elseif ($batch->status_id === $closedStatusId) {
$session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
}
elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
@@ -289,11 +291,11 @@ public function postProcess() {
public function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
if ((CRM_Core_Permission::check($permissions[0]) || CRM_Core_Permission::check($permissions[1]))) {
if (CRM_Core_Permission::check($permissions[0]) && $userContactID != $createdID && !CRM_Core_Permission::check($permissions[1])) {
- CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
+ CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
}
}
else {
- CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
+ CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
}
}
diff --git a/CRM/Financial/Form/FinancialType.php b/CRM/Financial/Form/FinancialType.php
index caa7f7eaae32..f64304a648dd 100644
--- a/CRM/Financial/Form/FinancialType.php
+++ b/CRM/Financial/Form/FinancialType.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
parent::preProcess();
+ $this->setPageTitle(ts('Financial Type'));
+ if ($this->_id) {
+ $this->_title = CRM_Core_PseudoConstant::getLabel(
+ 'CRM_Financial_BAO_FinancialType',
+ 'financial_type',
+ $this->_id
+ );
+ $this->assign('aid', $this->_id);
+ }
+ }
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'name' => [
+ 'name' => 'name',
+ 'required' => TRUE,
+ ],
+ 'description' => ['name' => 'description'],
+ 'is_deductible' => [
+ 'name' => 'is_deductible',
+ 'description' => ts('Are contributions of this type tax-deductible?'),
+ ],
+ 'is_reserved' => ['name' => 'is_reserved'],
+ 'is_active' => ['name' => 'is_active'],
+ ];
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'FinancialType';
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('WARNING: You cannot delete a financial type if it is currently used by any Contributions, Contribution Pages or Membership Types. Consider disabling this option instead.') . ts('Deleting a financial type cannot be undone.') . ts('Do you want to continue?');
}
/**
* Build the form object.
*/
public function buildQuickForm() {
- parent::buildQuickForm();
- $this->setPageTitle(ts('Financial Type'));
-
- $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- if ($this->_id) {
- $this->_title = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'name');
- }
+ self::buildQuickEntityForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'name'), TRUE);
-
- $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'description'));
-
- $this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_deductible'));
- $this->add('checkbox', 'is_active', ts('Enabled?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_active'));
- $this->add('checkbox', 'is_reserved', ts('Reserved?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_reserved'));
- if ($this->_action == CRM_Core_Action::UPDATE) {
- $this->assign('aid', $this->_id);
- }
- if ($this->_action == CRM_Core_Action::UPDATE && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'is_reserved', 'vid')) {
- $this->freeze(array('is_active'));
+ if ($this->_action == CRM_Core_Action::UPDATE && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'is_reserved')) {
+ $this->freeze(['is_active']);
}
-
$this->addRule('name', ts('A financial type with this name already exists. Please select another name.'), 'objectExists',
- array('CRM_Financial_DAO_FinancialType', $this->_id)
+ ['CRM_Financial_DAO_FinancialType', $this->_id]
);
}
@@ -95,35 +138,46 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected financial type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $params = $ids = array();
// store the submitted values in an array
$params = $this->exportValues();
-
- if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['financialType'] = $this->_id;
+ if ($this->_id) {
+ $params['id'] = $this->_id;
}
-
- $financialType = CRM_Financial_BAO_FinancialType::add($params, $ids);
+ foreach ([
+ 'is_active',
+ 'is_reserved',
+ 'is_deductible',
+ ] as $field) {
+ $params[$field] = CRM_Utils_Array::value($field, $params, FALSE);
+ }
+ $financialType = civicrm_api3('FinancialType', 'create', $params);
if ($this->_action & CRM_Core_Action::UPDATE) {
$url = CRM_Utils_System::url('civicrm/admin/financial/financialType', 'reset=1&action=browse');
- CRM_Core_Session::setStatus(ts('The financial type "%1" has been updated.', array(1 => $financialType->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The financial type "%1" has been updated.', [1 => $params['name']]), ts('Saved'), 'success');
}
else {
- $url = CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', 'reset=1&action=browse&aid=' . $financialType->id);
- $statusArray = array(
- 1 => $financialType->name,
- 2 => $financialType->name,
- 3 => CRM_Utils_Array::value(0, $financialType->titles),
- 4 => CRM_Utils_Array::value(1, $financialType->titles),
- 5 => CRM_Utils_Array::value(2, $financialType->titles),
- );
- if (empty($financialType->titles)) {
- $text = ts('Your Financial "%1" Type has been created and assigned to an existing financial account with the same title. You should review the assigned account and determine whether additional account relationships are needed.', $statusArray);
+ $url = CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', 'reset=1&action=browse&aid=' . $financialType['id']);
+
+ $statusArray = [
+ 1 => $params['name'],
+ ];
+ $financialAccounts = civicrm_api3('EntityFinancialAccount', 'get', [
+ 'return' => ["financial_account_id.name"],
+ 'entity_table' => "civicrm_financial_type",
+ 'entity_id' => $financialType['id'],
+ 'options' => ['sort' => "id"],
+ 'account_relationship' => ['!=' => "Income Account is"],
+ ]);
+ if (!empty($financialAccounts['values'])) {
+ foreach ($financialAccounts['values'] as $financialAccount) {
+ $statusArray[] = $financialAccount['financial_account_id.name'];
+ }
+ $text = ts('Your Financial "%1" Type has been created, along with a corresponding income account "%1". That income account, along with standard financial accounts "%2", "%3" and "%4" have been linked to the financial type. You may edit or replace those relationships here.', $statusArray);
}
else {
- $text = ts('Your Financial "%1" Type has been created, along with a corresponding income account "%2". That income account, along with standard financial accounts "%3", "%4" and "%5" have been linked to the financial type. You may edit or replace those relationships here.', $statusArray);
+ $text = ts('Your Financial "%1" Type has been created and assigned to an existing financial account with the same title. You should review the assigned account and determine whether additional account relationships are needed.', $statusArray);
}
- CRM_Core_Session::setStatus($text, ts('Saved'), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($text, ts('Saved'), 'success', ['expires' => 0]);
}
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Financial/Form/FinancialTypeAccount.php b/CRM/Financial/Form/FinancialTypeAccount.php
index e686724d3701..b6834aac46e9 100644
--- a/CRM/Financial/Form/FinancialTypeAccount.php
+++ b/CRM/Financial/Form/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
ts('Financial Type Accounts'),
'url' => $url,
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -125,7 +125,7 @@ public function buildQuickForm() {
}
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
$this->setDefaults($defaults);
$financialAccountTitle = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $defaults['financial_account_id'], 'name');
@@ -147,7 +147,7 @@ public function buildQuickForm() {
$element = $this->add('select',
'account_relationship',
ts('Financial Account Relationship'),
- array('select' => ts('- Select Financial Account Relationship -')) + $AccountTypeRelationship,
+ ['select' => ts('- Select Financial Account Relationship -')] + $AccountTypeRelationship,
TRUE
);
}
@@ -162,12 +162,12 @@ public function buildQuickForm() {
$financialAccountType = CRM_Utils_Array::value($this->_submitValues['account_relationship'], $financialAccountType);
$result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
- $financialAccountSelect = array('' => ts('- select -')) + $result;
+ $financialAccountSelect = ['' => ts('- select -')] + $result;
}
else {
- $financialAccountSelect = array(
+ $financialAccountSelect = [
'select' => ts('- select -'),
- ) + CRM_Contribute_PseudoConstant::financialAccount();
+ ] + CRM_Contribute_PseudoConstant::financialAccount();
}
}
if ($this->_action == CRM_Core_Action::UPDATE) {
@@ -175,7 +175,7 @@ public function buildQuickForm() {
$financialAccountType = $financialAccountType[$this->_defaultValues['account_relationship']];
$result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
- $financialAccountSelect = array('' => ts('- select -')) + $result;
+ $financialAccountSelect = ['' => ts('- select -')] + $result;
}
$this->add('select',
@@ -185,24 +185,23 @@ public function buildQuickForm() {
TRUE
);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
- $this->addFormRule(array('CRM_Financial_Form_FinancialTypeAccount', 'formRule'), $this);
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+ $this->addFormRule(['CRM_Financial_Form_FinancialTypeAccount', 'formRule'], $this);
}
/**
@@ -217,7 +216,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errorMsg = array();
+ $errorMsg = [];
$errorFlag = FALSE;
if ($self->_action == CRM_Core_Action::DELETE) {
$relationValues = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
@@ -238,12 +237,14 @@ public static function formRule($values, $files, $self) {
$errorMsg['financial_account_id'] = 'Financial Account is a required field.';
}
if (!empty($values['account_relationship']) && !empty($values['financial_account_id'])) {
- $params = array(
+ $params = [
'account_relationship' => $values['account_relationship'],
'entity_id' => $self->_aid,
- );
- $defaults = array();
+ 'entity_table' => 'civicrm_financial_type',
+ ];
+ $defaults = [];
if ($self->_action == CRM_Core_Action::ADD) {
+ // @todo replace with call to CRM_Financial_BAO_FinancialAccount getSalesTaxFinancialAccount
$relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
$isTax = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $values['financial_account_id'], 'is_tax');
if ($values['account_relationship'] == $relationshipId) {
@@ -285,7 +286,7 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected financial type account has been deleted.'));
}
else {
- $params = $ids = array();
+ $params = $ids = [];
// store the submitted values in an array
$params = $this->exportValues();
@@ -299,8 +300,13 @@ public function postProcess() {
if ($this->_action & CRM_Core_Action::ADD) {
$params['entity_id'] = $this->_aid;
}
- $financialTypeAccount = CRM_Financial_BAO_FinancialTypeAccount::add($params, $ids);
- CRM_Core_Session::setStatus(ts('The financial type Account has been saved.'));
+ try {
+ $financialTypeAccount = CRM_Financial_BAO_FinancialTypeAccount::add($params, $ids);
+ CRM_Core_Session::setStatus(ts('The financial type Account has been saved.'), ts('Saved'), 'success');
+ }
+ catch (CRM_Core_Exception $e) {
+ CRM_Core_Error::statusBounce($e->getMessage());
+ }
}
$buttonName = $this->controller->getButtonName();
diff --git a/CRM/Financial/Form/FrontEndPaymentFormTrait.php b/CRM/Financial/Form/FrontEndPaymentFormTrait.php
new file mode 100644
index 000000000000..7380cdd857be
--- /dev/null
+++ b/CRM/Financial/Form/FrontEndPaymentFormTrait.php
@@ -0,0 +1,82 @@
+ $value) {
+ foreach ($value as $k => $v) {
+ if (isset($v['tax_rate']) && $v['tax_rate'] != '') {
+ // These only need assigning once, but code is more readable with them here
+ $this->assign('getTaxDetails', TRUE);
+ $this->assign('taxTerm', CRM_Invoicing_Utils::getTaxTerm());
+ // Cast to float to display without trailing zero decimals
+ $tplLineItems[$key][$k]['tax_rate'] = (float) $v['tax_rate'];
+ }
+ }
+ }
+ }
+
+ /**
+ * Assign line items to the template.
+ *
+ * @param $tplLineItems
+ */
+ protected function assignLineItemsToTemplate($tplLineItems) {
+ // @todo this should be a hook that invoicing code hooks into rather than a call to it.
+ $this->alterLineItemsForTemplate($tplLineItems);
+ $this->assign('lineItem', $tplLineItems);
+ }
+
+}
diff --git a/CRM/Financial/Form/Payment.php b/CRM/Financial/Form/Payment.php
index 996e45abc040..f51cc0f2e25f 100644
--- a/CRM/Financial/Form/Payment.php
+++ b/CRM/Financial/Form/Payment.php
@@ -1,9 +1,9 @@
_formName = CRM_Utils_Request::retrieve('formName', 'String', $this);
+
$this->_values['custom_pre_id'] = CRM_Utils_Request::retrieve('pre_profile_id', 'Integer', $this);
$this->_paymentProcessorID = CRM_Utils_Request::retrieve('processor_id', 'Integer', CRM_Core_DAO::$_nullObject,
@@ -72,19 +79,19 @@ public function preProcess() {
CRM_Core_Payment_ProcessorForm::preProcess($this);
- self::addCreditCardJs($this->_paymentProcessorID);
-
- $this->assign('paymentProcessorID', $this->_paymentProcessorID);
- $this->assign('currency', $this->currency);
-
$this->assign('suppressForm', TRUE);
$this->controller->_generateQFKey = FALSE;
}
/**
+ * Get currency
+ *
+ * @param array $submittedValues
+ * Required for consistency with other form methods.
+ *
* @return string
*/
- public function getCurrency() {
+ public function getCurrency($submittedValues = []) {
return $this->currency;
}
@@ -108,15 +115,75 @@ public function setDefaultValues() {
* Add JS to show icons for the accepted credit cards.
*
* @param int $paymentProcessorID
+ * @param string $region
*/
- public static function addCreditCardJs($paymentProcessorID = NULL) {
+ public static function addCreditCardJs($paymentProcessorID = NULL, $region = 'billing-block') {
$creditCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($paymentProcessorID);
- $creditCardTypes = CRM_Core_Payment_Form::getCreditCardCSSNames($creditCards);
+ if (empty($creditCards)) {
+ $creditCards = CRM_Contribute_PseudoConstant::creditCard();
+ }
+ $creditCardTypes = [];
+ foreach ($creditCards as $name => $label) {
+ $creditCardTypes[$name] = [
+ 'label' => $label,
+ 'name' => $name,
+ 'css_key' => self::getCssLabelFriendlyName($name),
+ 'pattern' => self::getCardPattern($name),
+ ];
+ }
+
CRM_Core_Resources::singleton()
- ->addScriptFile('civicrm', 'templates/CRM/Core/BillingBlock.js', 10, 'html-header', FALSE)
+ // CRM-20516: add BillingBlock script on billing-block region
+ // to support this feature in payment form snippet too.
+ ->addScriptFile('civicrm', 'templates/CRM/Core/BillingBlock.js', 10, $region, FALSE)
// workaround for CRM-13634
// ->addSetting(array('config' => array('creditCardTypes' => $creditCardTypes)));
- ->addScript('CRM.config.creditCardTypes = ' . json_encode($creditCardTypes) . ';', '-9999', 'html-header');
+ ->addScript('CRM.config.creditCardTypes = ' . json_encode($creditCardTypes) . ';', '-9999', $region);
+ }
+
+ /**
+ * Get css friendly labels for credit cards.
+ *
+ * We add the icons based on these css names which are lower cased
+ * and only AlphaNumeric (+ _).
+ *
+ * @param $key
+ *
+ * @return string
+ */
+ protected static function getCssLabelFriendlyName($key) {
+ $key = str_replace(' ', '', $key);
+ $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
+ $key = strtolower($key);
+
+ return $key;
+ }
+
+ /**
+ * Get the pattern that can be used to determine the card type.
+ *
+ * We do a strotolower comparison as we don't know what case people might have if they
+ * are using a non-std one like dinersclub.
+ *
+ * @param $key
+ *
+ * Based on http://davidwalsh.name/validate-credit-cards
+ * See also https://en.wikipedia.org/wiki/Credit_card_numbers
+ *
+ * @return string
+ */
+ protected static function getCardPattern($key) {
+ $cardMappings = [
+ 'mastercard' => '(5[1-5][0-9]{2}|2[3-6][0-9]{2}|22[3-9][0-9]|222[1-9]|27[0-1][0-9]|2720)[0-9]{12}',
+ 'visa' => '4(?:[0-9]{12}|[0-9]{15})',
+ 'amex' => '3[47][0-9]{13}',
+ 'dinersclub' => '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
+ 'carteblanche' => '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
+ 'discover' => '6011[0-9]{12}',
+ 'jcb' => '(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
+ 'unionpay' => '62(?:[0-9]{14}|[0-9]{17})',
+ ];
+ return isset($cardMappings[strtolower($key)]) ? $cardMappings[strtolower($key)] : '';
}
}
diff --git a/CRM/Financial/Form/PaymentEdit.php b/CRM/Financial/Form/PaymentEdit.php
new file mode 100644
index 000000000000..22a38b9be59c
--- /dev/null
+++ b/CRM/Financial/Form/PaymentEdit.php
@@ -0,0 +1,329 @@
+_action = CRM_Core_Action::UPDATE;
+ parent::preProcess();
+ $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
+ $this->assign('id', $this->_id);
+ $this->_contributionID = CRM_Utils_Request::retrieve('contribution_id', 'Positive', $this);
+
+ $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $this->_id]);
+ if (!empty($this->_values['payment_processor_id'])) {
+ CRM_Core_Error::statusBounce(ts('You cannot update this payment as it is tied to a payment processor'));
+ }
+ }
+
+ /**
+ * Set default values.
+ *
+ * @return array
+ */
+ public function setDefaultValues() {
+ $defaults = $this->_values;
+ // Format money fields - localize for display
+ $moneyFields = ['total_amount', 'fee_amount', 'net_amount'];
+ foreach ($moneyFields as $field) {
+ $defaults[$field] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($this->_values[$field]);
+ }
+ return $defaults;
+ }
+
+ /**
+ * Build quickForm.
+ */
+ public function buildQuickForm() {
+ CRM_Utils_System::setTitle(ts('Update Payment details'));
+
+ $paymentFields = $this->getPaymentFields();
+ $this->assign('paymentFields', $paymentFields);
+ foreach ($paymentFields as $name => $paymentField) {
+ if (!empty($paymentField['add_field'])) {
+ $attributes = [
+ 'entity' => 'FinancialTrxn',
+ 'name' => $name,
+ ];
+ $this->addField($name, $attributes, $paymentField['is_required']);
+ }
+ else {
+ $this->add($paymentField['htmlType'],
+ $name,
+ $paymentField['title'],
+ $paymentField['attributes'],
+ $paymentField['is_required']
+ );
+ }
+ }
+
+ $this->assign('currency', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $this->_values['currency'], 'symbol', 'name'));
+ $this->addFormRule([__CLASS__, 'formRule'], $this);
+
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Update'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+ }
+
+ /**
+ * Global form rule.
+ *
+ * @param array $fields
+ * The input form values.
+ * @param array $files
+ * The uploaded files if any.
+ * @param $self
+ *
+ * @return bool|array
+ * true if no errors, else array of errors
+ */
+ public static function formRule($fields, $files, $self) {
+ $errors = [];
+
+ // if Credit Card is chosen and pan_truncation is not NULL ensure that it's value is numeric else throw validation error
+ if (CRM_Core_PseudoConstant::getName('CRM_Financial_DAO_FinancialTrxn', 'payment_instrument_id', $fields['payment_instrument_id']) == 'Credit Card' &&
+ !empty($fields['pan_truncation']) &&
+ !CRM_Utils_Rule::numeric($fields['pan_truncation'])
+ ) {
+ $errors['pan_truncation'] = ts('Please enter a valid Card Number');
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Process the form submission.
+ */
+ public function postProcess() {
+ $params = [
+ 'id' => $this->_id,
+ 'payment_instrument_id' => $this->_submitValues['payment_instrument_id'],
+ 'trxn_id' => CRM_Utils_Array::value('trxn_id', $this->_submitValues),
+ 'trxn_date' => CRM_Utils_Array::value('trxn_date', $this->_submitValues, date('YmdHis')),
+ ];
+
+ $paymentInstrumentName = CRM_Core_PseudoConstant::getName('CRM_Financial_DAO_FinancialTrxn', 'payment_instrument_id', $params['payment_instrument_id']);
+ if ($paymentInstrumentName == 'Credit Card') {
+ $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $this->_submitValues);
+ $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $this->_submitValues);
+ }
+ elseif ($paymentInstrumentName == 'Check') {
+ $params['check_number'] = CRM_Utils_Array::value('check_number', $this->_submitValues);
+ }
+
+ $this->submit($params);
+
+ $contactId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_contributionID, 'contact_id');
+ $url = CRM_Utils_System::url(
+ "civicrm/contact/view/contribution",
+ "reset=1&action=update&id={$this->_contributionID}&cid={$contactId}&context=contribution"
+ );
+ CRM_Core_Session::singleton()->pushUserContext($url);
+ }
+
+ /**
+ * Wrapper function to process form submission
+ *
+ * @param array $submittedValues
+ *
+ */
+ protected function submit($submittedValues) {
+ // if payment instrument is changed then
+ // 1. Record a new reverse financial transaction with old payment instrument
+ // 2. Record a new financial transaction with new payment instrument
+ // 3. Add EntityFinancialTrxn records to relate with corresponding financial item and contribution
+ if ($submittedValues['payment_instrument_id'] != $this->_values['payment_instrument_id']) {
+ $previousFinanciaTrxn = $this->_values;
+ $newFinancialTrxn = $submittedValues;
+ unset($previousFinanciaTrxn['id'], $newFinancialTrxn['id']);
+ $previousFinanciaTrxn['trxn_date'] = CRM_Utils_Array::value('trxn_date', $submittedValues, date('YmdHis'));
+ $previousFinanciaTrxn['total_amount'] = -$previousFinanciaTrxn['total_amount'];
+ $previousFinanciaTrxn['net_amount'] = -$previousFinanciaTrxn['net_amount'];
+ $previousFinanciaTrxn['fee_amount'] = -$previousFinanciaTrxn['fee_amount'];
+ $previousFinanciaTrxn['contribution_id'] = $newFinancialTrxn['contribution_id'] = $this->_contributionID;
+
+ $newFinancialTrxn['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($submittedValues['payment_instrument_id']);
+ foreach (['total_amount', 'fee_amount', 'net_amount', 'currency', 'is_payment', 'status_id'] as $fieldName) {
+ $newFinancialTrxn[$fieldName] = $this->_values[$fieldName];
+ }
+
+ foreach ([$previousFinanciaTrxn, $newFinancialTrxn] as $financialTrxnParams) {
+ $financialTrxn = civicrm_api3('FinancialTrxn', 'create', $financialTrxnParams);
+ $trxnParams = [
+ 'total_amount' => $financialTrxnParams['total_amount'],
+ 'contribution_id' => $this->_contributionID,
+ ];
+ $contributionTotalAmount = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionID, 'total_amount');
+ CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $financialTrxn['id'], $contributionTotalAmount);
+ }
+ }
+ else {
+ // simply update the financial trxn
+ civicrm_api3('FinancialTrxn', 'create', $submittedValues);
+ }
+
+ self::updateRelatedContribution($submittedValues, $this->_contributionID);
+ }
+
+ /**
+ * Wrapper for unit testing the post process submit function.
+ *
+ * @param array $params
+ */
+ public function testSubmit($params) {
+ $this->_id = $params['id'];
+ $this->_contributionID = $params['contribution_id'];
+ $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $params['id']]);
+
+ $this->submit($params);
+ }
+
+ /**
+ * Function to update contribution's check_number and trxn_id by
+ * concatenating values from financial trxn's check_number and trxn_id respectively
+ *
+ * @param array $params
+ * @param int $contributionID
+ */
+ public static function updateRelatedContribution($params, $contributionID) {
+ $contributionDAO = new CRM_Contribute_DAO_Contribution();
+ $contributionDAO->id = $contributionID;
+ $contributionDAO->find(TRUE);
+
+ foreach (['trxn_id', 'check_number'] as $fieldName) {
+ if (!empty($params[$fieldName])) {
+ if (!empty($contributionDAO->$fieldName)) {
+ $values = explode(',', $contributionDAO->$fieldName);
+ // if submitted check_number or trxn_id value is
+ // already present then ignore else add to $values array
+ if (!in_array($params[$fieldName], $values)) {
+ $values[] = $params[$fieldName];
+ }
+ $contributionDAO->$fieldName = implode(',', $values);
+ }
+ }
+ }
+
+ $contributionDAO->save();
+ }
+
+ /**
+ * Get payment fields
+ */
+ public function getPaymentFields() {
+ $paymentFields = [
+ 'payment_instrument_id' => [
+ 'is_required' => TRUE,
+ 'add_field' => TRUE,
+ ],
+ 'check_number' => [
+ 'is_required' => FALSE,
+ 'add_field' => TRUE,
+ ],
+ // @TODO we need to show card type icon in place of select field
+ 'card_type_id' => [
+ 'is_required' => FALSE,
+ 'add_field' => TRUE,
+ ],
+ 'pan_truncation' => [
+ 'is_required' => FALSE,
+ 'add_field' => TRUE,
+ ],
+ 'trxn_id' => [
+ 'add_field' => TRUE,
+ 'is_required' => FALSE,
+ ],
+ 'trxn_date' => [
+ 'htmlType' => 'datepicker',
+ 'name' => 'trxn_date',
+ 'title' => ts('Transaction Date'),
+ 'is_required' => TRUE,
+ 'attributes' => [
+ 'date' => 'yyyy-mm-dd',
+ 'time' => 24,
+ ],
+ ],
+ 'total_amount' => [
+ 'htmlType' => 'text',
+ 'name' => 'total_amount',
+ 'title' => ts('Total Amount'),
+ 'is_required' => TRUE,
+ 'attributes' => [
+ 'readonly' => TRUE,
+ 'size' => 6,
+ ],
+ ],
+ ];
+
+ return $paymentFields;
+ }
+
+}
diff --git a/CRM/Financial/Form/SalesTaxTrait.php b/CRM/Financial/Form/SalesTaxTrait.php
new file mode 100644
index 000000000000..bf0b89818e02
--- /dev/null
+++ b/CRM/Financial/Form/SalesTaxTrait.php
@@ -0,0 +1,89 @@
+assign('taxTerm', $this->getSalesTaxTerm());
+ }
+
+ /**
+ * Assign sales tax rates to the template.
+ */
+ public function assignSalesTaxRates() {
+ $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
+ }
+
+ /**
+ * Return the string to be assigned to the template for sales tax - e.g GST, VAT.
+ *
+ * @return string
+ */
+ public function getSalesTaxTerm() {
+ $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
+ $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
+ if (!$invoicing) {
+ return '';
+ }
+ return CRM_Utils_Array::value('tax_term', $invoiceSettings);
+ }
+
+ /**
+ * Assign information to the template required for sales tax purposes.
+ */
+ public function assignSalesTaxMetadataToTemplate() {
+ $this->assignSalesTaxRates();
+ $this->assignSalesTaxTermToTemplate();
+ }
+
+ /**
+ * Get sales tax rates.
+ *
+ * @return array
+ */
+ public function getTaxRatesForFinancialTypes() {
+ return CRM_Core_PseudoConstant::getTaxRates();
+ }
+
+ /**
+ * @param int $financialTypeID
+ *
+ * @return string
+ */
+ public function getTaxRateForFinancialType($financialTypeID) {
+ return CRM_Utils_Array::value($financialTypeID, $this->getTaxRatesForFinancialTypes());
+ }
+
+}
diff --git a/CRM/Financial/Form/Search.php b/CRM/Financial/Form/Search.php
index c7d9a0b72032..30de0e886610 100644
--- a/CRM/Financial/Form/Search.php
+++ b/CRM/Financial/Form/Search.php
@@ -1,9 +1,9 @@
_batchStatus) {
@@ -63,17 +63,17 @@ public function buildQuickForm() {
$attributes['total']['class'] = $attributes['item_count']['class'] = 'number';
$this->add('text', 'title', ts('Batch Name'), $attributes['title']);
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
$this->add(
'select',
'status_id',
ts('Batch Status'),
- array(
+ [
'' => ts('- any -'),
array_search('Open', $batchStatus) => ts('Open'),
array_search('Closed', $batchStatus) => ts('Closed'),
array_search('Exported', $batchStatus) => ts('Exported'),
- ),
+ ],
FALSE
);
@@ -81,7 +81,7 @@ public function buildQuickForm() {
'select',
'payment_instrument_id',
ts('Payment Method'),
- array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ ['' => ts('- any -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE
);
@@ -90,40 +90,45 @@ public function buildQuickForm() {
$this->add('text', 'item_count', ts('Number of Items'), $attributes['item_count']);
$this->add('text', 'sort_name', ts('Created By'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
- $this->assign('elements', array('status_id', 'title', 'sort_name', 'payment_instrument_id', 'item_count', 'total'));
- $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
- $batchAction = array(
+ $this->assign('elements', ['status_id', 'title', 'sort_name', 'payment_instrument_id', 'item_count', 'total']);
+ $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
+ $batchAction = [
'reopen' => ts('Re-open'),
'close' => ts('Close'),
'export' => ts('Export'),
'delete' => ts('Delete'),
- );
+ ];
+ foreach ($batchAction as $action => $ignore) {
+ if (!CRM_Batch_BAO_Batch::checkBatchPermission($action)) {
+ unset($batchAction[$action]);
+ }
+ }
$this->add('select',
'batch_update',
ts('Task'),
- array('' => ts('- actions -')) + $batchAction);
+ ['' => ts('- actions -')] + $batchAction);
$this->add('submit', 'submit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'Go',
- ));
+ ]);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
parent::buildQuickForm();
}
public function postProcess() {
- $batchIds = array();
+ $batchIds = [];
foreach ($_POST as $key => $value) {
if (substr($key, 0, 6) == "check_") {
$batch = explode("_", $key);
diff --git a/CRM/Financial/Page/AJAX.php b/CRM/Financial/Page/AJAX.php
index 2715e99b9e18..27b4b347ca28 100644
--- a/CRM/Financial/Page/AJAX.php
+++ b/CRM/Financial/Page/AJAX.php
@@ -1,9 +1,9 @@
ts('- select -'),
'value' => 'select',
- ),
- );
+ ],
+ ];
if (!empty($result)) {
foreach ($result as $id => $name) {
- $selectedArray = array();
+ $selectedArray = [];
if ($id == $defaultId) {
$selectedArray['selected'] = 'Selected';
}
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- ) + $selectedArray;
+ ] + $selectedArray;
}
}
CRM_Utils_JSON::output($elements);
@@ -100,36 +100,36 @@ public static function jqFinancialRelation($config) {
$params['orderColumn'] = 'label';
$result = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
- $elements = array(
- array(
+ $elements = [
+ [
'name' => ts('- Select Financial Account Relationship -'),
'value' => 'select',
- ),
- );
+ ],
+ ];
$countResult = count($financialAccountType[$financialAccountTypeId]);
if (!empty($result)) {
foreach ($result as $id => $name) {
if (in_array($id, $financialAccountType[$financialAccountTypeId]) && $_GET['_value'] != 'select') {
if ($countResult != 1) {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- );
+ ];
}
else {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
'selected' => 'Selected',
- );
+ ];
}
}
elseif ($_GET['_value'] == 'select') {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- );
+ ];
}
}
}
@@ -164,17 +164,17 @@ public static function assignRemove() {
}
$entityID = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
- $methods = array(
- 'assign' => 'addBatchEntity',
- 'remove' => 'removeBatchEntity',
+ $methods = [
+ 'assign' => 'create',
+ 'remove' => 'del',
'reopen' => 'create',
'close' => 'create',
'delete' => 'deleteBatch',
- );
+ ];
if ($op == 'close') {
$totals = CRM_Batch_BAO_Batch::batchTotals($records);
}
- $response = array('status' => 'record-updated-fail');
+ $response = ['status' => 'record-updated-fail'];
// first munge and clean the recordBAO and get rid of any non alpha numeric characters
$recordBAO = CRM_Utils_String::munge($recordBAO);
$recordClass = explode('_', $recordBAO);
@@ -182,8 +182,7 @@ public static function assignRemove() {
// at least 3 levels deep
if ($recordClass[0] == 'CRM' && count($recordClass) >= 3) {
foreach ($records as $recordID) {
- $params = array();
- $ids = NULL;
+ $params = [];
switch ($op) {
case 'assign':
case 'remove':
@@ -191,14 +190,14 @@ public static function assignRemove() {
$batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
$paymentInstrument = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchPID);
if ($op == 'remove' || ($recordPID == $batchPID && $op == 'assign') || !isset($batchPID)) {
- $params = array(
+ $params = [
'entity_id' => $recordID,
'entity_table' => 'civicrm_financial_trxn',
'batch_id' => $entityID,
- );
+ ];
}
else {
- $response = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array(1 => $paymentInstrument)));
+ $response = ['status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", [1 => $paymentInstrument])];
}
break;
@@ -207,14 +206,12 @@ public static function assignRemove() {
$params = $totals[$recordID];
case 'reopen':
$status = $op == 'close' ? 'Closed' : 'Reopened';
- $ids['batchID'] = $recordID;
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
$params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
$session = CRM_Core_Session::singleton();
$params['modified_date'] = date('YmdHis');
$params['modified_id'] = $session->get('userID');
$params['id'] = $recordID;
- $context = "financialBatch";
break;
case 'export':
@@ -223,26 +220,20 @@ public static function assignRemove() {
case 'delete':
$params = $recordID;
- $context = "financialBatch";
break;
}
if (method_exists($recordBAO, $methods[$op]) & !empty($params)) {
- if (isset($context)) {
- $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params, $ids, $context));
- }
- else {
- $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params, $ids));
- }
+ $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params));
if ($updated) {
$redirectStatus = $updated->status_id;
if ($batchStatus[$updated->status_id] == "Reopened") {
$redirectStatus = array_search("Open", $batchStatus);
}
- $response = array(
+ $response = [
'status' => 'record-updated-success',
'status_id' => $redirectStatus,
- );
+ ];
}
}
}
@@ -257,17 +248,18 @@ public static function assignRemove() {
* @return string|wtf??
*/
public static function getFinancialTransactionsList() {
- $sortMapper = array(
+ $sortMapper = [
0 => '',
1 => '',
2 => 'sort_name',
3 => 'amount',
4 => 'trxn_id',
5 => 'transaction_date',
- 6 => 'payment_method',
- 7 => 'status',
- 8 => 'name',
- );
+ 6 => 'receive_date',
+ 7 => 'payment_method',
+ 8 => 'status',
+ 9 => 'name',
+ ];
$sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
$return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE;
@@ -275,7 +267,7 @@ public static function getFinancialTransactionsList() {
$rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
$sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
$sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
- $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL;
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
$entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
$notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
$statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
@@ -286,7 +278,7 @@ public static function getFinancialTransactionsList() {
$params['sortBy'] = $sort . ' ' . $sortOrder;
}
- $returnvalues = array(
+ $returnvalues = [
'civicrm_financial_trxn.payment_instrument_id as payment_method',
'civicrm_contribution.contact_id as contact_id',
'civicrm_contribution.id as contributionID',
@@ -296,22 +288,26 @@ public static function getFinancialTransactionsList() {
'contact_a.contact_type',
'contact_a.contact_sub_type',
'civicrm_financial_trxn.trxn_date as transaction_date',
+ 'civicrm_contribution.receive_date as receive_date',
'civicrm_financial_type.name',
'civicrm_financial_trxn.currency as currency',
'civicrm_financial_trxn.status_id as status',
'civicrm_financial_trxn.check_number as check_number',
- );
+ 'civicrm_financial_trxn.card_type_id',
+ 'civicrm_financial_trxn.pan_truncation',
+ ];
- $columnHeader = array(
+ $columnHeader = [
'contact_type' => '',
'sort_name' => ts('Contact Name'),
'amount' => ts('Amount'),
'trxn_id' => ts('Trxn ID'),
- 'transaction_date' => ts('Received'),
+ 'transaction_date' => ts('Transaction Date'),
+ 'receive_date' => ts('Received'),
'payment_method' => ts('Payment Method'),
'status' => ts('Status'),
'name' => ts('Type'),
- );
+ ];
if ($sort && $sortOrder) {
$params['sortBy'] = $sort . ' ' . $sortOrder;
@@ -353,20 +349,20 @@ public static function getFinancialTransactionsList() {
$params['total'] = count($assignedTransactionsCount);
}
}
- $financialitems = array();
+ $financialitems = [];
if ($statusID) {
- $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name', 'condition' => " v.value={$statusID}"));
+ $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$statusID}"]);
$batchStatus = $batchStatuses[$statusID];
}
while ($financialItem->fetch()) {
- $row[$financialItem->id] = array();
+ $row[$financialItem->id] = [];
foreach ($columnHeader as $columnKey => $columnValue) {
if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
$row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
continue;
}
$row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
- if ($columnKey == 'sort_name' && $financialItem->$columnKey) {
+ if ($columnKey == 'sort_name' && $financialItem->$columnKey && $financialItem->contact_id) {
$url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=" . $financialItem->contact_id);
$row[$financialItem->id][$columnKey] = '' . $financialItem->$columnKey . '';
}
@@ -383,22 +379,25 @@ public static function getFinancialTransactionsList() {
elseif ($columnKey == 'transaction_date' && $financialItem->$columnKey) {
$row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
}
+ elseif ($columnKey == 'receive_date' && $financialItem->$columnKey) {
+ $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
+ }
elseif ($columnKey == 'status' && $financialItem->$columnKey) {
$row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->$columnKey);
}
}
- if (isset($batchStatus) && in_array($batchStatus, array('Open', 'Reopened'))) {
+ if (isset($batchStatus) && in_array($batchStatus, ['Open', 'Reopened'])) {
if (isset($notPresent)) {
$js = "enableActions('x')";
$row[$financialItem->id]['check'] = "";
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
CRM_Financial_Form_BatchTransaction::links(),
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -412,11 +411,11 @@ public static function getFinancialTransactionsList() {
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
CRM_Financial_Page_BatchTransaction::links(),
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -433,11 +432,11 @@ public static function getFinancialTransactionsList() {
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
$links,
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -445,23 +444,26 @@ public static function getFinancialTransactionsList() {
$financialItem->id
);
}
- $row[$financialItem->id]['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage(CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) ? CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) : CRM_Utils_Array::value('contact_type', $row[$financialItem->id]), FALSE, $financialItem->contact_id);
+ if ($financialItem->contact_id) {
+ $row[$financialItem->id]['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage(CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) ? $row[$financialItem->id]['contact_sub_type'] : CRM_Utils_Array::value('contact_type', $row[$financialItem->id]), FALSE, $financialItem->contact_id);
+ }
$financialitems = $row;
}
$iFilteredTotal = $iTotal = $params['total'];
- $selectorElements = array(
+ $selectorElements = [
'check',
'contact_type',
'sort_name',
'amount',
'trxn_id',
'transaction_date',
+ 'receive_date',
'payment_method',
'status',
'name',
'action',
- );
+ ];
if ($return) {
return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
@@ -487,31 +489,31 @@ public static function bulkAssignRemove() {
foreach ($cIDs as $key => $value) {
$recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $value, 'payment_instrument_id');
if ($action == 'Remove' || ($recordPID == $batchPID && $action == 'Assign') || !isset($batchPID)) {
- $params = array(
+ $params = [
'entity_id' => $value,
'entity_table' => 'civicrm_financial_trxn',
'batch_id' => $entityID,
- );
+ ];
if ($action == 'Assign') {
- $updated = CRM_Batch_BAO_Batch::addBatchEntity($params);
+ $updated = CRM_Batch_BAO_EntityBatch::create($params);
}
else {
- $updated = CRM_Batch_BAO_Batch::removeBatchEntity($params);
+ $updated = CRM_Batch_BAO_EntityBatch::del($params);
}
}
}
if ($updated) {
- $status = array('status' => 'record-updated-success');
+ $status = ['status' => 'record-updated-success'];
}
else {
- $status = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array(1 => $paymentInstrument)));
+ $status = ['status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", [1 => $paymentInstrument])];
}
CRM_Utils_JSON::output($status);
}
public static function getBatchSummary() {
$batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
- $params = array('id' => $batchID);
+ $params = ['id' => $batchID];
$batchSummary = self::makeBatchSummary($batchID, $params);
@@ -528,8 +530,8 @@ public static function getBatchSummary() {
*/
public static function makeBatchSummary($batchID, $params) {
$batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
- $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID));
- $batchSummary = array(
+ $batchTotals = CRM_Batch_BAO_Batch::batchTotals([$batchID]);
+ $batchSummary = [
'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
'status' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'status_id', $batchInfo->status_id),
'description' => $batchInfo->description,
@@ -539,7 +541,7 @@ public static function makeBatchSummary($batchID, $params) {
'total' => CRM_Utils_Money::format($batchInfo->total),
'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
- );
+ ];
return $batchSummary;
}
diff --git a/CRM/Financial/Page/Batch.php b/CRM/Financial/Page/Batch.php
index 58126d73d6fb..36340646abc5 100644
--- a/CRM/Financial/Page/Batch.php
+++ b/CRM/Financial/Page/Batch.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ 'view' => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&id=%%contid%%&cid=%%cid%%&action=view&context=contribution&selectedChild=contribute',
'title' => ts('View Contribution'),
- ),
- 'remove' => array(
+ ],
+ 'remove' => [
'name' => ts('Remove'),
'title' => ts('Remove Transaction'),
'extra' => 'onclick = "assignRemove( %%id%%,\'' . 'remove' . '\' );"',
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -91,23 +91,25 @@ public function &links() {
*/
public function run() {
// get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
+ // default to 'browse'
+ $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
// assign vars to templates
$this->assign('action', $action);
self::$_entityID = CRM_Utils_Request::retrieve('bid', 'Positive');
+ $statusID = NULL;
if (isset(self::$_entityID)) {
$statusID = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'status_id');
}
$breadCrumb
- = array(
- array(
+ = [
+ [
'title' => ts('Accounting Batches'),
'url' => CRM_Utils_System::url('civicrm/financial/financialbatches',
"reset=1&batchStatus=$statusID"),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$this->edit($action, self::$_entityID);
diff --git a/CRM/Financial/Page/FinancialAccount.php b/CRM/Financial/Page/FinancialAccount.php
index 3bfe8862a2b6..74c38c429c95 100644
--- a/CRM/Financial/Page/FinancialAccount.php
+++ b/CRM/Financial/Page/FinancialAccount.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialAccount',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Financial Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Financial Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Financial Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialAccount',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Financial Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
- /**
- * Run the page.
- *
- * This method is called after the page is created. It checks for the
- * type of action and executes that action.
- * Finally it calls the parent's run method.
- */
- public function run() {
- // get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
-
- // assign vars to templates
- $this->assign('action', $action);
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
-
- // what action to take ?
- if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $this->edit($action, $id);
- }
-
- // parent run
- return parent::run();
- }
-
/**
* Browse all custom data groups.
*/
public function browse() {
// get all custom groups sorted by weight
- $contributionType = array();
+ $contributionType = [];
$dao = new CRM_Financial_DAO_FinancialAccount();
$dao->orderBy('financial_account_type_id, name');
$dao->find();
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
while ($dao->fetch()) {
- $contributionType[$dao->id] = array();
+ $contributionType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $contributionType[$dao->id]);
$contributionType[$dao->id]['financial_account_type_id'] = $financialAccountType[$dao->financial_account_type_id];
// form all action links
@@ -146,7 +122,7 @@ public function browse() {
}
$contributionType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'financialAccount.manage.action',
diff --git a/CRM/Financial/Page/FinancialBatch.php b/CRM/Financial/Page/FinancialBatch.php
index 17b9cf84b7ef..0c25a0a72b99 100644
--- a/CRM/Financial/Page/FinancialBatch.php
+++ b/CRM/Financial/Page/FinancialBatch.php
@@ -1,9 +1,9 @@
set("context", $context);
- // assign vars to templates
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
+
+ $id = $this->getIdAndAction();
// what action to take ?
- if ($action & (CRM_Core_Action::UPDATE |
+ if ($this->_action & (CRM_Core_Action::UPDATE |
CRM_Core_Action::ADD |
CRM_Core_Action::CLOSE |
CRM_Core_Action::REOPEN |
CRM_Core_Action::EXPORT)
) {
- $this->edit($action, $id);
+ $this->edit($this->_action, $id);
}
// parent run
- return parent::run();
+ return CRM_Core_Page::run();
}
-
/**
* Get name of edit form.
*
diff --git a/CRM/Financial/Page/FinancialType.php b/CRM/Financial/Page/FinancialType.php
index 7d3ff037d802..f0e1f1823214 100644
--- a/CRM/Financial/Page/FinancialType.php
+++ b/CRM/Financial/Page/FinancialType.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::BROWSE => [
'name' => ts('Accounts'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'reset=1&action=browse&aid=%%id%%',
'title' => ts('Accounts'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialType',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Financial Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Financial Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Financial Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialType',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Financial Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
- /**
- * Run the page.
- *
- * This method is called after the page is created. It checks for the
- * type of action and executes that action.
- * Finally it calls the parent's run method.
- */
- public function run() {
- // get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
-
- // assign vars to templates
- $this->assign('action', $action);
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
-
- // what action to take ?
- if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $this->edit($action, $id);
- }
-
- // parent run
- return parent::run();
- }
-
/**
* Browse all financial types.
*/
@@ -131,21 +107,22 @@ public function browse() {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
// get all financial types sorted by weight
- $financialType = array();
+ $financialType = [];
$dao = new CRM_Financial_DAO_FinancialType();
$dao->orderBy('name');
$dao->find();
while ($dao->fetch()) {
- $financialType[$dao->id] = array();
+ $financialType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
- $defaults = $financialAccountId = array();
+ $defaults = $financialAccountId = [];
$financialAccounts = CRM_Contribute_PseudoConstant::financialAccount();
- $financialAccountIds = array();
+ $financialAccountIds = [];
$params['entity_id'] = $dao->id;
$params['entity_table'] = 'civicrm_financial_type';
- CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, CRM_Core_DAO::$_nullArray, $financialAccountIds);
+ $null = [];
+ CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $null, $financialAccountIds);
foreach ($financialAccountIds as $key => $values) {
if (!empty($financialAccounts[$values['financial_account_id']])) {
@@ -177,7 +154,7 @@ public function browse() {
}
$financialType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'financialType.manage.action',
diff --git a/CRM/Financial/Page/FinancialTypeAccount.php b/CRM/Financial/Page/FinancialTypeAccount.php
index 5f20b5f2b22b..c4f019b6645c 100644
--- a/CRM/Financial/Page/FinancialTypeAccount.php
+++ b/CRM/Financial/Page/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'action=update&id=%%id%%&aid=%%aid%%&reset=1',
'title' => ts('Edit Financial Type Account'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'action=delete&id=%%id%%&aid=%%aid%%',
'title' => ts('Delete Financial Type Account'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -94,7 +94,8 @@ public function &links() {
*/
public function run() {
// get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
+ // default to 'browse'
+ $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
// assign vars to templates
$this->assign('action', $action);
@@ -118,8 +119,8 @@ public function run() {
*/
public function browse() {
// get all Financial Type Account data sorted by weight
- $financialType = array();
- $params = array();
+ $financialType = [];
+ $params = [];
$dao = new CRM_Financial_DAO_EntityFinancialAccount();
$params['entity_id'] = $this->_aid;
$params['entity_table'] = 'civicrm_financial_type';
@@ -132,11 +133,11 @@ public function browse() {
$dao->copyValues($params);
$dao->find();
while ($dao->fetch()) {
- $financialType[$dao->id] = array();
+ $financialType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
- $params = array('id' => $dao->financial_account_id);
- $defaults = array();
+ $params = ['id' => $dao->financial_account_id];
+ $defaults = [];
$financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, $defaults);
if (!empty($financialAccount)) {
$financialType[$dao->id]['financial_account'] = $financialAccount->name;
@@ -165,10 +166,10 @@ public function browse() {
unset($links[CRM_Core_Action::DELETE]);
}
$financialType[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
- array(
+ [
'id' => $dao->id,
'aid' => $dao->entity_id,
- ),
+ ],
ts('more'),
FALSE,
'financialTypeAccount.manage.action',
diff --git a/CRM/Friend/BAO/Friend.php b/CRM/Friend/BAO/Friend.php
index acd6ca2a48c9..2e8328255df8 100644
--- a/CRM/Friend/BAO/Friend.php
+++ b/CRM/Friend/BAO/Friend.php
@@ -1,9 +1,9 @@
copyValues($params);
-
$friend->find(TRUE);
-
CRM_Core_DAO::storeValues($friend, $values);
-
return $values;
}
@@ -88,38 +91,41 @@ public static function retrieve(&$params, &$values) {
* Takes an associative array and creates a friend object.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * (reference) an assoc array of name/value pairs.
*
- * @return void
+ * @throws \CRM_Core_Exception
*/
public static function create(&$params) {
$transaction = new CRM_Core_Transaction();
- $mailParams = array();
- //create contact corresponding to each friend
+ $mailParams = [];
+ $contactParams = [];
+
+ // create contact corresponding to each friend
foreach ($params['friend'] as $key => $details) {
if ($details["first_name"]) {
- $contactParams[$key] = array(
+ $contactParams[$key] = [
'first_name' => $details["first_name"],
'last_name' => $details["last_name"],
'contact_source' => ts('Tell a Friend') . ": {$params['title']}",
'email-Primary' => $details["email"],
- );
+ ];
$displayName = $details["first_name"] . " " . $details["last_name"];
$mailParams['email'][$displayName] = $details["email"];
}
}
- $frndParams = array();
- $frndParams['entity_id'] = $params['entity_id'];
- $frndParams['entity_table'] = $params['entity_table'];
- self::getValues($frndParams);
+ $friendParams = [
+ 'entity_id' => $params['entity_id'],
+ 'entity_table' => $params['entity_table'],
+ ];
+ self::getValues($friendParams);
$activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'Tell a Friend', 'value', 'name');
- //create activity
- $activityParams = array(
+ // create activity
+ $activityParams = [
'source_contact_id' => $params['source_contact_id'],
'source_record_id' => NULL,
'activity_type_id' => $activityTypeId,
@@ -127,33 +133,32 @@ public static function create(&$params) {
'activity_date_time' => date("YmdHis"),
'subject' => ts('Tell a Friend') . ": {$params['title']}",
'details' => $params['suggested_message'],
- 'status_id' => 2,
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
'is_test' => $params['is_test'],
'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
- );
+ ];
- //activity creation
+ // activity creation
$activity = CRM_Activity_BAO_Activity::create($activityParams);
- $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
+ $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
- //friend contacts creation
+ // friend contacts creation
foreach ($contactParams as $key => $value) {
-
- //create contact only if it does not exits in db
+ // create contact only if it does not exits in db
$value['email'] = $value['email-Primary'];
- $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($value, 'Individual', 'Supervised', array(), FALSE);
+ $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($value, 'Individual', 'Supervised', [], FALSE);
if (!$contactID) {
$contactID = self::add($value);
}
// attempt to save activity targets
- $targetParams = array(
+ $targetParams = [
'activity_id' => $activity->id,
'contact_id' => $contactID,
'record_type_id' => $targetID,
- );
+ ];
// See if it already exists
$activityContact = new CRM_Activity_DAO_ActivityContact();
@@ -167,28 +172,27 @@ public static function create(&$params) {
$transaction->commit();
- //process sending of mails
+ // Process sending of mails
$mailParams['title'] = CRM_Utils_Array::value('title', $params);
- $mailParams['general_link'] = CRM_Utils_Array::value('general_link', $frndParams);
+ $mailParams['general_link'] = CRM_Utils_Array::value('general_link', $friendParams);
$mailParams['message'] = CRM_Utils_Array::value('suggested_message', $params);
- // get domain
- $domainDetails = CRM_Core_BAO_Domain::getNameAndEmail();
- list($username, $mailParams['domain']) = explode('@', $domainDetails[1]);
+ // Default "from email address" is default domain address.
+ list($_, $mailParams['email_from']) = CRM_Core_BAO_Domain::getNameAndEmail();
+ list($username, $mailParams['domain']) = explode('@', $mailParams['email_from']);
- $default = array();
- $findProperties = array('id' => $params['entity_id']);
+ $default = [];
+ $findProperties = ['id' => $params['entity_id']];
if ($params['entity_table'] == 'civicrm_contribution_page') {
-
- $returnProperties = array('receipt_from_email', 'is_email_receipt');
+ $returnProperties = ['receipt_from_email', 'is_email_receipt'];
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage',
$findProperties,
$default,
$returnProperties
);
- //if is_email_receipt is set then take receipt_from_email
- //as from_email
+
+ // if is_email_receipt is set then take receipt_from_email as from_email
if (!empty($default['is_email_receipt']) && !empty($default['receipt_from_email'])) {
$mailParams['email_from'] = $default['receipt_from_email'];
}
@@ -197,18 +201,14 @@ public static function create(&$params) {
$mailParams['module'] = 'contribute';
}
elseif ($params['entity_table'] == 'civicrm_event') {
-
- $returnProperties = array('confirm_from_email', 'is_email_confirm');
+ $returnProperties = ['confirm_from_email', 'is_email_confirm'];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event',
$findProperties,
$default,
$returnProperties
);
- $mailParams['email_from'] = $domainDetails['1'];
-
- //if is_email_confirm is set then take confirm_from_email
- //as from_email
+ // if is_email_confirm is set then take confirm_from_email as from_email
if (!empty($default['is_email_confirm']) && !empty($default['confirm_from_email'])) {
$mailParams['email_from'] = $default['confirm_from_email'];
}
@@ -217,34 +217,36 @@ public static function create(&$params) {
$mailParams['module'] = 'event';
}
elseif ($params['entity_table'] == 'civicrm_pcp') {
- $mailParams['email_from'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $params['source_contact_id'],
- 'email', 'contact_id'
- );
+ if (Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ $mailParams['email_from'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $params['source_contact_id'],
+ 'email', 'contact_id'
+ );
+ }
$urlPath = 'civicrm/pcp/info';
$mailParams['module'] = 'contribute';
}
$mailParams['page_url'] = CRM_Utils_System::url($urlPath, "reset=1&id={$params['entity_id']}", TRUE, NULL, FALSE, TRUE);
- //send mail
+ // Send the email
self::sendMail($params['source_contact_id'], $mailParams);
}
/**
* Build the form object.
*
- * @param CRM_Core_Form $form
+ * @param CRM_Friend_Form $form
* Form object.
*
* @return void
*/
public static function buildFriendForm($form) {
- $form->addElement('checkbox', 'tf_is_active', ts('Tell a Friend enabled?'), NULL, array('onclick' => "friendBlock(this)"));
+ $form->addElement('checkbox', 'tf_is_active', ts('Tell a Friend enabled?'), NULL, ['onclick' => "friendBlock(this)"]);
// name
$form->add('text', 'tf_title', ts('Title'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'title'), TRUE);
// intro-text and thank-you text
- $form->add('wysiwyg', 'intro', ts('Introduction'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'intro') + array('class' => 'collapsed'));
+ $form->add('wysiwyg', 'intro', ts('Introduction'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'intro') + ['class' => 'collapsed']);
$form->add('textarea', 'suggested_message', ts('Suggested Message'),
CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'suggested_message'), FALSE
@@ -254,7 +256,7 @@ public static function buildFriendForm($form) {
$form->add('text', 'tf_thankyou_title', ts('Thank-you Title'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_title'), TRUE);
- $form->add('wysiwyg', 'tf_thankyou_text', ts('Thank-you Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_text') + array('class' => 'collapsed'));
+ $form->add('wysiwyg', 'tf_thankyou_text', ts('Thank-you Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_text') + ['class' => 'collapsed']);
if ($form->_friendId) {
// CRM-14200 the i18n dialogs need this for translation
@@ -263,12 +265,12 @@ public static function buildFriendForm($form) {
}
/**
- * The function sets the deafult values of the form.
+ * The function sets the default values of the form.
*
* @param array $defaults
* (reference) the default values.
*
- * @return booelan
+ * @return bool
* whether anything was found
*/
public static function getValues(&$defaults) {
@@ -283,7 +285,7 @@ public static function getValues(&$defaults) {
}
/**
- * Process that send tell a friend e-mails
+ * Process that sends tell a friend e-mails
*
* @param int $contactID
* @param array $values
@@ -297,33 +299,41 @@ public static function sendMail($contactID, &$values) {
$fromName = $email;
}
- // use contact email, CRM-4963
+ if (Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ // use contact email, CRM-4963
+ if (empty($values['email_from'])) {
+ $values['email_from'] = $email;
+ }
+ }
+
+ // If we have no "email_from" when we get to here, explicitly set it to the default domain email.
if (empty($values['email_from'])) {
- $values['email_from'] = $email;
+ list($domainFromName, $domainEmail) = CRM_Core_BAO_Domain::getNameAndEmail();
+ $values['email_from'] = $domainEmail;
+ $values['domain'] = $domainFromName;
}
+ $templateParams = [
+ 'groupName' => 'msg_tpl_workflow_friend',
+ 'valueName' => 'friend',
+ 'contactId' => $contactID,
+ 'tplParams' => [
+ $values['module'] => $values['module'],
+ 'senderContactName' => $fromName,
+ 'title' => $values['title'],
+ 'generalLink' => $values['general_link'],
+ 'pageURL' => $values['page_url'],
+ 'senderMessage' => $values['message'],
+ ],
+ 'from' => "$fromName (via {$values['domain']}) <{$values['email_from']}>",
+ 'replyTo' => $email,
+ ];
+
foreach ($values['email'] as $displayName => $emailTo) {
if ($emailTo) {
- // FIXME: factor the below out of the foreach loop
- CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
- 'groupName' => 'msg_tpl_workflow_friend',
- 'valueName' => 'friend',
- 'contactId' => $contactID,
- 'tplParams' => array(
- $values['module'] => $values['module'],
- 'senderContactName' => $fromName,
- 'title' => $values['title'],
- 'generalLink' => $values['general_link'],
- 'pageURL' => $values['page_url'],
- 'senderMessage' => $values['message'],
- ),
- 'from' => "$fromName (via {$values['domain']}) <{$values['email_from']}>",
- 'toName' => $displayName,
- 'toEmail' => $emailTo,
- 'replyTo' => $email,
- )
- );
+ $templateParams['toName'] = $displayName;
+ $templateParams['toEmail'] = $emailTo;
+ CRM_Core_BAO_MessageTemplate::sendTemplate($templateParams);
}
}
}
@@ -336,16 +346,14 @@ public static function sendMail($contactID, &$values) {
* pairs
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * (reference) an assoc array of name/value pairs.
*
- * @return CRM_Friend_BAO_Friend
+ * @return CRM_Friend_DAO_Friend
*/
public static function addTellAFriend(&$params) {
$friendDAO = new CRM_Friend_DAO_Friend();
-
$friendDAO->copyValues($params);
$friendDAO->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
-
$friendDAO->save();
return $friendDAO;
diff --git a/CRM/Friend/DAO/Friend.php b/CRM/Friend/DAO/Friend.php
index 186a78673fec..2e11e0822660 100644
--- a/CRM/Friend/DAO/Friend.php
+++ b/CRM/Friend/DAO/Friend.php
@@ -1,310 +1,309 @@
__table = 'civicrm_tell_friend';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Friend ID') ,
- 'description' => 'Friend ID',
- 'required' => true,
+ 'title' => ts('Friend ID'),
+ 'description' => ts('Friend ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_tell_friend.id',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Name of table where item being referenced is stored.',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Name of table where item being referenced is stored.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_tell_friend.entity_table',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'Foreign key to the referenced item.',
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Foreign key to the referenced item.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_tell_friend.entity_id',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Title') ,
+ 'title' => ts('Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_tell_friend.title',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'intro' => array(
+ ],
+ ],
+ 'intro' => [
'name' => 'intro',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Intro') ,
- 'description' => 'Introductory message to contributor or participant displayed on the Tell a Friend form.',
+ 'title' => ts('Intro'),
+ 'description' => ts('Introductory message to contributor or participant displayed on the Tell a Friend form.'),
+ 'where' => 'civicrm_tell_friend.intro',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'suggested_message' => array(
+ ],
+ ],
+ 'suggested_message' => [
'name' => 'suggested_message',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Suggested Message') ,
- 'description' => 'Suggested message to friends, provided as default on the Tell A Friend form.',
+ 'title' => ts('Suggested Message'),
+ 'description' => ts('Suggested message to friends, provided as default on the Tell A Friend form.'),
+ 'where' => 'civicrm_tell_friend.suggested_message',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'general_link' => array(
+ ],
+ ],
+ 'general_link' => [
'name' => 'general_link',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('General Link') ,
- 'description' => 'URL for general info about the organization - included in the email sent to friends.',
+ 'title' => ts('General Link'),
+ 'description' => ts('URL for general info about the organization - included in the email sent to friends.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_tell_friend.general_link',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_title' => array(
+ ],
+ ],
+ 'thankyou_title' => [
'name' => 'thankyou_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Thank You Title') ,
- 'description' => 'Text for Tell a Friend thank you page header and HTML title.',
+ 'title' => ts('Thank You Title'),
+ 'description' => ts('Text for Tell a Friend thank you page header and HTML title.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_tell_friend.thankyou_title',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_text' => array(
+ ],
+ ],
+ 'thankyou_text' => [
'name' => 'thankyou_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Thank You Text') ,
- 'description' => 'Thank you message displayed on success page.',
+ 'title' => ts('Thank You Text'),
+ 'description' => ts('Thank you message displayed on success page.'),
+ 'where' => 'civicrm_tell_friend.thankyou_text',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
+ 'title' => ts('Enabled?'),
+ 'where' => 'civicrm_tell_friend.is_active',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -312,10 +311,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'tell_friend', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'tell_friend', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -323,15 +323,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'tell_friend', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'tell_friend', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Friend/Form.php b/CRM/Friend/Form.php
index ecd589234ac8..4509acd99337 100644
--- a/CRM/Friend/Form.php
+++ b/CRM/Friend/Form.php
@@ -1,9 +1,9 @@
$this->_entityId);
+ ])) {
+ $values = [];
+ $params = ['id' => $this->_entityId];
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage',
- $params, $values, array('title', 'campaign_id', 'is_share')
+ $params, $values, ['title', 'campaign_id', 'is_share']
);
$this->_title = CRM_Utils_Array::value('title', $values);
$this->_campaignId = CRM_Utils_Array::value('campaign_id', $values);
@@ -88,6 +95,7 @@ public function preProcess() {
if ($pcomponent == 'event') {
$this->_entityTable = 'civicrm_event';
$isShare = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_entityId, 'is_share');
+ $this->_title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_entityId, 'title');
}
else {
$isShare = CRM_Utils_Array::value('is_share', $values);
@@ -98,10 +106,10 @@ public function preProcess() {
elseif ($pcomponent == 'pcp') {
$this->_pcpBlockId = CRM_Utils_Request::retrieve('blockId', 'Positive', $this, TRUE);
- $values = array();
- $params = array('id' => $this->_pcpBlockId);
+ $values = [];
+ $params = ['id' => $this->_pcpBlockId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock',
- $params, $values, array('is_tellfriend_enabled', 'tellfriend_limit')
+ $params, $values, ['is_tellfriend_enabled', 'tellfriend_limit']
);
if (empty($values['is_tellfriend_enabled'])) {
@@ -117,11 +125,10 @@ public function preProcess() {
FROM civicrm_pcp pcp
INNER JOIN civicrm_contribution_page contrib ON ( pcp.page_id = contrib.id AND pcp.page_type = "contribute" )
WHERE pcp.id = %1';
- $pcp = CRM_Core_DAO::executeQuery($sql, array(1 => array($this->_entityId, 'Positive')));
+ $pcp = CRM_Core_DAO::executeQuery($sql, [1 => [$this->_entityId, 'Positive']]);
while ($pcp->fetch()) {
$this->_title = $pcp->title;
$this->_campaignId = $pcp->campaign_id;
- $pcp->free();
}
$this->assign('pcpTitle', $this->_title);
@@ -152,7 +159,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['entity_id'] = $this->_entityId;
$defaults['entity_table'] = $this->_entityTable;
@@ -197,7 +204,7 @@ public function buildQuickForm() {
$email->freeze();
$this->add('wysiwyg', 'suggested_message', ts('Your Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'suggested_message'));
- $friend = array();
+ $friend = [];
$mailLimit = self::NUM_OPTION;
if ($this->_entityTable == 'civicrm_pcp') {
$mailLimit = $this->_mailLimit;
@@ -210,21 +217,20 @@ public function buildQuickForm() {
$this->addRule("friend[$i][email]", ts('The format of this email address is not valid.'), 'email');
}
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Send Your Message'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Friend_Form', 'formRule'));
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Send Your Message'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Friend_Form', 'formRule']);
}
/**
@@ -237,7 +243,7 @@ public function buildQuickForm() {
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
$valid = FALSE;
foreach ($fields['friend'] as $key => $val) {
@@ -285,7 +291,7 @@ public function postProcess() {
CRM_Friend_BAO_Friend::create($formValues);
$this->assign('status', 'thankyou');
- $defaults = array();
+ $defaults = [];
$defaults['entity_id'] = $this->_entityId;
$defaults['entity_table'] = $this->_entityTable;
diff --git a/CRM/Friend/Form/Contribute.php b/CRM/Friend/Form/Contribute.php
index e59f94074f82..f4bb3971944b 100644
--- a/CRM/Friend/Form/Contribute.php
+++ b/CRM/Friend/Form/Contribute.php
@@ -1,9 +1,9 @@
_id)) {
$defaults['entity_table'] = 'civicrm_contribution_page';
diff --git a/CRM/Friend/Form/Event.php b/CRM/Friend/Form/Event.php
index 86f2a1d9a562..2e68f80dc88d 100644
--- a/CRM/Friend/Form/Event.php
+++ b/CRM/Friend/Form/Event.php
@@ -1,9 +1,9 @@
setSelectedChild('friend');
}
/**
@@ -57,7 +58,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
$defaults['entity_table'] = 'civicrm_event';
diff --git a/CRM/Grant/BAO/Grant.php b/CRM/Grant/BAO/Grant.php
index 7a669d599e6b..4db6f2a3c23f 100644
--- a/CRM/Grant/BAO/Grant.php
+++ b/CRM/Grant/BAO/Grant.php
@@ -1,9 +1,9 @@
$name) {
- $stats[$id] = array(
+ $stats[$id] = [
'label' => $name,
'total' => 0,
- );
+ ];
}
while ($dao->fetch()) {
- $stats[$dao->status_id] = array(
+ $stats[$dao->status_id] = [
'label' => $status[$dao->status_id],
'total' => $dao->status_total,
- );
+ ];
$summary['total_grants'] += $dao->status_total;
}
@@ -96,10 +90,10 @@ public static function getGrantSummary($admin = FALSE) {
*/
public static function getGrantStatusOptGroup() {
- $params = array();
+ $params = [];
$params['name'] = CRM_Grant_BAO_Grant::$statusGroupName;
- $defaults = array();
+ $defaults = [];
$og = CRM_Core_BAO_OptionGroup::retrieve($params, $defaults);
if (!$og) {
@@ -150,23 +144,23 @@ public static function add(&$params, &$ids) {
}
// first clean up all the money fields
- $moneyFields = array(
+ $moneyFields = [
'amount_total',
'amount_granted',
'amount_requested',
- );
+ ];
foreach ($moneyFields as $field) {
if (isset($params[$field])) {
$params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
}
}
// convert dates to mysql format
- $dates = array(
+ $dates = [
'application_received_date',
'decision_date',
'money_transfer_date',
'grant_due_date',
- );
+ ];
foreach ($dates as $d) {
if (isset($params[$d])) {
@@ -197,7 +191,7 @@ public static function add(&$params, &$ids) {
}
$title = CRM_Contact_BAO_Contact::displayName($grant->contact_id) . ' - ' . ts('Grant') . ': ' . $grantTypes[$grant->grant_type_id];
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviGrant', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/grant',
"action=update&reset=1&id={$grant->id}&cid={$grant->contact_id}&context=home"
@@ -256,23 +250,23 @@ public static function create(&$params, &$ids) {
$id = CRM_Utils_Array::value('contact_id', $params);
}
if (!empty($params['note']) || CRM_Utils_Array::value('id', CRM_Utils_Array::value('note', $ids))) {
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_grant',
'note' => $params['note'] = $params['note'] ? $params['note'] : "null",
'entity_id' => $grant->id,
'contact_id' => $id,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Note::add($noteParams, (array) CRM_Utils_Array::value('note', $ids));
}
// Log the information on successful add/edit of Grant
- $logParams = array(
+ $logParams = [
'entity_table' => 'civicrm_grant',
'entity_id' => $grant->id,
'modified_id' => $id,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Log::add($logParams);
@@ -325,10 +319,10 @@ public static function del($id) {
$grant->find();
// delete the recently created Grant
- $grantRecent = array(
+ $grantRecent = [
'id' => $id,
'type' => 'Grant',
- );
+ ];
CRM_Utils_Recent::del($grantRecent);
if ($grant->fetch()) {
@@ -346,54 +340,19 @@ public static function del($id) {
* array of exportable Fields
*/
public static function &exportableFields() {
- if (!self::$_exportableFields) {
- if (!self::$_exportableFields) {
- self::$_exportableFields = array();
- }
-
- $grantFields = array(
- 'grant_status' => array(
- 'title' => ts('Grant Status'),
- 'name' => 'grant_status',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_type' => array(
- 'title' => ts('Grant Type'),
- 'name' => 'grant_type',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_money_transfer_date' => array(
- 'title' => ts('Grant Money Transfer Date'),
- 'name' => 'grant_money_transfer_date',
- 'data_type' => CRM_Utils_Type::T_DATE,
- ),
- 'grant_amount_requested' => array(
- 'title' => ts('Grant Amount Requested'),
- 'name' => 'grant_amount_requested',
- 'data_type' => CRM_Utils_Type::T_FLOAT,
- ),
- 'grant_application_received_date' => array(
- 'title' => ts('Grant Application Received Date'),
- 'name' => 'grant_application_received_date',
- 'data_type' => CRM_Utils_Type::T_DATE,
- ),
- );
-
- $fields = CRM_Grant_DAO_Grant::export();
- $grantNote = array(
- 'grant_note' => array(
- 'title' => ts('Grant Note'),
- 'name' => 'grant_note',
- 'data_type' => CRM_Utils_Type::T_TEXT,
- ),
- );
- $fields = array_merge($fields, $grantFields, $grantNote,
- CRM_Core_BAO_CustomField::getFieldsForImport('Grant')
- );
- self::$_exportableFields = $fields;
- }
+ $fields = CRM_Grant_DAO_Grant::export();
+ $grantNote = [
+ 'grant_note' => [
+ 'title' => ts('Grant Note'),
+ 'name' => 'grant_note',
+ 'data_type' => CRM_Utils_Type::T_TEXT,
+ ],
+ ];
+ $fields = array_merge($fields, $grantNote,
+ CRM_Core_BAO_CustomField::getFieldsForImport('Grant')
+ );
- return self::$_exportableFields;
+ return $fields;
}
/**
diff --git a/CRM/Grant/BAO/Query.php b/CRM/Grant/BAO/Query.php
index d10acbe418d6..b76fcfd5118e 100644
--- a/CRM/Grant/BAO/Query.php
+++ b/CRM/Grant/BAO/Query.php
@@ -1,9 +1,9 @@
_where[$grouping][] = "civicrm_grant.application_received_date IS NULL";
$query->_qill[$grouping][] = ts("Grant Application Received Date is NULL");
$query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
@@ -159,7 +158,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'grant_due_date_high':
$query->dateQueryBuilder($values, 'civicrm_grant',
'grant_due_date',
- 'grant_due_date', 'Grant Due Date'
+ 'grant_due_date', ts('Grant Due Date')
);
return;
@@ -173,7 +172,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'grant_decision_date_high':
$query->dateQueryBuilder($values, 'civicrm_grant',
'grant_decision_date',
- 'decision_date', 'Grant Decision Date'
+ 'decision_date', ts('Grant Decision Date')
);
return;
@@ -190,17 +189,17 @@ public static function whereClauseSingle(&$values, &$query) {
if (strstr($name, 'type')) {
$name = 'grant_type_id';
- $label = 'Grant Type(s)';
+ $label = ts('Grant Type(s)');
}
else {
$name = 'status_id';
- $label = 'Grant Status(s)';
+ $label = ts('Grant Status(s)');
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_grant.$name", $op, $value, "Integer");
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Grant_DAO_Grant', $name, $value, $op);
- $query->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
+ $query->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
$query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
return;
@@ -208,15 +207,15 @@ public static function whereClauseSingle(&$values, &$query) {
case 'grant_report_received':
if ($value == 1) {
- $yesNo = 'Yes';
+ $yesNo = ts('Yes');
$query->_where[$grouping][] = "civicrm_grant.grant_report_received $op $value";
}
elseif ($value == 0) {
- $yesNo = 'No';
+ $yesNo = ts('No');
$query->_where[$grouping][] = "civicrm_grant.grant_report_received IS NULL";
}
- $query->_qill[$grouping][] = "Grant Report Received = $yesNo ";
+ $query->_qill[$grouping][] = ts('Grant Report Received = %1', [1 => $yesNo]);
$query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
return;
@@ -279,7 +278,7 @@ public static function defaultReturnProperties(
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_GRANT) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -291,61 +290,68 @@ public static function defaultReturnProperties(
'grant_report_received' => 1,
'grant_money_transfer_date' => 1,
'grant_note' => 1,
- );
+ ];
}
return $properties;
}
+ /**
+ * Get the metadata for fields to be included on the grant search form.
+ */
+ public static function getSearchFieldMetadata() {
+ $fields = [
+ 'grant_report_received',
+ 'grant_application_received_date',
+ 'grant_decision_date',
+ 'grant_money_transfer_date',
+ 'grant_due_date',
+ ];
+ $metadata = civicrm_api3('Grant', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
+ /**
+ * Transitional function for specifying which fields the tpl can iterate through.
+ */
+ public static function getTemplateHandlableSearchFields() {
+ return array_diff_key(self::getSearchFieldMetadata(), ['grant_report_received' => 1]);
+ }
+
/**
* Add all the elements shared between grant search and advanaced search.
*
*
- * @param CRM_Core_Form $form
+ * @param \CRM_Grant_Form_Search $form
*
* @return void
*/
public static function buildSearchForm(&$form) {
$grantType = CRM_Core_OptionGroup::values('grant_type');
+ $form->addSearchFieldMetadata(['Grant' => self::getSearchFieldMetadata()]);
+ $form->addFormFieldsFromMetadata();
+ $form->assign('grantSearchFields', self::getTemplateHandlableSearchFields());
$form->add('select', 'grant_type_id', ts('Grant Type'), $grantType, FALSE,
- array('id' => 'grant_type_id', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'grant_type_id', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
$grantStatus = CRM_Core_OptionGroup::values('grant_status');
$form->add('select', 'grant_status_id', ts('Grant Status'), $grantStatus, FALSE,
- array('id' => 'grant_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'grant_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
+ $form->addElement('checkbox', 'grant_application_received_date_notset', ts('Date is not set'), NULL);
+ $form->addElement('checkbox', 'grant_money_transfer_date_notset', ts('Date is not set'), NULL);
+ $form->addElement('checkbox', 'grant_due_date_notset', ts('Date is not set'), NULL);
+ $form->addElement('checkbox', 'grant_decision_date_notset', ts('Date is not set'), NULL);
- $form->addDate('grant_application_received_date_low', ts('App. Received Date - From'), FALSE, array('formatType' => 'searchDate'));
- $form->addDate('grant_application_received_date_high', ts('To'), FALSE, array('formatType' => 'searchDate'));
-
- $form->addElement('checkbox', 'grant_application_received_notset', '', NULL);
-
- $form->addDate('grant_money_transfer_date_low', ts('Money Sent Date - From'), FALSE, array('formatType' => 'searchDate'));
- $form->addDate('grant_money_transfer_date_high', ts('To'), FALSE, array('formatType' => 'searchDate'));
-
- $form->addElement('checkbox', 'grant_money_transfer_date_notset', '', NULL);
-
- $form->addDate('grant_due_date_low', ts('Report Due Date - From'), FALSE, array('formatType' => 'searchDate'));
- $form->addDate('grant_due_date_high', ts('To'), FALSE, array('formatType' => 'searchDate'));
-
- $form->addElement('checkbox', 'grant_due_date_notset', '', NULL);
-
- $form->addDate('grant_decision_date_low', ts('Grant Decision Date - From'), FALSE, array('formatType' => 'searchDate'));
- $form->addDate('grant_decision_date_high', ts('To'), FALSE, array('formatType' => 'searchDate'));
-
- $form->addElement('checkbox', 'grant_decision_date_notset', '', NULL);
-
- $form->addYesNo('grant_report_received', ts('Grant report received?'), TRUE);
-
- $form->add('text', 'grant_amount_low', ts('Minimum Amount'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('grant_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+ $form->add('text', 'grant_amount_low', ts('Minimum Amount'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('grant_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
- $form->add('text', 'grant_amount_high', ts('Maximum Amount'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('grant_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $form->add('text', 'grant_amount_high', ts('Maximum Amount'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('grant_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
- self::addCustomFormFields($form, array('Grant'));
+ self::addCustomFormFields($form, ['Grant']);
$form->assign('validGrant', TRUE);
}
diff --git a/CRM/Grant/Controller/Search.php b/CRM/Grant/Controller/Search.php
index c04784ab45b0..847ac448a7d3 100644
--- a/CRM/Grant/Controller/Search.php
+++ b/CRM/Grant/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_grant';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'grant_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'grant_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant ID') ,
- 'description' => 'Unique Grant id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Grant ID'),
+ 'description' => ts('Unique Grant id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_grant.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- ) ,
- 'grant_contact_id' => array(
+ ],
+ 'grant_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Contact ID of contact record given grant belongs to.',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Contact ID of contact record given grant belongs to.'),
+ 'required' => TRUE,
'where' => 'civicrm_grant.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'application_received_date' => array(
+ ],
+ ],
+ 'grant_application_received_date' => [
'name' => 'application_received_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Application received date') ,
- 'description' => 'Date on which grant application was received by donor.',
- 'export' => true,
+ 'title' => ts('Application received date'),
+ 'description' => ts('Date on which grant application was received by donor.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.application_received_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- ) ,
- 'decision_date' => array(
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_decision_date' => [
'name' => 'decision_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Decision date') ,
- 'description' => 'Date on which grant decision was made.',
- 'import' => true,
+ 'title' => ts('Decision date'),
+ 'description' => ts('Date on which grant decision was made.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.decision_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_money_transfer_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_money_transfer_date' => [
'name' => 'money_transfer_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Grant Money transfer date') ,
- 'description' => 'Date on which grant money transfer was made.',
- 'import' => true,
+ 'title' => ts('Grant Money transfer date'),
+ 'description' => ts('Date on which grant money transfer was made.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.money_transfer_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_due_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_due_date' => [
'name' => 'grant_due_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Grant Due Date') ,
- 'description' => 'Date on which grant report is due.',
+ 'title' => ts('Grant Report Due Date'),
+ 'description' => ts('Date on which grant report is due.'),
+ 'import' => TRUE,
+ 'where' => 'civicrm_grant.grant_due_date',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_report_received' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_report_received' => [
'name' => 'grant_report_received',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Grant report received') ,
- 'description' => 'Yes/No field stating whether grant report was received by donor.',
- 'import' => true,
+ 'title' => ts('Grant report received'),
+ 'description' => ts('Yes/No field stating whether grant report was received by donor.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.grant_report_received',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'grant_type_id' => array(
+ ],
+ ],
+ 'grant_type_id' => [
'name' => 'grant_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant Type') ,
- 'description' => 'Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Grant Type'),
+ 'description' => ts('Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.'),
+ 'required' => TRUE,
'where' => 'civicrm_grant.grant_type_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'grant_type',
'optionEditPath' => 'civicrm/admin/options/grant_type',
- )
- ) ,
- 'amount_total' => array(
+ ],
+ ],
+ 'amount_total' => [
'name' => 'amount_total',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Total Amount') ,
- 'description' => 'Requested grant amount, in default currency.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Total Amount'),
+ 'description' => ts('Requested grant amount, in default currency.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_total',
- 'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'amount_requested' => array(
+ ],
+ ],
+ 'amount_requested' => [
'name' => 'amount_requested',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount Requested') ,
- 'description' => 'Requested grant amount, in original currency (optional).',
- 'precision' => array(
+ 'title' => ts('Amount Requested'),
+ 'description' => ts('Requested grant amount, in original currency (optional).'),
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_grant.amount_requested',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'amount_granted' => array(
+ ],
+ ],
+ 'amount_granted' => [
'name' => 'amount_granted',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount granted') ,
- 'description' => 'Granted amount, in default currency.',
- 'precision' => array(
+ 'title' => ts('Amount granted'),
+ 'description' => ts('Granted amount, in default currency.'),
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_granted',
- 'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Grant Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
- 'required' => true,
+ 'title' => ts('Grant Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
+ 'required' => TRUE,
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_grant.currency',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'rationale' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'rationale' => [
'name' => 'rationale',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Grant Rationale') ,
- 'description' => 'Grant rationale.',
+ 'title' => ts('Grant Rationale'),
+ 'description' => ts('Grant rationale.'),
'rows' => 4,
'cols' => 60,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_grant.rationale',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'grant_status_id' => array(
+ ],
+ ],
+ 'grant_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant Status') ,
- 'description' => 'Id of Grant status.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Grant Status'),
+ 'description' => ts('Id of Grant status.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_grant.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'grant_status',
'optionEditPath' => 'civicrm/admin/options/grant_status',
- )
- ) ,
- 'financial_type_id' => array(
+ ],
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_grant.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -492,10 +487,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -503,32 +499,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'grant', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'grant', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_grant_type_id' => array(
+ $indices = [
+ 'index_grant_type_id' => [
'name' => 'index_grant_type_id',
- 'field' => array(
+ 'field' => [
0 => 'grant_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_grant::0::grant_type_id',
- ) ,
- 'index_status_id' => array(
+ ],
+ 'index_status_id' => [
'name' => 'index_status_id',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_grant::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Grant/Form/Grant.php b/CRM/Grant/Form/Grant.php
index fd477e6848ac..de05a0c7cb8d 100644
--- a/CRM/Grant/Form/Grant.php
+++ b/CRM/Grant/Form/Grant.php
@@ -1,9 +1,9 @@
_id) {
$this->_grantType = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $this->_id, 'grant_type_id');
}
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
@@ -141,22 +141,11 @@ public function setDefaultValues() {
if (isset($defaults['amount_granted'])) {
$defaults['amount_granted'] = CRM_Utils_Money::format($defaults['amount_granted'], NULL, '%a');
}
-
- $dates = array(
- 'application_received_date',
- 'decision_date',
- 'money_transfer_date',
- 'grant_due_date',
- );
-
- foreach ($dates as $key) {
- if (!empty($defaults[$key])) {
- list($defaults[$key]) = CRM_Utils_Date::setDateDefaults($defaults[$key]);
- }
- }
}
else {
- list($defaults['application_received_date']) = CRM_Utils_Date::setDateDefaults();
+ if ($this->_contactID) {
+ $defaults['contact_id'] = $this->_contactID;
+ }
}
return $defaults;
@@ -170,36 +159,35 @@ public function setDefaultValues() {
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
return;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Grant_DAO_Grant');
- $this->addSelect('grant_type_id', array('onChange' => "CRM.buildCustomData( 'Grant', this.value );"), TRUE);
+ $this->addSelect('grant_type_id', ['onChange' => "CRM.buildCustomData( 'Grant', this.value );"], TRUE);
//need to assign custom data type and subtype to the template
$this->assign('customDataType', 'Grant');
$this->assign('customDataSubType', $this->_grantType);
$this->assign('entityID', $this->_id);
- $this->addSelect('status_id', array(), TRUE);
+ $this->addSelect('status_id', [], TRUE);
- $this->addDate('application_received_date', ts('Application Received'), FALSE, array('formatType' => 'custom'));
- $this->addDate('decision_date', ts('Grant Decision'), FALSE, array('formatType' => 'custom'));
- $this->addDate('money_transfer_date', ts('Money Transferred'), FALSE, array('formatType' => 'custom'));
- $this->addDate('grant_due_date', ts('Grant Report Due'), FALSE, array('formatType' => 'custom'));
+ $this->add('datepicker', 'application_received_date', ts('Application Received'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'decision_date', ts('Grant Decision'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'money_transfer_date', ts('Money Transferred'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'grant_due_date', ts('Grant Report Due'), [], FALSE, ['time' => FALSE]);
$this->addElement('checkbox', 'grant_report_received', ts('Grant Report Received?'), NULL);
$this->add('textarea', 'rationale', ts('Rationale'), $attributes['rationale']);
@@ -223,27 +211,27 @@ public function buildQuickForm() {
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc $uploadNames = $this->get( 'uploadNames' );
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'upload',
- 'name' => ts('Save and New'),
- 'js' => array('onclick' => "return verify( );"),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Applicant'), array('create' => TRUE), TRUE);
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save and New'),
+ 'js' => ['onclick' => "return verify( );"],
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $contactField = $this->addEntityRef('contact_id', ts('Applicant'), ['create' => TRUE], TRUE);
+ if ($this->_context != 'standalone') {
+ $contactField->freeze();
}
}
@@ -276,7 +264,7 @@ public function postProcess() {
}
$params['contact_id'] = $this->_contactID;
- $ids['note'] = array();
+ $ids['note'] = [];
if ($this->_noteId) {
$ids['note']['id'] = $this->_noteId;
}
diff --git a/CRM/Grant/Form/GrantView.php b/CRM/Grant/Form/GrantView.php
index 3c2522750e15..1f55a08c89e0 100644
--- a/CRM/Grant/Form/GrantView.php
+++ b/CRM/Grant/Form/GrantView.php
@@ -1,9 +1,9 @@
_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $context);
- $values = array();
+ $values = [];
$params['id'] = $this->_id;
CRM_Grant_BAO_Grant::retrieve($params, $values);
$grantType = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id');
$grantStatus = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'status_id');
$this->assign('grantType', $grantType[$values['grant_type_id']]);
$this->assign('grantStatus', $grantStatus[$values['status_id']]);
- $grantTokens = array(
+ $grantTokens = [
'amount_total',
'amount_requested',
'amount_granted',
@@ -67,7 +67,7 @@ public function preProcess() {
'decision_date',
'money_transfer_date',
'grant_due_date',
- );
+ ];
foreach ($grantTokens as $token) {
$this->assign($token, CRM_Utils_Array::value($token, $values));
@@ -93,7 +93,7 @@ public function preProcess() {
$title = CRM_Contact_BAO_Contact::displayName($values['contact_id']) . ' - ' . ts('Grant') . ': ' . CRM_Utils_Money::format($values['amount_total']) . ' (' . $grantType[$values['grant_type_id']] . ')';
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviGrant', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/grant',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -117,7 +117,7 @@ public function preProcess() {
$this->assign('attachment', $attachment);
$grantType = CRM_Core_DAO::getFieldValue("CRM_Grant_DAO_Grant", $this->_id, "grant_type_id");
- $groupTree = CRM_Core_BAO_CustomGroup::getTree("Grant", $this, $this->_id, 0, $grantType);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree("Grant", NULL, $this->_id, 0, $grantType);
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->_id);
$this->assign('id', $this->_id);
@@ -131,15 +131,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Search.php b/CRM/Grant/Form/Search.php
index 3a1400ad7565..588fcceda823 100644
--- a/CRM/Grant/Form/Search.php
+++ b/CRM/Grant/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
-
- // get user submitted values
- // get it from controller only if form has been submitted, else preProcess has set this
- if (!empty($_POST)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
- else {
- $this->_formValues = $this->get('formValues');
- }
-
- if (empty($this->_formValues)) {
- if (isset($this->_ssID)) {
- $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
- }
- }
+ $this->loadStandardSearchOptionsFromUrl();
+ $this->loadFormValues();
if ($this->_force) {
$this->postProcess();
@@ -154,9 +138,6 @@ public function preProcess() {
/**
* Build the form object.
- *
- *
- * @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
@@ -170,9 +151,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Grant_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Grant_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -319,4 +298,13 @@ public function getTitle() {
return ts('Find Grants');
}
+ /**
+ * Get metadata for fields being assigned by metadata.
+ *
+ * @return array
+ */
+ protected function getEntityMetadata() {
+ return CRM_Grant_BAO_Query::getSearchFieldMetadata();
+ }
+
}
diff --git a/CRM/Grant/Form/Task.php b/CRM/Grant/Form/Task.php
index c7700b34b94e..1cc6fddb24b6 100644
--- a/CRM/Grant/Form/Task.php
+++ b/CRM/Grant/Form/Task.php
@@ -1,9 +1,9 @@
_grantIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_grantIds = [];
- $values = $form->controller->exportValues('Search');
+ $values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
- $grantTasks = CRM_Grant_Task::tasks();
- $form->assign('taskName', $grantTasks[$form->_task]);
+ $tasks = CRM_Grant_Task::tasks();
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -124,7 +105,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_grantIds = $form->_componentIds = $ids;
//set the context for redirection for any task actions
- $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
+ $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
@@ -139,7 +120,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_grantIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_grantIds,
'civicrm_grant'
);
}
@@ -156,18 +137,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/Delete.php b/CRM/Grant/Form/Task/Delete.php
index 6c6eb1cd6709..59e8d822f7af 100644
--- a/CRM/Grant/Form/Task/Delete.php
+++ b/CRM/Grant/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count grants deleted.', 'count' => $deleted));
+ $msg = ts('%count grant deleted.', ['plural' => '%count grants deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Grant/Form/Task/Print.php b/CRM/Grant/Form/Task/Print.php
index dc4c429abb5d..9f962f129489 100644
--- a/CRM/Grant/Form/Task/Print.php
+++ b/CRM/Grant/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Grant List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Grant List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Grant/Form/Task/Result.php b/CRM/Grant/Form/Task/Result.php
index 099beb47f142..eb6086e47b00 100644
--- a/CRM/Grant/Form/Task/Result.php
+++ b/CRM/Grant/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/SearchTaskHookSample.php b/CRM/Grant/Form/Task/SearchTaskHookSample.php
index 86708453827d..a09dfa62132a 100644
--- a/CRM/Grant/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Grant/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_grantIds);
@@ -62,12 +62,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'decision_date' => $dao->decision_date,
'amount_requested' => $dao->amount_total,
'amount_granted' => $dao->amount_granted,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -78,14 +78,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/Update.php b/CRM/Grant/Form/Task/Update.php
index 552e7dc15fed..c1d9b4ad3784 100644
--- a/CRM/Grant/Form/Task/Update.php
+++ b/CRM/Grant/Form/Task/Update.php
@@ -1,9 +1,9 @@
addElement('select', 'status_id', ts('Grant Status'), array('' => '') + $grantStatus);
+ $this->addElement('select', 'status_id', ts('Grant Status'), ['' => ''] + $grantStatus);
$this->addElement('text', 'amount_granted', ts('Amount Granted'));
$this->addRule('amount_granted', ts('Please enter a valid amount.'), 'money');
- $this->addDate('decision_date', ts('Grant Decision'), FALSE, array('formatType' => 'custom'));
+ $this->add('datepicker', 'decision_date', ts('Grant Decision'), [], FALSE, ['time' => FALSE]);
- $this->assign('elements', array('status_id', 'amount_granted', 'decision_date'));
+ $this->assign('elements', ['status_id', 'amount_granted', 'decision_date']);
$this->assign('totalSelectedGrants', count($this->_grantIds));
$this->addDefaultButtons(ts('Update Grants'), 'done');
@@ -105,7 +105,7 @@ public function postProcess() {
}
}
- $status = ts('Updated Grant(s): %1 (Total Selected: %2)', array(1 => $updatedGrants, 2 => count($this->_grantIds)));
+ $status = ts('Updated Grant(s): %1 (Total Selected: %2)', [1 => $updatedGrants, 2 => count($this->_grantIds)]);
CRM_Core_Session::setStatus($status, '', 'info');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 'force=1&qfKey=' . $qfKey));
}
diff --git a/CRM/Grant/Info.php b/CRM/Grant/Info.php
index 5addd46e102c..7ae2788d9107 100644
--- a/CRM/Grant/Info.php
+++ b/CRM/Grant/Info.php
@@ -1,9 +1,9 @@
'CiviGrant',
'translatedName' => ts('CiviGrant'),
'title' => 'CiviCRM Grant Management Engine',
'path' => 'CRM_Grant_',
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* @param bool $getAllUnconditionally
@@ -67,20 +67,20 @@ public function getInfo() {
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviGrant' => array(
+ $permissions = [
+ 'access CiviGrant' => [
ts('access CiviGrant'),
ts('View all grants'),
- ),
- 'edit grants' => array(
+ ],
+ 'edit grants' => [
ts('edit grants'),
ts('Create and update grants'),
- ),
- 'delete in CiviGrant' => array(
+ ],
+ 'delete in CiviGrant' => [
ts('delete in CiviGrant'),
ts('Delete grants'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -114,11 +114,19 @@ public function getUserDashboardObject() {
* @return array
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Grants'),
'url' => 'grant',
- 'weight' => 50,
- );
+ 'weight' => 60,
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-money';
}
/**
@@ -126,10 +134,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Grants'),
'weight' => 50,
- );
+ ];
}
/**
@@ -148,14 +156,14 @@ public function creatNewShortcut(&$shortCuts) {
if (CRM_Core_Permission::check('access CiviGrant') &&
CRM_Core_Permission::check('edit grants')
) {
- $shortCuts = array_merge($shortCuts, array(
- array(
+ $shortCuts = array_merge($shortCuts, [
+ [
'path' => 'civicrm/grant/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-grant',
'title' => ts('Grant'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Page/DashBoard.php b/CRM/Grant/Page/DashBoard.php
index 0a6bb61fe885..b039a8f9954e 100644
--- a/CRM/Grant/Page/DashBoard.php
+++ b/CRM/Grant/Page/DashBoard.php
@@ -1,9 +1,9 @@
_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -151,7 +151,7 @@ public function run() {
}
public function setContext() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
$session = CRM_Core_Session::singleton();
@@ -177,7 +177,7 @@ public function setContext() {
break;
case 'edit':
- $url = CRM_utils_System::url('civicrm/contact/view/grant', 'reset=1&id=' . $this->_id . '&cid=' . $this->_contactId . '&action=view&context=grant&selectedChild=grant');
+ $url = CRM_Utils_System::url('civicrm/contact/view/grant', 'reset=1&id=' . $this->_id . '&cid=' . $this->_contactId . '&action=view&context=grant&selectedChild=grant');
break;
case 'grant':
diff --git a/CRM/Grant/Selector/Search.php b/CRM/Grant/Selector/Search.php
index 49e957623c19..1eebd8d32b6f 100644
--- a/CRM/Grant/Selector/Search.php
+++ b/CRM/Grant/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant' . $extraParams,
'title' => ts('View Grant'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Grant'),
- ),
- );
+ ],
+ ];
if ($cid) {
- $delLink = array(
- CRM_Core_Action::DELETE => array(
+ $delLink = [
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant' . $extraParams,
'title' => ts('Delete Grant'),
- ),
- );
+ ],
+ ];
self::$_links = self::$_links + $delLink;
}
}
@@ -279,10 +279,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
//CRM-4418 check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit grants')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -292,7 +292,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -306,11 +306,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['action'] = CRM_Core_Action::formLink(self::links($this->_key),
$mask,
- array(
+ [
'id' => $result->grant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'grant.selector.row',
@@ -348,54 +348,54 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Status'),
'sort' => 'grant_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Type'),
'sort' => 'grant_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Requested'),
'sort' => 'grant_amount_total',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Granted'),
'sort' => 'grant_amount_granted',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Application Received'),
'sort' => 'grant_application_received_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Report Received'),
'sort' => 'grant_report_received',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Money Transferred'),
'sort' => 'money_transfer_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
diff --git a/CRM/Grant/StateMachine/Search.php b/CRM/Grant/StateMachine/Search.php
index 2b387d63b0c5..6e5890336684 100644
--- a/CRM/Grant/StateMachine/Search.php
+++ b/CRM/Grant/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Grant_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -82,7 +82,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Grant/Task.php b/CRM/Grant/Task.php
index 290f52ab78f2..467853f627a6 100644
--- a/CRM/Grant/Task.php
+++ b/CRM/Grant/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete grants'),
'class' => 'CRM_Grant_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Grant_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export grants'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::UPDATE_GRANTS => [
'title' => ts('Update grants'),
'class' => 'CRM_Grant_Form_Task_Update',
'result' => FALSE,
- ),
- );
+ ],
+ ];
if (!CRM_Core_Permission::check('delete in CiviGrant')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
- CRM_Utils_Hook::searchTasks('grant', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit grants')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviGrant')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -154,14 +135,12 @@ public static function &permissionedTaskTitles($permission) {
*/
public static function getTask($value) {
self::tasks();
- if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+
+ if (!CRM_Utils_Array::value($value, self::$_tasks)) {
+ // make it the print task by default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Group/Controller.php b/CRM/Group/Controller.php
index b97e1030393e..8e3f05464afc 100644
--- a/CRM/Group/Controller.php
+++ b/CRM/Group/Controller.php
@@ -1,9 +1,9 @@
entityFields = [
+ 'title' => [
+ 'name' => 'title',
+ 'required' => TRUE,
+ ],
+ 'description' => ['name' => 'description'],
+ ];
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = '';
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'Group';
+ }
+
/**
* Set up variables to build the form.
*/
@@ -106,7 +137,12 @@ public function preProcess() {
if ($this->_action == CRM_Core_Action::DELETE) {
if (isset($this->_id)) {
$this->assign('title', $this->_title);
- $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+ try {
+ $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+ }
+ catch (CRM_Core_Exception $e) {
+ // If the group is borked the query might fail but delete should be possible.
+ }
CRM_Utils_System::setTitle(ts('Confirm Group Delete'));
}
if ($this->_groupValues['is_reserved'] == 1 && !CRM_Core_Permission::check('administer reserved groups')) {
@@ -160,7 +196,6 @@ public function preProcess() {
*/
public function setDefaultValues() {
$defaults = array();
-
if (isset($this->_id)) {
$defaults = $this->_groupValues;
if (!empty($defaults['group_type'])) {
@@ -177,6 +212,9 @@ public function setDefaultValues() {
CRM_Contact_BAO_GroupOrganization::retrieve($this->_id, $defaults);
}
}
+ else {
+ $defaults['is_active'] = 1;
+ }
if (!((CRM_Core_Permission::check('access CiviMail')) ||
(CRM_Mailing_Info::workflowEnabled() &&
@@ -206,19 +244,8 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- if ($this->_action == CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete Group'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ self::buildQuickEntityForm();
+ if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
@@ -227,15 +254,6 @@ public function buildQuickForm() {
$this->preventAjaxSubmit();
}
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'title', ts('Name') . ' ',
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'), TRUE
- );
-
- $this->add('textarea', 'description', ts('Description') . ' ',
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
- );
-
$groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
if (isset($this->_id) && !empty($this->_groupValues['saved_search_id'])) {
@@ -261,23 +279,11 @@ public function buildQuickForm() {
if (!CRM_Core_Permission::check('administer reserved groups')) {
$this->freeze('is_reserved');
}
+ $this->addElement('checkbox', 'is_active', ts('Is active?'));
//build custom data
CRM_Custom_Form_CustomData::buildQuickForm($this);
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ($this->_action == CRM_Core_Action::ADD) ? ts('Continue') : ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
$doParentCheck = FALSE;
if (CRM_Core_Permission::isMultisiteEnabled()) {
$doParentCheck = ($this->_id && CRM_Core_BAO_Domain::isDomainGroup($this->_id)) ? FALSE : TRUE;
@@ -356,7 +362,7 @@ public static function formRule($fields, $fileParams, $options) {
* Process the form when submitted.
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Core_DAO_Group');
+ CRM_Utils_System::flushCache();
$updateNestingCache = FALSE;
if ($this->_action & CRM_Core_Action::DELETE) {
@@ -367,9 +373,6 @@ public function postProcess() {
else {
// store the submitted values in an array
$params = $this->controller->exportValues($this->_name);
-
- $params['is_active'] = CRM_Utils_Array::value('is_active', $this->_groupValues, 1);
-
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
}
@@ -378,8 +381,13 @@ public function postProcess() {
$params['group_organization'] = $this->_groupOrganizationID;
}
- $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
+ // CRM-21431 If all group_type are unchecked, the change will not be saved otherwise.
+ if (!isset($params['group_type'])) {
+ $params['group_type'] = array();
+ }
+ $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
+ $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
$this->_id,
'Group'
@@ -448,7 +456,7 @@ public static function buildParentGroups(&$form) {
$potentialParentGroupIds = array_keys($groupNames);
}
- $parentGroupSelectValues = array('' => '- ' . ts('select group') . ' -');
+ $parentGroupSelectValues = array();
foreach ($potentialParentGroupIds as $potentialParentGroupId) {
if (array_key_exists($potentialParentGroupId, $groupNames)) {
$parentGroupSelectValues[$potentialParentGroupId] = $groupNames[$potentialParentGroupId];
@@ -462,7 +470,7 @@ public static function buildParentGroups(&$form) {
else {
$required = FALSE;
}
- $form->add('select', 'parents', ts('Add Parent'), $parentGroupSelectValues, $required, array('class' => 'crm-select2'));
+ $form->add('select', 'parents', ts('Add Parent'), $parentGroupSelectValues, $required, array('class' => 'crm-select2', 'multiple' => TRUE));
}
return $parentGroups;
diff --git a/CRM/Group/Form/Search.php b/CRM/Group/Form/Search.php
index 6922d218dfb6..8de0d8beaa58 100644
--- a/CRM/Group/Form/Search.php
+++ b/CRM/Group/Form/Search.php
@@ -1,9 +1,9 @@
add('select', 'visibility', ts('Visibility'),
- array('' => ts('- any visibility -')) + CRM_Core_SelectValues::ufVisibility(TRUE)
+ ['' => ts('- any visibility -')] + CRM_Core_SelectValues::ufVisibility(TRUE)
);
- $groupStatuses = array(ts('Enabled') => 1, ts('Disabled') => 2);
+ $groupStatuses = [ts('Enabled') => 1, ts('Disabled') => 2];
$this->addCheckBox('group_status',
ts('Status'),
$groupStatuses,
NULL, NULL, NULL, NULL, ' '
);
- $this->addButtons(array(
- array(
+ $componentModes = CRM_Contact_Form_Search::getModeSelect();
+ if (count($componentModes) > 1) {
+ $this->add('select',
+ 'component_mode',
+ ts('View Results As'),
+ $componentModes,
+ FALSE,
+ ['class' => 'crm-select2']
+ );
+ }
+
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
parent::buildQuickForm();
$this->assign('suppressForm', TRUE);
@@ -97,7 +108,7 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array('title', 'created_by', 'group_type', 'visibility', 'active_status', 'inactive_status');
+ $fields = ['title', 'created_by', 'group_type', 'visibility', 'active_status', 'inactive_status', 'component_mode'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
diff --git a/CRM/Group/Page/AJAX.php b/CRM/Group/Page/AJAX.php
index 9210ddbead21..5ccad88a887f 100644
--- a/CRM/Group/Page/AJAX.php
+++ b/CRM/Group/Page/AJAX.php
@@ -1,9 +1,9 @@
'String',
'created_by' => 'String',
'group_type' => 'String',
'visibility' => 'String',
+ 'component_mode' => 'String',
'status' => 'Integer',
'parentsOnly' => 'Integer',
'showOrgInfo' => 'Boolean',
// Ignore 'parent_id' as that case is handled above
- );
+ ];
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParams, $optionalParams);
diff --git a/CRM/Group/Page/Group.php b/CRM/Group/Page/Group.php
index c371fe56bc76..a4409c2e4905 100644
--- a/CRM/Group/Page/Group.php
+++ b/CRM/Group/Page/Group.php
@@ -1,9 +1,9 @@
_pages = array(
+ $this->_pages = [
'CRM_Group_Form_Edit' => NULL,
'CRM_Contact_Form_Search_Basic' => NULL,
'CRM_Contact_Form_Task_AddToGroup' => NULL,
'CRM_Contact_Form_Task_Result' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Import/DataSource.php b/CRM/Import/DataSource.php
index 9091e3f647a1..a9d837d59693 100644
--- a/CRM/Import/DataSource.php
+++ b/CRM/Import/DataSource.php
@@ -1,9 +1,9 @@
ts('Comma-Separated Values (CSV)'));
+ return ['title' => ts('Comma-Separated Values (CSV)')];
}
/**
@@ -74,10 +74,10 @@ public function buildQuickForm(&$form) {
$form->assign('uploadSize', $uploadSize);
$form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
$form->setMaxFileSize($uploadFileSize);
- $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(
- 1 => $uploadSize,
- 2 => $uploadFileSize,
- )), 'maxfilesize', $uploadFileSize);
+ $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [
+ 1 => $uploadSize,
+ 2 => $uploadFileSize,
+ ]), 'maxfilesize', $uploadFileSize);
$form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
$form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
@@ -131,7 +131,7 @@ private static function _CsvToTable(
$table = NULL,
$fieldSeparator = ','
) {
- $result = array();
+ $result = [];
$fd = fopen($file, 'r');
if (!$fd) {
CRM_Core_Error::fatal("Could not read $file");
@@ -192,7 +192,7 @@ private static function _CsvToTable(
}
}
else {
- $columns = array();
+ $columns = [];
foreach ($firstrow as $i => $_) {
$columns[] = "col_$i";
}
@@ -239,7 +239,7 @@ private static function _CsvToTable(
function($string) {
return trim($string, chr(0xC2) . chr(0xA0));
}, $row);
- $row = array_map(array('CRM_Core_DAO', 'escapeString'), $row);
+ $row = array_map(['CRM_Core_DAO', 'escapeString'], $row);
$sql .= "('" . implode("', '", $row) . "')";
$count++;
diff --git a/CRM/Import/DataSource/SQL.php b/CRM/Import/DataSource/SQL.php
index 44d8ba64cf7f..0017b5c55af3 100644
--- a/CRM/Import/DataSource/SQL.php
+++ b/CRM/Import/DataSource/SQL.php
@@ -1,9 +1,9 @@
ts('SQL Query'),
- 'permissions' => array('import SQL datasource'),
- );
+ 'permissions' => ['import SQL datasource'],
+ ];
}
/**
@@ -68,7 +68,7 @@ public function preProcess(&$form) {
public function buildQuickForm(&$form) {
$form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_SQL');
$form->add('textarea', 'sqlQuery', ts('Specify SQL Query'), 'rows=10 cols=45', TRUE);
- $form->addFormRule(array('CRM_Import_DataSource_SQL', 'formRule'), $form);
+ $form->addFormRule(['CRM_Import_DataSource_SQL', 'formRule'], $form);
}
/**
@@ -79,13 +79,13 @@ public function buildQuickForm(&$form) {
* @return array|bool
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
- // poor man's query validation (case-insensitive regex matching on word boundaries)
- $forbidden = array('ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema');
+ // Makeshift query validation (case-insensitive regex matching on word boundaries)
+ $forbidden = ['ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema'];
foreach ($forbidden as $pattern) {
if (preg_match("/\\b$pattern\\b/i", $fields['sqlQuery'])) {
- $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', array(1 => $pattern));
+ $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', [1 => $pattern]);
}
}
diff --git a/CRM/Import/Form/DataSource.php b/CRM/Import/Form/DataSource.php
index 2270e6b74823..ae577f0c519c 100644
--- a/CRM/Import/Form/DataSource.php
+++ b/CRM/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
$this->setMaxFileSize($uploadFileSize);
- $this->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(
+ $this->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [
1 => $uploadSize,
2 => $uploadFileSize,
- )), 'maxfilesize', $uploadFileSize);
+ ]), 'maxfilesize', $uploadFileSize);
$this->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
$this->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
$this->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
- $this->add('text', 'fieldSeparator', ts('Import Field Separator'), array('size' => 2), TRUE);
- $this->setDefaults(array('fieldSeparator' => $config->fieldSeparator));
+ $this->add('text', 'fieldSeparator', ts('Import Field Separator'), ['size' => 2], TRUE);
+ $this->setDefaults(['fieldSeparator' => $config->fieldSeparator]);
+ $mappingArray = CRM_Core_BAO_Mapping::getCreateMappingValues('Import ' . static::IMPORT_ENTITY);
- //get the saved mapping details
- $mappingArray = CRM_Core_BAO_Mapping::getMappings(CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import ' . static::IMPORT_ENTITY,
- 'name'
- ));
$this->assign('savedMapping', $mappingArray);
- $this->add('select', 'savedMapping', ts('Mapping Option'), array('' => ts('- select -')) + $mappingArray);
+ $this->add('select', 'savedMapping', ts('Mapping Option'), ['' => ts('- select -')] + $mappingArray);
if ($loadedMapping = $this->get('loadedMapping')) {
$this->assign('loadedMapping', $loadedMapping);
- $this->setDefaults(array('savedMapping' => $loadedMapping));
+ $this->setDefaults(['savedMapping' => $loadedMapping]);
}
//build date formats
CRM_Core_Form_Date::buildAllowedDateFormats($this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
/**
@@ -116,7 +111,7 @@ public function buildQuickForm() {
*/
protected function addContactTypeSelector() {
//contact types option
- $contactOptions = array();
+ $contactOptions = [];
if (CRM_Contact_BAO_ContactType::isActive('Individual')) {
$contactOptions[] = $this->createElement('radio',
NULL, NULL, ts('Individual'), CRM_Import_Parser::CONTACT_INDIVIDUAL
@@ -137,9 +132,9 @@ protected function addContactTypeSelector() {
ts('Contact Type')
);
- $this->setDefaults(array(
+ $this->setDefaults([
'contactType' => CRM_Import_Parser::CONTACT_INDIVIDUAL,
- ));
+ ]);
}
/**
@@ -172,7 +167,7 @@ protected function submitFileForMapping($parserClassName, $entity = NULL) {
$separator = $this->controller->exportValue($this->_name, 'fieldSeparator');
- $mapper = array();
+ $mapper = [];
$parser = new $parserClassName($mapper);
if ($entity) {
diff --git a/CRM/Import/Form/MapField.php b/CRM/Import/Form/MapField.php
index 08ca4fbd34e2..9a5a309a23bb 100644
--- a/CRM/Import/Form/MapField.php
+++ b/CRM/Import/Form/MapField.php
@@ -1,9 +1,9 @@
_dataValues);
@@ -153,4 +153,37 @@ public function defaultFromData(&$patterns, $index) {
return $best;
}
+ /**
+ * Add the saved mapping fields to the form.
+ *
+ * @param int|null $savedMappingID
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ protected function buildSavedMappingFields($savedMappingID) {
+ //to save the current mappings
+ if (!$savedMappingID) {
+ $saveDetailsName = ts('Save this field mapping');
+ $this->applyFilter('saveMappingName', 'trim');
+ $this->add('text', 'saveMappingName', ts('Name'));
+ $this->add('text', 'saveMappingDesc', ts('Description'));
+ }
+ else {
+ $savedMapping = $this->get('savedMapping');
+
+ $mappingName = (string) civicrm_api3('Mapping', 'getvalue', ['id' => $savedMappingID, 'return' => 'name']);
+ $this->set('loadedMapping', $savedMapping);
+ $this->assign('loadedMapping', $mappingName);
+ $this->assign('savedName', $mappingName);
+ $this->add('hidden', 'mappingId', $savedMappingID);
+
+ $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
+ $saveDetailsName = ts('Save as a new field mapping');
+ $this->add('text', 'saveMappingName', ts('Name'));
+ $this->add('text', 'saveMappingDesc', ts('Description'));
+ }
+
+ $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
+ }
+
}
diff --git a/CRM/Import/Form/Preview.php b/CRM/Import/Form/Preview.php
index 1ed08fda51ae..88810af0ba99 100644
--- a/CRM/Import/Form/Preview.php
+++ b/CRM/Import/Form/Preview.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'back',
'name' => ts('Previous'),
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Import Now'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
+ }
+
+ /**
+ * Set status url for ajax.
+ */
+ public function setStatusUrl() {
+ $statusID = $this->get('statusID');
+ if (!$statusID) {
+ $statusID = md5(uniqid(rand(), TRUE));
+ $this->set('statusID', $statusID);
+ }
+ $statusUrl = CRM_Utils_System::url('civicrm/ajax/status', "id={$statusID}", FALSE, NULL, FALSE);
+ $this->assign('statusUrl', $statusUrl);
}
}
diff --git a/CRM/Import/Form/Summary.php b/CRM/Import/Form/Summary.php
index 32639f8cb8a4..f24de6ebb9cf 100644
--- a/CRM/Import/Form/Summary.php
+++ b/CRM/Import/Form/Summary.php
@@ -1,9 +1,9 @@
ts('Done'),
'isDefault' => TRUE,
),
- )
- );
+ ));
}
/**
diff --git a/CRM/Import/ImportProcessor.php b/CRM/Import/ImportProcessor.php
new file mode 100644
index 000000000000..79ddc3b640e3
--- /dev/null
+++ b/CRM/Import/ImportProcessor.php
@@ -0,0 +1,570 @@
+formName;
+ }
+
+ /**
+ * @param string $formName
+ */
+ public function setFormName(string $formName) {
+ $this->formName = $formName;
+ }
+
+ /**
+ * @return array
+ */
+ public function getValidRelationships(): array {
+ if (!isset($this->validRelationships[$this->getContactType() . '_' . $this->getContactSubType()])) {
+ //Relationship importables
+ $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(
+ NULL, NULL, NULL, $this->getContactType(),
+ FALSE, 'label', TRUE, $this->getContactSubType()
+ );
+ asort($relations);
+ $this->setValidRelationships($relations);
+ }
+ return $this->validRelationships[$this->getContactType() . '_' . $this->getContactSubType()];
+ }
+
+ /**
+ * @param array $validRelationships
+ */
+ public function setValidRelationships(array $validRelationships) {
+ $this->validRelationships[$this->getContactType() . '_' . $this->getContactSubType()] = $validRelationships;
+ }
+
+ /**
+ * Get contact subtype for import.
+ *
+ * @return string
+ */
+ public function getContactSubType(): string {
+ return $this->contactSubType ?? '';
+ }
+
+ /**
+ * Set contact subtype for import.
+ *
+ * @param string $contactSubType
+ */
+ public function setContactSubType($contactSubType) {
+ $this->contactSubType = (string) $contactSubType;
+ }
+
+ /**
+ * Saved Mapping ID.
+ *
+ * @var int
+ */
+ protected $mappingID;
+
+ /**
+ * @return array
+ */
+ public function getMetadata(): array {
+ return $this->metadata;
+ }
+
+ /**
+ * Setting for metadata.
+ *
+ * We wrangle the label for custom fields to include the label since the
+ * metadata trait presents it in a more 'pure' form but the label is appended for importing.
+ *
+ * @param array $metadata
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function setMetadata(array $metadata) {
+ $fieldDetails = civicrm_api3('CustomField', 'get', [
+ 'return' => ['custom_group_id.title'],
+ 'options' => ['limit' => 0],
+ ])['values'];
+ foreach ($metadata as $index => $field) {
+ if (!empty($field['custom_field_id'])) {
+ // The 'label' format for import is custom group title :: custom name title
+ $metadata[$index]['name'] = $index;
+ $metadata[$index]['title'] .= ' :: ' . $fieldDetails[$field['custom_field_id']]['custom_group_id.title'];
+ }
+ }
+ $this->metadata = $metadata;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMappingID(): int {
+ return $this->mappingID;
+ }
+
+ /**
+ * @param int $mappingID
+ */
+ public function setMappingID(int $mappingID) {
+ $this->mappingID = $mappingID;
+ }
+
+ /**
+ * Get the contact type for the import.
+ *
+ * @return string
+ */
+ public function getContactType(): string {
+ return $this->contactType;
+ }
+
+ /**
+ * @param string $contactType
+ */
+ public function setContactType(string $contactType) {
+ $this->contactType = $contactType;
+ }
+
+ /**
+ * Set the contact type according to the constant.
+ *
+ * @param int $contactTypeKey
+ */
+ public function setContactTypeByConstant($contactTypeKey) {
+ $constantTypeMap = [
+ CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
+ CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
+ CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
+ ];
+ $this->contactType = $constantTypeMap[$contactTypeKey];
+ }
+
+ /**
+ * Get Mapping Fields.
+ *
+ * @return array
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getMappingFields(): array {
+ if (empty($this->mappingFields) && !empty($this->getMappingID())) {
+ $this->loadSavedMapping();
+ }
+ return $this->mappingFields;
+ }
+
+ /**
+ * Set mapping fields.
+ *
+ * We do a little cleanup here too.
+ *
+ * We ensure that column numbers are set and that the fields are ordered by them.
+ *
+ * This would mean the fields could be loaded unsorted.
+ *
+ * @param array $mappingFields
+ */
+ public function setMappingFields(array $mappingFields) {
+ $i = 0;
+ foreach ($mappingFields as &$mappingField) {
+ if (!isset($mappingField['column_number'])) {
+ $mappingField['column_number'] = $i;
+ }
+ if ($mappingField['column_number'] > $i) {
+ $i = $mappingField['column_number'];
+ }
+ $i++;
+ }
+ $this->mappingFields = $this->rekeyBySortedColumnNumbers($mappingFields);
+ }
+
+ /**
+ * Get the names of the mapped fields.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldNames() {
+ return CRM_Utils_Array::collect('name', $this->getMappingFields());
+ }
+
+ /**
+ * Get the field name for the given column.
+ *
+ * @param int $columnNumber
+ *
+ * @return string
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldName($columnNumber) {
+ return $this->getFieldNames()[$columnNumber];
+ }
+
+ /**
+ * Get the field name for the given column.
+ *
+ * @param int $columnNumber
+ *
+ * @return string
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getRelationshipKey($columnNumber) {
+ $field = $this->getMappingFields()[$columnNumber];
+ return empty($field['relationship_type_id']) ? NULL : $field['relationship_type_id'] . '_' . $field['relationship_direction'];
+ }
+
+ /**
+ * Get relationship key only if it is valid.
+ *
+ * @param int $columnNumber
+ *
+ * @return string|null
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getValidRelationshipKey($columnNumber) {
+ $key = $this->getRelationshipKey($columnNumber);
+ return $this->isValidRelationshipKey($key) ? $key : NULL;
+ }
+
+ /**
+ * Get the IM Provider ID.
+ *
+ * @param int $columnNumber
+ *
+ * @return int
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getIMProviderID($columnNumber) {
+ return $this->getMappingFields()[$columnNumber]['im_provider_id'] ?? NULL;
+ }
+
+ /**
+ * Get the Phone Type
+ *
+ * @param int $columnNumber
+ *
+ * @return int
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getPhoneTypeID($columnNumber) {
+ return $this->getMappingFields()[$columnNumber]['phone_type_id'] ?? NULL;
+ }
+
+ /**
+ * Get the Website Type
+ *
+ * @param int $columnNumber
+ *
+ * @return int
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getWebsiteTypeID($columnNumber) {
+ return $this->getMappingFields()[$columnNumber]['website_type_id'] ?? NULL;
+ }
+
+ /**
+ * Get the Location Type
+ *
+ * Returning 0 rather than null is historical.
+ *
+ * @param int $columnNumber
+ *
+ * @return int
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getLocationTypeID($columnNumber) {
+ return $this->getMappingFields()[$columnNumber]['location_type_id'] ?? 0;
+ }
+
+ /**
+ * Get the IM or Phone type.
+ *
+ * We have a field that would be the 'relevant' type - which could be either.
+ *
+ * @param int $columnNumber
+ *
+ * @return int
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getPhoneOrIMTypeID($columnNumber) {
+ return $this->getIMProviderID($columnNumber) ?? $this->getPhoneTypeID($columnNumber);
+ }
+
+ /**
+ * Get the location types of the mapped fields.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldLocationTypes() {
+ return CRM_Utils_Array::collect('location_type_id', $this->getMappingFields());
+ }
+
+ /**
+ * Get the phone types of the mapped fields.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldPhoneTypes() {
+ return CRM_Utils_Array::collect('phone_type_id', $this->getMappingFields());
+ }
+
+ /**
+ * Get the names of the im_provider fields.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldIMProviderTypes() {
+ return CRM_Utils_Array::collect('im_provider_id', $this->getMappingFields());
+ }
+
+ /**
+ * Get the names of the website fields.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getFieldWebsiteTypes() {
+ return CRM_Utils_Array::collect('im_provider_id', $this->getMappingFields());
+ }
+
+ /**
+ * Get an instance of the importer object.
+ *
+ * @return CRM_Contact_Import_Parser_Contact
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getImporterObject() {
+ $importer = new CRM_Contact_Import_Parser_Contact(
+ $this->getFieldNames(),
+ $this->getFieldLocationTypes(),
+ $this->getFieldPhoneTypes(),
+ $this->getFieldIMProviderTypes(),
+ // @todo - figure out related mappings.
+ // $mapperRelated = [], $mapperRelatedContactType = [], $mapperRelatedContactDetails = [], $mapperRelatedContactLocType = [], $mapperRelatedContactPhoneType = [], $mapperRelatedContactImProvider = [],
+ [],
+ [],
+ [],
+ [],
+ [],
+ [],
+ $this->getFieldWebsiteTypes()
+ // $mapperRelatedContactWebsiteType = []
+ );
+ $importer->init();
+ $importer->_contactType = $this->getContactType();
+ return $importer;
+ }
+
+ /**
+ * Load the mapping from the datbase into the format that would be received from the UI.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ protected function loadSavedMapping() {
+ $fields = civicrm_api3('MappingField', 'get', [
+ 'mapping_id' => $this->getMappingID(),
+ 'options' => ['limit' => 0],
+ ])['values'];
+ foreach ($fields as $index => $field) {
+ // Fix up the fact that for lost reasons we save by label not name.
+ $fields[$index]['label'] = $field['name'];
+ if (empty($field['relationship_type_id'])) {
+ $fields[$index]['name'] = $this->getNameFromLabel($field['name']);
+ }
+ else {
+ // Honour legacy chaos factor.
+ if ($field['name'] === ts('- do not import -')) {
+ // This is why we save names not labels people....
+ $field['name'] = 'do_not_import';
+ }
+ $fields[$index]['name'] = strtolower(str_replace(" ", "_", $field['name']));
+ // fix for edge cases, CRM-4954
+ if ($fields[$index]['name'] === 'image_url') {
+ $fields[$index]['name'] = str_replace('url', 'URL', $fields[$index]['name']);
+ }
+ }
+ $fieldSpec = $this->getMetadata()[$fields[$index]['name']];
+ if (empty($field['location_type_id']) && !empty($fieldSpec['hasLocationType'])) {
+ $fields[$index]['location_type_id'] = 'Primary';
+ }
+ }
+ $this->mappingFields = $this->rekeyBySortedColumnNumbers($fields);
+ }
+
+ /**
+ * Get the titles from metadata.
+ */
+ public function getMetadataTitles() {
+ if (empty($this->metadataByTitle)) {
+ $this->metadataByTitle = CRM_Utils_Array::collect('title', $this->getMetadata());
+ }
+ return $this->metadataByTitle;
+ }
+
+ /**
+ * Rekey the array by the column_number.
+ *
+ * @param array $mappingFields
+ *
+ * @return array
+ */
+ protected function rekeyBySortedColumnNumbers(array $mappingFields) {
+ $this->mappingFields = CRM_Utils_Array::rekey($mappingFields, 'column_number');
+ ksort($this->mappingFields);
+ return $this->mappingFields;
+ }
+
+ /**
+ * Get the field name from the label.
+ *
+ * @param string $label
+ *
+ * @return string
+ */
+ protected function getNameFromLabel($label) {
+ $titleMap = array_flip($this->getMetadataTitles());
+ return $titleMap[$label] ?? '';
+ }
+
+ /**
+ * Validate the key against the relationships available for the contatct type & subtype.
+ *
+ * @param string $key
+ *
+ * @return bool
+ */
+ protected function isValidRelationshipKey($key) {
+ return !empty($this->getValidRelationships()[$key]) ? TRUE : FALSE;
+ }
+
+ /**
+ * Get the relevant js for quickform.
+ *
+ * @param int $column
+ *
+ * @return string
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getQuickFormJSForField($column) {
+ $columnNumbersToHide = [];
+ if ($this->getFieldName($column) === 'do_not_import') {
+ $columnNumbersToHide = [1, 2, 3];
+ }
+ elseif ($this->getRelationshipKey($column)) {
+ if (!$this->getWebsiteTypeID($column) && !$this->getLocationTypeID($column)) {
+ $columnNumbersToHide[] = 2;
+ }
+ if (!$this->getFieldName($column)) {
+ $columnNumbersToHide[] = 1;
+ }
+ if (!$this->getPhoneOrIMTypeID($column)) {
+ $columnNumbersToHide[] = 3;
+ }
+ }
+ else {
+ if (!$this->getLocationTypeID($column) && !$this->getWebsiteTypeID($column)) {
+ $columnNumbersToHide[] = 1;
+ }
+ if (!$this->getPhoneOrIMTypeID($column)) {
+ $columnNumbersToHide[] = 2;
+ }
+ $columnNumbersToHide[] = 3;
+ }
+
+ $jsClauses = [];
+ foreach ($columnNumbersToHide as $columnNumber) {
+ $jsClauses[] = $this->getFormName() . "['mapper[$column][" . $columnNumber . "]'].style.display = 'none';";
+ }
+ return empty($jsClauses) ? '' : implode("\n", $jsClauses) . "\n";
+ }
+
+ /**
+ * Get the defaults for the column from the saved mapping.
+ *
+ * @param int $column
+ *
+ * @return array
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getSavedQuickformDefaultsForColumn($column) {
+ if ($this->getFieldName($column) === 'do_not_import') {
+ return [];
+ }
+ if ($this->getValidRelationshipKey($column)) {
+ if ($this->getWebsiteTypeID($column)) {
+ return [$this->getValidRelationshipKey($column), $this->getFieldName($column), $this->getWebsiteTypeID($column)];
+ }
+ return [$this->getValidRelationshipKey($column), $this->getFieldName($column), $this->getLocationTypeID($column), $this->getPhoneOrIMTypeID($column)];
+ }
+ if ($this->getWebsiteTypeID($column)) {
+ return [$this->getFieldName($column), $this->getWebsiteTypeID($column)];
+ }
+ return [(string) $this->getFieldName($column), $this->getLocationTypeID($column), $this->getPhoneOrIMTypeID($column)];
+ }
+
+}
diff --git a/CRM/Import/Parser.php b/CRM/Import/Parser.php
index 7791b129a9ad..3766625e71da 100644
--- a/CRM/Import/Parser.php
+++ b/CRM/Import/Parser.php
@@ -1,9 +1,9 @@
importableFieldsMetadata;
+ }
+
+ /**
+ * Set metadata for all importable fields in std getfields style format.
+ * @param array $importableFieldsMetadata
+ */
+ public function setImportableFieldsMetadata(array $importableFieldsMetadata) {
+ $this->importableFieldsMetadata = $importableFieldsMetadata;
+ }
+
/**
* Array of the fields that are actually part of the import process
* the position in the array also dictates their position in the import
@@ -192,7 +225,6 @@ abstract class CRM_Import_Parser {
*/
public function __construct() {
$this->_maxLinesToProcess = 0;
- $this->_maxErrorCount = self::MAX_ERRORS;
}
/**
@@ -279,7 +311,7 @@ public function setActiveFieldValues($elements, &$erroneousField) {
* (reference) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -292,11 +324,66 @@ public function &getActiveFieldParams() {
return $params;
}
+ /**
+ * Add progress bar to the import process. Calculates time remaining, status etc.
+ *
+ * @param $statusID
+ * status id of the import process saved in $config->uploadDir.
+ * @param bool $startImport
+ * True when progress bar is to be initiated.
+ * @param $startTimestamp
+ * Initial timstamp when the import was started.
+ * @param $prevTimestamp
+ * Previous timestamp when this function was last called.
+ * @param $totalRowCount
+ * Total number of rows in the import file.
+ *
+ * @return NULL|$currTimestamp
+ */
+ public function progressImport($statusID, $startImport = TRUE, $startTimestamp = NULL, $prevTimestamp = NULL, $totalRowCount = NULL) {
+ $config = CRM_Core_Config::singleton();
+ $statusFile = "{$config->uploadDir}status_{$statusID}.txt";
+
+ if ($startImport) {
+ $status = "
Clicks: " .
CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0);
- $actionLinks = array(
- CRM_Core_Action::VIEW => array(
+ $actionLinks = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/mailing/view',
'qs' => "reset=1&id=%%mkey%%",
'title' => ts('View Mailing'),
'class' => 'crm-popup',
- ),
- CRM_Core_Action::BROWSE => array(
+ ],
+ CRM_Core_Action::BROWSE => [
'name' => ts('Mailing Report'),
'url' => 'civicrm/mailing/report',
'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
'title' => ts('View Mailing Report'),
- ),
- );
+ ],
+ ];
$mailingKey = $values['mailing_id'];
if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
@@ -3097,11 +2935,11 @@ public static function getContactMailingSelector(&$params) {
$mailing['links'] = CRM_Core_Action::formLink(
$actionLinks,
NULL,
- array(
+ [
'mid' => $values['mailing_id'],
'cid' => $params['contact_id'],
'mkey' => $mailingKey,
- ),
+ ],
ts('more'),
FALSE,
'mailing.contact.action',
@@ -3112,7 +2950,7 @@ public static function getContactMailingSelector(&$params) {
array_push($contactMailings, $mailing);
}
- $contactMailingsDT = array();
+ $contactMailingsDT = [];
$contactMailingsDT['data'] = $contactMailings;
$contactMailingsDT['recordsTotal'] = $params['total'];
$contactMailingsDT['recordsFiltered'] = $params['total'];
@@ -3129,7 +2967,7 @@ public static function getContactMailingSelector(&$params) {
* Array of mailings for a contact
*
*/
- static public function getContactMailings(&$params) {
+ public static function getContactMailings(&$params) {
$params['version'] = 3;
$params['offset'] = ($params['page'] - 1) * $params['rp'];
$params['limit'] = $params['rp'];
@@ -3148,7 +2986,7 @@ static public function getContactMailings(&$params) {
* count of mailings for a contact
*
*/
- static public function getContactMailingsCount(&$params) {
+ public static function getContactMailingsCount(&$params) {
$params['version'] = 3;
return civicrm_api('MailingContact', 'getcount', $params);
}
@@ -3162,27 +3000,40 @@ static public function getContactMailingsCount(&$params) {
*/
public static function getWorkflowFieldPerms() {
$fieldNames = array_keys(CRM_Mailing_DAO_Mailing::fields());
- $fieldPerms = array();
+ $fieldPerms = [];
foreach ($fieldNames as $fieldName) {
if ($fieldName == 'id') {
- $fieldPerms[$fieldName] = array(
- array('access CiviMail', 'schedule mailings', 'approve mailings', 'create mailings'), // OR
- );
- }
- elseif (in_array($fieldName, array('scheduled_date', 'scheduled_id'))) {
- $fieldPerms[$fieldName] = array(
- array('access CiviMail', 'schedule mailings'), // OR
- );
- }
- elseif (in_array($fieldName, array('approval_date', 'approver_id', 'approval_status_id', 'approval_note'))) {
- $fieldPerms[$fieldName] = array(
- array('access CiviMail', 'approve mailings'), // OR
- );
+ $fieldPerms[$fieldName] = [
+ // OR
+ [
+ 'access CiviMail',
+ 'schedule mailings',
+ 'approve mailings',
+ ],
+ ];
+ }
+ elseif (in_array($fieldName, ['scheduled_date', 'scheduled_id'])) {
+ $fieldPerms[$fieldName] = [
+ // OR
+ ['access CiviMail', 'schedule mailings'],
+ ];
+ }
+ elseif (in_array($fieldName, [
+ 'approval_date',
+ 'approver_id',
+ 'approval_status_id',
+ 'approval_note',
+ ])) {
+ $fieldPerms[$fieldName] = [
+ // OR
+ ['access CiviMail', 'approve mailings'],
+ ];
}
else {
- $fieldPerms[$fieldName] = array(
- array('access CiviMail', 'create mailings'), // OR
- );
+ $fieldPerms[$fieldName] = [
+ // OR
+ ['access CiviMail', 'create mailings'],
+ ];
}
}
return $fieldPerms;
@@ -3194,10 +3045,10 @@ public static function getWorkflowFieldPerms() {
* @return array
*/
public static function mailingGroupEntityTables() {
- return array(
+ return [
CRM_Contact_BAO_Group::getTableName() => 'Group',
CRM_Mailing_BAO_Mailing::getTableName() => 'Mailing',
- );
+ ];
}
/**
@@ -3209,8 +3060,18 @@ public static function mailingGroupEntityTables() {
* @return string
*/
public static function getPublicViewUrl($id, $absolute = TRUE) {
- if ((civicrm_api3('Mailing', 'getvalue', array('id' => $id, 'return' => 'visibility'))) === 'Public Pages') {
- return CRM_Utils_System::url('civicrm/mailing/view', array('id' => $id), $absolute, NULL, TRUE, TRUE);
+ if ((civicrm_api3('Mailing', 'getvalue', [
+ 'id' => $id,
+ 'return' => 'visibility',
+ ])) === 'Public Pages') {
+
+ // if hash setting is on then we change the public url into a hash
+ $hash = CRM_Mailing_BAO_Mailing::getMailingHash($id);
+ if (!empty($hash)) {
+ $id = $hash;
+ }
+
+ return CRM_Utils_System::url('civicrm/mailing/view', ['id' => $id], $absolute, NULL, TRUE, TRUE);
}
}
@@ -3226,16 +3087,16 @@ public static function getPublicViewUrl($id, $absolute = TRUE) {
*/
public static function getTemplateTypes() {
if (!isset(Civi::$statics[__CLASS__]['templateTypes'])) {
- $types = array();
- $types[] = array(
+ $types = [];
+ $types[] = [
'name' => 'traditional',
'editorUrl' => CRM_Mailing_Info::workflowEnabled() ? '~/crmMailing/EditMailingCtrl/workflow.html' : '~/crmMailing/EditMailingCtrl/2step.html',
'weight' => 0,
- );
+ ];
CRM_Utils_Hook::mailingTemplateTypes($types);
- $defaults = array('weight' => 0);
+ $defaults = ['weight' => 0];
foreach (array_keys($types) as $typeName) {
$types[$typeName] = array_merge($defaults, $types[$typeName]);
}
@@ -3259,7 +3120,7 @@ public static function getTemplateTypes() {
* Array(string $name => string $label).
*/
public static function getTemplateTypeNames() {
- $r = array();
+ $r = [];
foreach (self::getTemplateTypes() as $type) {
$r[$type['name']] = $type['name'];
}
diff --git a/CRM/Mailing/BAO/MailingAB.php b/CRM/Mailing/BAO/MailingAB.php
index 21a80ada5554..2ff81ed5e92c 100644
--- a/CRM/Mailing/BAO/MailingAB.php
+++ b/CRM/Mailing/BAO/MailingAB.php
@@ -1,9 +1,9 @@
id = $id;
if ($dao->find(TRUE)) {
- $mailing_ids = array($dao->mailing_id_a, $dao->mailing_id_b, $dao->mailing_id_c);
+ $mailing_ids = [$dao->mailing_id_a, $dao->mailing_id_b, $dao->mailing_id_c];
$dao->delete();
foreach ($mailing_ids as $mailing_id) {
if ($mailing_id) {
@@ -147,16 +146,16 @@ public static function del($id) {
* @param CRM_Mailing_DAO_MailingAB $dao
*/
public static function distributeRecipients(CRM_Mailing_DAO_MailingAB $dao) {
- CRM_Mailing_BAO_Mailing::getRecipients($dao->mailing_id_a, $dao->mailing_id_a, TRUE);
+ CRM_Mailing_BAO_Mailing::getRecipients($dao->mailing_id_a);
//calculate total number of random recipients for mail C from group_percentage selected
$totalCount = CRM_Mailing_BAO_Recipients::mailingSize($dao->mailing_id_a);
$totalSelected = max(1, round(($totalCount * $dao->group_percentage) / 100));
- CRM_Mailing_BAO_Recipients::reassign($dao->mailing_id_a, array(
+ CRM_Mailing_BAO_Recipients::reassign($dao->mailing_id_a, [
$dao->mailing_id_b => (2 * $totalSelected <= $totalCount) ? $totalSelected : $totalCount - $totalSelected,
$dao->mailing_id_c => max(0, $totalCount - $totalSelected - $totalSelected),
- ));
+ ]);
}
@@ -174,7 +173,7 @@ public static function getABTest($mailingID) {
OR ab.mailing_id_b = %1
OR ab.mailing_id_c = %1)
GROUP BY ab.id";
- $params = array(1 => array($mailingID, 'Integer'));
+ $params = [1 => [$mailingID, 'Integer']];
$abTest = CRM_Core_DAO::executeQuery($query, $params);
$abTest->fetch();
return $abTest;
diff --git a/CRM/Mailing/BAO/MailingComponent.php b/CRM/Mailing/BAO/MailingComponent.php
new file mode 100644
index 000000000000..2fa8b553181d
--- /dev/null
+++ b/CRM/Mailing/BAO/MailingComponent.php
@@ -0,0 +1,114 @@
+copyValues($params);
+ if ($component->find(TRUE)) {
+ CRM_Core_DAO::storeValues($component, $defaults);
+ return $component;
+ }
+ return NULL;
+ }
+
+ /**
+ * Update the is_active flag in the db.
+ *
+ * @param int $id
+ * Id of the database record.
+ * @param bool $is_active
+ * Value we want to set the is_active field.
+ *
+ * @return bool
+ * true if we found and updated the object, else false
+ */
+ public static function setIsActive($id, $is_active) {
+ return CRM_Core_DAO::setFieldValue('CRM_Mailing_DAO_MailingComponent', $id, 'is_active', $is_active);
+ }
+
+ /**
+ * Create and Update mailing component.
+ *
+ * @param array $params
+ * (reference ) an assoc array of name/value pairs.
+ * @param array $ids
+ * (deprecated) the array that holds all the db ids.
+ *
+ * @return CRM_Mailing_BAO_MailingComponent
+ */
+ public static function add(&$params, $ids = []) {
+ $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
+ $component = new CRM_Mailing_BAO_MailingComponent();
+ if ($id) {
+ $component->id = $id;
+ $component->find(TRUE);
+ }
+
+ $component->copyValues($params);
+ if (empty($id) && empty($params['body_text'])) {
+ $component->body_text = CRM_Utils_String::htmlToText(CRM_Utils_Array::value('body_html', $params));
+ }
+
+ if ($component->is_default) {
+ if (!empty($id)) {
+ $sql = 'UPDATE civicrm_mailing_component SET is_default = 0 WHERE component_type = %1 AND id <> %2';
+ $sqlParams = [
+ 1 => [$component->component_type, 'String'],
+ 2 => [$id, 'Positive'],
+ ];
+ }
+ else {
+ $sql = 'UPDATE civicrm_mailing_component SET is_default = 0 WHERE component_type = %1';
+ $sqlParams = [
+ 1 => [$component->component_type, 'String'],
+ ];
+ }
+ CRM_Core_DAO::executeQuery($sql, $sqlParams);
+ }
+
+ $component->save();
+ return $component;
+ }
+
+}
diff --git a/CRM/Mailing/BAO/MailingJob.php b/CRM/Mailing/BAO/MailingJob.php
index 49d3fc5989d6..58b58e4170c3 100644
--- a/CRM/Mailing/BAO/MailingJob.php
+++ b/CRM/Mailing/BAO/MailingJob.php
@@ -1,9 +1,9 @@
mailing_id = $params['mailing_id'];
- $job->status = $params['status'];
- $job->scheduled_date = $params['scheduled_date'];
- $job->is_test = $params['is_test'];
- $job->save();
- $mailing = new CRM_Mailing_BAO_Mailing();
- $mailing->id = $params['mailing_id'];
- if ($mailing->id && $mailing->find(TRUE)) {
- $mailing->getRecipients($job->id, $params['mailing_id'], TRUE, $mailing->dedupe_email);
- return $job;
- }
- else {
+ public static function create($params) {
+ if (empty($params['id']) && empty($params['mailing_id'])) {
throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
}
+ $op = empty($params['id']) ? 'create' : 'edit';
+ CRM_Utils_Hook::pre($op, 'MailingJob', CRM_Utils_Array::value('id', $params), $params);
+
+ $jobDAO = new CRM_Mailing_BAO_MailingJob();
+ $jobDAO->copyValues($params, TRUE);
+ $jobDAO->save();
+ if (!empty($params['mailing_id']) && empty('is_calling_function_updated_to_reflect_deprecation')) {
+ CRM_Mailing_BAO_Mailing::getRecipients($params['mailing_id']);
+ }
+ CRM_Utils_Hook::post($op, 'MailingJob', $jobDAO->id, $jobDAO);
+ return $jobDAO;
}
/**
@@ -91,7 +90,6 @@ static public function create($params) {
public static function runJobs($testParams = NULL, $mode = NULL) {
$job = new CRM_Mailing_BAO_MailingJob();
- $config = CRM_Core_Config::singleton();
$jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
$mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
$mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
@@ -175,12 +173,12 @@ public static function runJobs($testParams = NULL, $mode = NULL) {
// get the parent ID, and limit and offset
$job->queue($testParams);
- // Mark up the starting time
- $saveJob = new CRM_Mailing_DAO_MailingJob();
- $saveJob->id = $job->id;
- $saveJob->start_date = date('YmdHis');
- $saveJob->status = 'Running';
- $saveJob->save();
+ // Update to show job has started.
+ self::create([
+ 'id' => $job->id,
+ 'start_date' => date('YmdHis'),
+ 'status' => 'Running',
+ ]);
$transaction->commit();
}
@@ -190,12 +188,12 @@ public static function runJobs($testParams = NULL, $mode = NULL) {
$mailer = \Civi::service('pear_mail');
}
elseif ($mode == 'sms') {
- $mailer = CRM_SMS_Provider::singleton(array('mailing_id' => $job->mailing_id));
+ $mailer = CRM_SMS_Provider::singleton(['mailing_id' => $job->mailing_id]);
}
// Compose and deliver each child job
if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
- $isComplete = Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER, array($job, $mailer, $testParams));
+ $isComplete = Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER, [$job, $mailer, $testParams]);
}
else {
$isComplete = $job->deliver($mailer, $testParams);
@@ -208,13 +206,7 @@ public static function runJobs($testParams = NULL, $mode = NULL) {
// Finish the job.
$transaction = new CRM_Core_Transaction();
-
- $saveJob = new CRM_Mailing_DAO_MailingJob();
- $saveJob->id = $job->id;
- $saveJob->end_date = date('YmdHis');
- $saveJob->status = 'Complete';
- $saveJob->save();
-
+ self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
$transaction->commit();
// don't mark the mailing as complete
@@ -281,7 +273,7 @@ public static function runJobs_post($mode = NULL) {
AND j.job_type = 'child'
AND j.parent_id = %1
AND j.status <> 'Complete'";
- $params = array(1 => array($job->id, 'Integer'));
+ $params = [1 => [$job->id, 'Integer']];
$anyChildLeft = CRM_Core_DAO::singleValueQuery($child_job_sql, $params);
@@ -309,7 +301,6 @@ public static function runJobs_post($mode = NULL) {
}
}
-
/**
* before we run jobs, we need to split the jobs
* @param int $offset
@@ -377,17 +368,12 @@ public static function runJobs_pre($offset = 200, $mode = NULL) {
continue;
}
- $job->split_job($offset);
-
- // update the status of the parent job
$transaction = new CRM_Core_Transaction();
- $saveJob = new CRM_Mailing_DAO_MailingJob();
- $saveJob->id = $job->id;
- $saveJob->start_date = date('YmdHis');
- $saveJob->status = 'Running';
- $saveJob->save();
+ $job->split_job($offset);
+ // Update the status of the parent job
+ self::create(['id' => $job->id, 'start_date' => date('YmdHis'), 'status' => 'Running']);
$transaction->commit();
// Release the job lock
@@ -412,15 +398,15 @@ public function split_job($offset = 200) {
(`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
VALUES (%1, %2, %3, %4, %5, %6, %7)
";
- $params = array(
- 1 => array($this->mailing_id, 'Integer'),
- 2 => array($this->scheduled_date, 'String'),
- 3 => array('Scheduled', 'String'),
- 4 => array('child', 'String'),
- 5 => array($this->id, 'Integer'),
- 6 => array(0, 'Integer'),
- 7 => array($recipient_count, 'Integer'),
- );
+ $params = [
+ 1 => [$this->mailing_id, 'Integer'],
+ 2 => [$this->scheduled_date, 'String'],
+ 3 => ['Scheduled', 'String'],
+ 4 => ['child', 'String'],
+ 5 => [$this->id, 'Integer'],
+ 6 => [0, 'Integer'],
+ 7 => [$recipient_count, 'Integer'],
+ ];
// create one child job if the mailing size is less than the offset
// probably use a CRM_Mailing_DAO_MailingJob( );
@@ -431,12 +417,15 @@ public function split_job($offset = 200) {
}
else {
// Creating 'child jobs'
- for ($i = 0; $i < $recipient_count; $i = $i + $offset) {
+ $scheduled_unixtime = strtotime($this->scheduled_date);
+ for ($i = 0, $s = 0; $i < $recipient_count; $i = $i + $offset, $s++) {
+ $params[2][0] = date('Y-m-d H:i:s', $scheduled_unixtime + $s);
$params[6][0] = $i;
$params[7][0] = $offset;
CRM_Core_DAO::executeQuery($sql, $params);
}
}
+
}
/**
@@ -457,7 +446,7 @@ public function queue($testParams = NULL) {
// INSERT INTO ... SELECT FROM ..
// the thing we need to figure out is how to generate the hash automatically
$now = time();
- $params = array();
+ $params = [];
$count = 0;
while ($recipients->fetch()) {
// CRM-18543: there are situations when both the email and phone are null.
@@ -473,17 +462,17 @@ public function queue($testParams = NULL) {
$recipients->phone_id = "null";
}
- $params[] = array(
+ $params[] = [
$this->id,
$recipients->email_id,
$recipients->contact_id,
$recipients->phone_id,
- );
+ ];
$count++;
if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
$count = 0;
- $params = array();
+ $params = [];
}
}
@@ -496,10 +485,13 @@ public function queue($testParams = NULL) {
/**
* Send the mailing.
*
+ * @deprecated
+ * This is used by CiviMail but will be made redundant by FlexMailer.
* @param object $mailer
* A Mail object to send the messages.
*
* @param array $testParams
+ * @return bool
*/
public function deliver(&$mailer, $testParams = NULL) {
if (\Civi::settings()->get('experimentalFlexMailerEngine')) {
@@ -509,7 +501,6 @@ public function deliver(&$mailer, $testParams = NULL) {
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->id = $this->mailing_id;
$mailing->find(TRUE);
- $mailing->free();
$config = NULL;
@@ -517,12 +508,12 @@ public function deliver(&$mailer, $testParams = NULL) {
$config = CRM_Core_Config::singleton();
}
- if (property_exists($mailing, 'language') && $mailing->language && $mailing->language != 'en_US') {
+ if (property_exists($mailing, 'language') && $mailing->language && $mailing->language != CRM_Core_I18n::getLocale()) {
$swapLang = CRM_Utils_AutoClean::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language);
}
$job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
- $fields = array();
+ $fields = [];
if (!empty($testParams)) {
$mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
@@ -550,30 +541,26 @@ public function deliver(&$mailer, $testParams = NULL) {
if (!empty($fields)) {
$this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
}
- $eq->free();
return FALSE;
}
self::$mailsProcessed++;
- $fields[] = array(
+ $fields[] = [
'id' => $eq->id,
'hash' => $eq->hash,
'contact_id' => $eq->contact_id,
'email' => $eq->email,
'phone' => $eq->phone,
- );
+ ];
if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
$isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
if (!$isDelivered) {
- $eq->free();
return $isDelivered;
}
- $fields = array();
+ $fields = [];
}
}
- $eq->free();
-
if (!empty($fields)) {
$isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
}
@@ -581,6 +568,8 @@ public function deliver(&$mailer, $testParams = NULL) {
}
/**
+ * @deprecated
+ * This is used by CiviMail but will be made redundant by FlexMailer.
* @param array $fields
* List of intended recipients.
* Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
@@ -601,14 +590,17 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
// get the return properties
$returnProperties = $mailing->getReturnProperties();
- $params = $targetParams = $deliveredParams = array();
+ $params = $targetParams = $deliveredParams = [];
$count = 0;
+ $retryGroup = FALSE;
// CRM-15702: Sending bulk sms to contacts without e-mail address fails.
// Solution is to skip checking for on hold
- $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
+ //do include a statement to check wether e-mail address is on hold
+ $skipOnHold = TRUE;
if ($mailing->sms_provider_id) {
- $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
+ //do not include a statement to check wether e-mail address is on hold
+ $skipOnHold = FALSE;
}
foreach ($fields as $key => $field) {
@@ -628,7 +620,7 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
foreach ($fields as $key => $field) {
$contactID = $field['contact_id'];
if (!array_key_exists($contactID, $details[0])) {
- $details[0][$contactID] = array();
+ $details[0][$contactID] = [];
}
// Compose the mailing.
@@ -653,11 +645,11 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
// Send the mailing.
- $body = &$message->get();
- $headers = &$message->headers();
+ $body = $message->get();
+ $headers = $message->headers();
if ($mailing->sms_provider_id) {
- $provider = CRM_SMS_Provider::singleton(array('mailing_id' => $mailing->id));
+ $provider = CRM_SMS_Provider::singleton(['mailing_id' => $mailing->id]);
$body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
$headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
}
@@ -680,18 +672,17 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) {
// CRM-9191
$message = $result->getMessage();
- if (
- strpos($message, 'Failed to write to socket') !== FALSE ||
- strpos($message, 'Failed to set sender') !== FALSE
- ) {
+ if ($this->isTemporaryError($message)) {
// lets log this message and code
$code = $result->getCode();
CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
// these are socket write errors which most likely means smtp connection errors
- // lets skip them
+ // lets skip them and reconnect.
$smtpConnectionErrors++;
if ($smtpConnectionErrors <= 5) {
+ $mailer->disconnect();
+ $retryGroup = TRUE;
continue;
}
@@ -710,11 +701,11 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
// Register the bounce event.
- $params = array(
+ $params = [
'event_queue_id' => $field['id'],
'job_id' => $this->id,
'hash' => $field['hash'],
- );
+ ];
$params = array_merge($params,
CRM_Mailing_BAO_BouncePattern::match($result->getMessage())
);
@@ -781,9 +772,50 @@ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attach
$job_date
);
+ if ($retryGroup) {
+ return FALSE;
+ }
+
return $result;
}
+ /**
+ * Determine if an SMTP error is temporary or permanent.
+ *
+ * @param string $message
+ * PEAR error message.
+ * @return bool
+ * TRUE - Temporary/retriable error
+ * FALSE - Permanent/non-retriable error
+ */
+ protected function isTemporaryError($message) {
+ // SMTP response code is buried in the message.
+ $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ? $matches[1] : '';
+
+ if (strpos($message, 'Failed to write to socket') !== FALSE) {
+ return TRUE;
+ }
+
+ // Register 5xx SMTP response code (permanent failure) as bounce.
+ if (isset($code{0}) && $code{0} === '5') {
+ return FALSE;
+ }
+
+ if (strpos($message, 'Failed to set sender') !== FALSE) {
+ return TRUE;
+ }
+
+ if (strpos($message, 'Failed to add recipient') !== FALSE) {
+ return TRUE;
+ }
+
+ if (strpos($message, 'Failed to send data') !== FALSE) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
/**
* Cancel a mailing.
*
@@ -799,17 +831,13 @@ public static function cancel($mailingId) {
AND ( ( job_type IS NULL ) OR
job_type <> 'child' )
";
- $params = array(1 => array($mailingId, 'Integer'));
+ $params = [1 => [$mailingId, 'Integer']];
$job = CRM_Core_DAO::executeQuery($sql, $params);
if ($job->fetch() &&
- in_array($job->status, array('Scheduled', 'Running', 'Paused'))
+ in_array($job->status, ['Scheduled', 'Running', 'Paused'])
) {
- $newJob = new CRM_Mailing_BAO_MailingJob();
- $newJob->id = $job->id;
- $newJob->end_date = date('YmdHis');
- $newJob->status = 'Canceled';
- $newJob->save();
+ self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
// also cancel all child jobs
$sql = "
@@ -821,16 +849,59 @@ public static function cancel($mailingId) {
AND job_type = 'child'
AND status IN ( 'Scheduled', 'Running', 'Paused' )
";
- $params = array(
- 1 => array($job->id, 'Integer'),
- 2 => array(date('YmdHis'), 'Timestamp'),
- );
+ $params = [
+ 1 => [$job->id, 'Integer'],
+ 2 => [date('YmdHis'), 'Timestamp'],
+ ];
CRM_Core_DAO::executeQuery($sql, $params);
-
- CRM_Core_Session::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
}
}
+ /**
+ * Pause a mailing
+ *
+ * @param int $mailingID
+ * The id of the mailing to be paused.
+ */
+ public static function pause($mailingID) {
+ $sql = "
+ UPDATE civicrm_mailing_job
+ SET status = 'Paused'
+ WHERE mailing_id = %1
+ AND is_test = 0
+ AND status IN ('Scheduled', 'Running')
+ ";
+ CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
+ }
+
+ /**
+ * Resume a mailing
+ *
+ * @param int $mailingID
+ * The id of the mailing to be resumed.
+ */
+ public static function resume($mailingID) {
+ $sql = "
+ UPDATE civicrm_mailing_job
+ SET status = 'Scheduled'
+ WHERE mailing_id = %1
+ AND is_test = 0
+ AND start_date IS NULL
+ AND status = 'Paused'
+ ";
+ CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
+
+ $sql = "
+ UPDATE civicrm_mailing_job
+ SET status = 'Running'
+ WHERE mailing_id = %1
+ AND is_test = 0
+ AND start_date IS NOT NULL
+ AND status = 'Paused'
+ ";
+ CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
+ }
+
/**
* Return a translated status enum string.
*
@@ -844,13 +915,13 @@ public static function status($status) {
static $translation = NULL;
if (empty($translation)) {
- $translation = array(
+ $translation = [
'Scheduled' => ts('Scheduled'),
'Running' => ts('Running'),
'Complete' => ts('Complete'),
'Paused' => ts('Paused'),
'Canceled' => ts('Canceled'),
- );
+ ];
}
return CRM_Utils_Array::value($status, $translation, ts('Not scheduled'));
}
@@ -866,10 +937,7 @@ public static function workflowClause() {
// add an additional check and only process
// jobs that are approved
if (CRM_Mailing_Info::workflowEnabled()) {
- $approveOptionID = CRM_Core_OptionGroup::getValue('mail_approval_status',
- 'Approved',
- 'name'
- );
+ $approveOptionID = CRM_Core_PseudoConstant::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
if ($approveOptionID) {
return " AND m.approval_status_id = $approveOptionID ";
}
@@ -898,7 +966,7 @@ public function writeToDB(
if (!empty($deliveredParams)) {
CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
- $deliveredParams = array();
+ $deliveredParams = [];
}
if ($writeActivity === NULL) {
@@ -914,25 +982,18 @@ public function writeToDB(
if (!$activityTypeID) {
if ($mailing->sms_provider_id) {
$mailing->subject = $mailing->name;
- $activityTypeID = CRM_Core_OptionGroup::getValue(
- 'activity_type',
- 'Mass SMS',
- 'name'
+ $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
);
}
else {
- $activityTypeID = CRM_Core_OptionGroup::getValue(
- 'activity_type',
- 'Bulk Email',
- 'name'
- );
+ $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
}
if (!$activityTypeID) {
CRM_Core_Error::fatal();
}
}
- $activity = array(
+ $activity = [
'source_contact_id' => $mailing->scheduled_id,
// CRM-9519
'target_contact_id' => array_unique($targetParams),
@@ -940,10 +1001,10 @@ public function writeToDB(
'source_record_id' => $this->mailing_id,
'activity_date_time' => $job_date,
'subject' => $mailing->subject,
- 'status_id' => 2,
+ 'status_id' => 'Completed',
'deleteActivityTarget' => FALSE,
'campaign_id' => $mailing->campaign_id,
- );
+ ];
//check whether activity is already created for this mailing.
//if yes then create only target contact record.
@@ -954,10 +1015,10 @@ public function writeToDB(
AND civicrm_activity.source_record_id = %2
";
- $queryParams = array(
- 1 => array($activityTypeID, 'Integer'),
- 2 => array($this->mailing_id, 'Integer'),
- );
+ $queryParams = [
+ 1 => [$activityTypeID, 'Integer'],
+ 2 => [$this->mailing_id, 'Integer'],
+ ];
$activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
if ($activityID) {
@@ -967,7 +1028,7 @@ public function writeToDB(
if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
static $targetRecordID = NULL;
if (!$targetRecordID) {
- $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
+ $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
}
@@ -987,11 +1048,14 @@ public function writeToDB(
}
}
- if (is_a(CRM_Activity_BAO_Activity::create($activity), 'CRM_Core_Error')) {
+ try {
+ civicrm_api3('Activity', 'create', $activity);
+ }
+ catch (Exception $e) {
$result = FALSE;
}
- $targetParams = array();
+ $targetParams = [];
}
return $result;
@@ -1061,4 +1125,24 @@ public static function findPendingTasks($jobId, $medium) {
return $eq;
}
+ /**
+ * Delete the mailing job.
+ *
+ * @param int $id
+ * Mailing Job id.
+ *
+ * @return mixed
+ */
+ public static function del($id) {
+ CRM_Utils_Hook::pre('delete', 'MailingJob', $id, CRM_Core_DAO::$_nullArray);
+
+ $jobDAO = new CRM_Mailing_BAO_MailingJob();
+ $jobDAO->id = $id;
+ $result = $jobDAO->delete();
+
+ CRM_Utils_Hook::post('delete', 'MailingJob', $jobDAO->id, $jobDAO);
+
+ return $result;
+ }
+
}
diff --git a/CRM/Mailing/BAO/Query.php b/CRM/Mailing/BAO/Query.php
index 7d690ad8ab74..aadb018caf01 100644
--- a/CRM/Mailing/BAO/Query.php
+++ b/CRM/Mailing/BAO/Query.php
@@ -1,9 +1,9 @@
'mailing_id',
'title' => ts('Mailing ID'),
'where' => 'civicrm_mailing.id',
- );
+ ];
}
return self::$_mailingFields;
}
@@ -137,7 +137,7 @@ public static function where(&$query) {
continue;
}
if (substr($query->_params[$id][0], 0, 8) == 'mailing_') {
- if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
+ if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$grouping = $query->_params[$id][3];
@@ -189,6 +189,10 @@ public static function from($name, $mode, $side) {
case 'recipient_email':
$from = " $side JOIN civicrm_email recipient_email ON recipient_email.id = civicrm_mailing_recipients.email_id";
break;
+
+ case 'civicrm_campaign':
+ $from = " $side JOIN civicrm_campaign ON civicrm_campaign.id = civicrm_mailing.campaign_id";
+ break;
}
return $from;
@@ -207,7 +211,7 @@ public static function defaultReturnProperties(
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
- $properties = array(
+ $properties = [
'mailing_id' => 1,
'mailing_campaign_id' => 1,
'mailing_name' => 1,
@@ -221,7 +225,7 @@ public static function defaultReturnProperties(
'contact_type' => 1,
'contact_sub_type' => 1,
'mailing_recipients_id' => 1,
- );
+ ];
}
return $properties;
}
@@ -233,9 +237,6 @@ public static function defaultReturnProperties(
public static function whereClauseSingle(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
- $fields = array();
- $fields = self::getFields();
-
switch ($name) {
case 'mailing_id':
$selectedMailings = array_flip($value);
@@ -255,14 +256,13 @@ public static function whereClauseSingle(&$values, &$query) {
return;
case 'mailing_name':
- $value = strtolower(addslashes($value));
+ $value = addslashes($value);
if ($wildcard) {
$value = "%$value%";
$op = 'LIKE';
}
- // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $query->_where[$grouping][] = "LOWER(civicrm_mailing.name) $op '$value'";
+ $query->_where[$grouping][] = "civicrm_mailing.name $op '$value'";
$query->_qill[$grouping][] = "Mailing Namename $op \"$value\"";
$query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
$query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
@@ -295,7 +295,7 @@ public static function whereClauseSingle(&$values, &$query) {
}
elseif ($value == 'N') {
$options['Y'] = $options['N'];
- $values = array($name, $op, 'Y', $grouping, $wildcard);
+ $values = [$name, $op, 'Y', $grouping, $wildcard];
self::mailingEventQueryBuilder($query, $values,
'civicrm_mailing_event_bounce',
'mailing_delivery_status',
@@ -307,15 +307,15 @@ public static function whereClauseSingle(&$values, &$query) {
case 'mailing_bounce_types':
$op = 'IN';
- $values = array($name, $op, $value, $grouping, $wildcard);
+ $values = [$name, $op, $value, $grouping, $wildcard];
self::mailingEventQueryBuilder($query, $values,
'civicrm_mailing_event_bounce',
'bounce_type_id',
ts('Bounce type(s)'),
- CRM_Core_PseudoConstant::get('CRM_Mailing_Event_DAO_Bounce', 'bounce_type_id', array(
- 'keyColumn' => 'id',
- 'labelColumn' => 'name',
- ))
+ CRM_Core_PseudoConstant::get('CRM_Mailing_Event_DAO_Bounce', 'bounce_type_id', [
+ 'keyColumn' => 'id',
+ 'labelColumn' => 'name',
+ ])
);
return;
@@ -338,7 +338,7 @@ public static function whereClauseSingle(&$values, &$query) {
return;
case 'mailing_optout':
- $valueTitle = array(1 => ts('Opt-out Requests'));
+ $valueTitle = [1 => ts('Opt-out Requests')];
// include opt-out events only
$query->_where[$grouping][] = "civicrm_mailing_event_unsubscribe.org_unsubscribe = 1";
self::mailingEventQueryBuilder($query, $values,
@@ -348,7 +348,7 @@ public static function whereClauseSingle(&$values, &$query) {
return;
case 'mailing_unsubscribe':
- $valueTitle = array(1 => ts('Unsubscribe Requests'));
+ $valueTitle = [1 => ts('Unsubscribe Requests')];
// exclude opt-out events
$query->_where[$grouping][] = "civicrm_mailing_event_unsubscribe.org_unsubscribe = 0";
self::mailingEventQueryBuilder($query, $values,
@@ -358,7 +358,7 @@ public static function whereClauseSingle(&$values, &$query) {
return;
case 'mailing_forward':
- $valueTitle = array('Y' => ts('Forwards'));
+ $valueTitle = ['Y' => ts('Forwards')];
// since its a checkbox
$values[2] = 'Y';
self::mailingEventQueryBuilder($query, $values,
@@ -385,7 +385,7 @@ public static function whereClauseSingle(&$values, &$query) {
$name = 'campaign_id';
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_mailing.$name", $op, $value, 'Integer');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Mailing_DAO_Mailing', $name, $value, $op);
- $query->_qill[$grouping][] = ts('Campaign %1 %2', array(1 => $op, 2 => $value));
+ $query->_qill[$grouping][] = ts('Campaign %1 %2', [1 => $op, 2 => $value]);
$query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
$query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
return;
@@ -404,36 +404,36 @@ public static function buildSearchForm(&$form) {
if (!empty($mailings)) {
$form->add('select', 'mailing_id', ts('Mailing Name(s)'), $mailings, FALSE,
- array('id' => 'mailing_id', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'mailing_id', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
CRM_Core_Form_Date::buildDateRange($form, 'mailing_date', 1, '_low', '_high', ts('From'), FALSE);
$form->addElement('hidden', 'mailing_date_range_error');
- $form->addFormRule(array('CRM_Mailing_BAO_Query', 'formRule'), $form);
+ $form->addFormRule(['CRM_Mailing_BAO_Query', 'formRule'], $form);
- $mailingJobStatuses = array(
+ $mailingJobStatuses = [
'' => ts('- select -'),
'Complete' => 'Complete',
'Scheduled' => 'Scheduled',
'Running' => 'Running',
'Canceled' => 'Canceled',
- );
+ ];
$form->addElement('select', 'mailing_job_status', ts('Mailing Job Status'), $mailingJobStatuses, FALSE);
$mailingBounceTypes = CRM_Core_PseudoConstant::get(
'CRM_Mailing_Event_DAO_Bounce', 'bounce_type_id',
- array('keyColumn' => 'id', 'labelColumn' => 'name')
+ ['keyColumn' => 'id', 'labelColumn' => 'name']
);
$form->add('select', 'mailing_bounce_types', ts('Bounce Types'), $mailingBounceTypes, FALSE,
- array('id' => 'mailing_bounce_types', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'mailing_bounce_types', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
// event filters
- $form->addRadio('mailing_delivery_status', ts('Delivery Status'), CRM_Mailing_PseudoConstant::yesNoOptions('delivered'), array('allowClear' => TRUE));
- $form->addRadio('mailing_open_status', ts('Trackable Opens'), CRM_Mailing_PseudoConstant::yesNoOptions('open'), array('allowClear' => TRUE));
- $form->addRadio('mailing_click_status', ts('Trackable URLs'), CRM_Mailing_PseudoConstant::yesNoOptions('click'), array('allowClear' => TRUE));
- $form->addRadio('mailing_reply_status', ts('Trackable Replies'), CRM_Mailing_PseudoConstant::yesNoOptions('reply'), array('allowClear' => TRUE));
+ $form->addRadio('mailing_delivery_status', ts('Delivery Status'), CRM_Mailing_PseudoConstant::yesNoOptions('delivered'), ['allowClear' => TRUE]);
+ $form->addRadio('mailing_open_status', ts('Trackable Opens'), CRM_Mailing_PseudoConstant::yesNoOptions('open'), ['allowClear' => TRUE]);
+ $form->addRadio('mailing_click_status', ts('Trackable URLs'), CRM_Mailing_PseudoConstant::yesNoOptions('click'), ['allowClear' => TRUE]);
+ $form->addRadio('mailing_reply_status', ts('Trackable Replies'), CRM_Mailing_PseudoConstant::yesNoOptions('reply'), ['allowClear' => TRUE]);
$form->add('checkbox', 'mailing_unsubscribe', ts('Unsubscribe Requests'));
$form->add('checkbox', 'mailing_optout', ts('Opt-out Requests'));
@@ -508,7 +508,7 @@ public static function mailingEventQueryBuilder(&$query, &$values, $tableName, $
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
if (empty($fields['mailing_date_high']) || empty($fields['mailing_date_low'])) {
return TRUE;
diff --git a/CRM/Mailing/BAO/Recipients.php b/CRM/Mailing/BAO/Recipients.php
index 27e39180333b..b554f385c68d 100644
--- a/CRM/Mailing/BAO/Recipients.php
+++ b/CRM/Mailing/BAO/Recipients.php
@@ -1,9 +1,9 @@
array($mailingID, 'Integer'));
+ $params = [1 => [$mailingID, 'Integer']];
return CRM_Core_DAO::singleValueQuery($sql, $params);
}
@@ -73,13 +73,29 @@ public static function mailingQuery(
$limitString = "LIMIT $offset, $limit";
}
+ $isSMSmode = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $mailingID, 'sms_provider_id', 'id');
+ $additionalJoin = '';
+ if (!$isSMSmode) {
+ // mailing_recipients added when mailing is submitted in UI by user.
+ // if any email is marked on_hold =1 or contact is deceased after mailing is submitted
+ // then it should be get skipped while preparing event_queue
+ // event_queue list is prepared when mailing job gets started.
+ $additionalJoin = " INNER JOIN civicrm_email e ON (r.email_id = e.id AND e.on_hold = 0 AND e.is_primary = 1)
+ INNER JOIN civicrm_contact c on (c.id = r.contact_id AND c.is_deceased <> 1 AND c.do_not_email = 0 AND c.is_opt_out = 0)
+";
+ }
+ else {
+ $additionalJoin = "INNER JOIN civicrm_contact c on (c.id = r.contact_id AND c.is_deceased <> 1 AND c.do_not_sms = 0 AND c.is_opt_out = 0)";
+ }
+
$sql = "
-SELECT contact_id, email_id, phone_id
-FROM civicrm_mailing_recipients
-WHERE mailing_id = %1
+SELECT r.contact_id, r.email_id, r.phone_id
+FROM civicrm_mailing_recipients r
+{$additionalJoin}
+WHERE r.mailing_id = %1
$limitString
";
- $params = array(1 => array($mailingID, 'Integer'));
+ $params = [1 => [$mailingID, 'Integer']];
return CRM_Core_DAO::executeQuery($sql, $params);
}
@@ -102,7 +118,7 @@ public static function updateRandomRecipients($sourceMailingId, $newMailingID, $
CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS srcMailing_$sourceMailingId");
$sql = "
CREATE TEMPORARY TABLE srcMailing_$sourceMailingId
- (mailing_recipient_id int, id int PRIMARY KEY AUTO_INCREMENT, INDEX(mailing_recipient_id))
+ (mailing_recipient_id int unsigned, id int PRIMARY KEY AUTO_INCREMENT, INDEX(mailing_recipient_id))
ENGINE=HEAP";
CRM_Core_DAO::executeQuery($sql);
$sql = "
diff --git a/CRM/Mailing/BAO/Spool.php b/CRM/Mailing/BAO/Spool.php
index b12ed227dfb7..ffb5e51c06f0 100644
--- a/CRM/Mailing/BAO/Spool.php
+++ b/CRM/Mailing/BAO/Spool.php
@@ -1,9 +1,9 @@
$value) {
$headerStr[] = "$name: $value";
}
@@ -70,7 +70,7 @@ public function send($recipient, $headers, $body, $job_id = NULL) {
// This is not a bulk mailing. Create a dummy job for it.
$session = CRM_Core_Session::singleton();
- $params = array();
+ $params = [];
$params['created_id'] = $session->get('userID');
$params['created_date'] = date('YmdHis');
$params['scheduled_id'] = $params['created_id'];
@@ -80,7 +80,7 @@ public function send($recipient, $headers, $body, $job_id = NULL) {
$params['body_html'] = htmlspecialchars($headerStr) . "\n\n" . $body;
$params['subject'] = $headers['Subject'];
$params['name'] = $headers['Subject'];
- $ids = array();
+ $ids = [];
$mailing = CRM_Mailing_BAO_Mailing::create($params, $ids);
if (empty($mailing) || is_a($mailing, 'CRM_Core_Error')) {
@@ -88,14 +88,16 @@ public function send($recipient, $headers, $body, $job_id = NULL) {
}
$job = new CRM_Mailing_BAO_MailingJob();
- $job->is_test = 0; // if set to 1 it doesn't show in the UI
+ // if set to 1 it doesn't show in the UI
+ $job->is_test = 0;
$job->status = 'Complete';
$job->scheduled_date = CRM_Utils_Date::processDate(date('Y-m-d'), date('H:i:s'));
$job->start_date = $job->scheduled_date;
$job->end_date = $job->scheduled_date;
$job->mailing_id = $mailing->id;
$job->save();
- $job_id = $job->id; // need this for parent_id below
+ // need this for parent_id below
+ $job_id = $job->id;
$job = new CRM_Mailing_BAO_MailingJob();
$job->is_test = 0;
@@ -107,7 +109,8 @@ public function send($recipient, $headers, $body, $job_id = NULL) {
$job->parent_id = $job_id;
$job->job_type = 'child';
$job->save();
- $job_id = $job->id; // this is the one we want for the spool
+ // this is the one we want for the spool
+ $job_id = $job->id;
if (is_array($recipient)) {
$recipient = implode(';', $recipient);
@@ -116,14 +119,14 @@ public function send($recipient, $headers, $body, $job_id = NULL) {
$session = CRM_Core_Session::singleton();
- $params = array(
+ $params = [
'job_id' => $job_id,
'recipient_email' => $recipient,
'headers' => $headerStr,
'body' => $body,
'added_at' => date("YmdHis"),
'removed_at' => NULL,
- );
+ ];
$spoolMail = new CRM_Mailing_DAO_Spool();
$spoolMail->copyValues($params);
diff --git a/CRM/Mailing/BAO/TrackableURL.php b/CRM/Mailing/BAO/TrackableURL.php
index 09307993b91c..da57a134c3eb 100644
--- a/CRM/Mailing/BAO/TrackableURL.php
+++ b/CRM/Mailing/BAO/TrackableURL.php
@@ -1,9 +1,9 @@
save();
}
$id = $tracker->id;
- $tracker->free();
$redirect = $config->userFrameworkResourceURL . "extern/url.php?u=$id";
$urlCache[$mailing_id . $url] = $redirect;
@@ -97,7 +96,7 @@ public static function getTrackerURL($url, $mailing_id, $queue_id) {
$returnUrl = "{$urlCache[$mailing_id . $url]}&qid={$queue_id}";
if ($hrefExists) {
- $returnUrl = "href='{$returnUrl}'";
+ $returnUrl = "href='{$returnUrl}' rel='nofollow'";
}
return $returnUrl;
diff --git a/CRM/Mailing/Config.php b/CRM/Mailing/Config.php
index c0a1e1c6cd39..79fdb2028ecd 100644
--- a/CRM/Mailing/Config.php
+++ b/CRM/Mailing/Config.php
@@ -1,9 +1,9 @@
$mid));
+ $clone = civicrm_api3('Mailing', 'clone', ['id' => $mid]);
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/a/', NULL, TRUE, '/mailing/' . $clone['id']));
}
}
diff --git a/CRM/Mailing/DAO/BouncePattern.php b/CRM/Mailing/DAO/BouncePattern.php
index 4901666ccabc..8ddb1faad08a 100644
--- a/CRM/Mailing/DAO/BouncePattern.php
+++ b/CRM/Mailing/DAO/BouncePattern.php
@@ -1,168 +1,157 @@
__table = 'civicrm_mailing_bounce_pattern';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'bounce_type_id', 'civicrm_mailing_bounce_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'bounce_type_id', 'civicrm_mailing_bounce_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Bounce Pattern ID') ,
- 'required' => true,
+ 'title' => ts('Bounce Pattern ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_bounce_pattern.id',
'table_name' => 'civicrm_mailing_bounce_pattern',
'entity' => 'BouncePattern',
'bao' => 'CRM_Mailing_BAO_BouncePattern',
'localizable' => 0,
- ) ,
- 'bounce_type_id' => array(
+ ],
+ 'bounce_type_id' => [
'name' => 'bounce_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Bounce Type') ,
- 'description' => 'Type of bounce',
- 'required' => true,
+ 'title' => ts('Bounce Type'),
+ 'description' => ts('Type of bounce'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_bounce_pattern.bounce_type_id',
'table_name' => 'civicrm_mailing_bounce_pattern',
'entity' => 'BouncePattern',
'bao' => 'CRM_Mailing_BAO_BouncePattern',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_BounceType',
- ) ,
- 'pattern' => array(
+ ],
+ 'pattern' => [
'name' => 'pattern',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pattern') ,
- 'description' => 'A regexp to match a message to a bounce type',
+ 'title' => ts('Pattern'),
+ 'description' => ts('A regexp to match a message to a bounce type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_bounce_pattern.pattern',
'table_name' => 'civicrm_mailing_bounce_pattern',
'entity' => 'BouncePattern',
'bao' => 'CRM_Mailing_BAO_BouncePattern',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -170,10 +159,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_bounce_pattern', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_bounce_pattern', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -181,15 +171,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_bounce_pattern', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_bounce_pattern', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/BounceType.php b/CRM/Mailing/DAO/BounceType.php
index 0c358e49d226..d72a3ccc696d 100644
--- a/CRM/Mailing/DAO/BounceType.php
+++ b/CRM/Mailing/DAO/BounceType.php
@@ -1,172 +1,162 @@
__table = 'civicrm_mailing_bounce_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Bounce Type ID') ,
- 'required' => true,
+ 'title' => ts('Bounce Type ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_bounce_type.id',
'table_name' => 'civicrm_mailing_bounce_type',
'entity' => 'BounceType',
'bao' => 'CRM_Mailing_DAO_BounceType',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Bounce Type Name') ,
- 'description' => 'Type of bounce',
- 'required' => true,
+ 'title' => ts('Bounce Type Name'),
+ 'description' => ts('Type of bounce'),
+ 'required' => TRUE,
'maxlength' => 24,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing_bounce_type.name',
'table_name' => 'civicrm_mailing_bounce_type',
'entity' => 'BounceType',
'bao' => 'CRM_Mailing_DAO_BounceType',
'localizable' => 0,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Bounce Type Description') ,
- 'description' => 'A description of this bounce type',
+ 'title' => ts('Bounce Type Description'),
+ 'description' => ts('A description of this bounce type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_bounce_type.description',
'table_name' => 'civicrm_mailing_bounce_type',
'entity' => 'BounceType',
'bao' => 'CRM_Mailing_DAO_BounceType',
'localizable' => 0,
- ) ,
- 'hold_threshold' => array(
+ ],
+ 'hold_threshold' => [
'name' => 'hold_threshold',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Hold Threshold') ,
- 'description' => 'Number of bounces of this type required before the email address is put on bounce hold',
- 'required' => true,
+ 'title' => ts('Hold Threshold'),
+ 'description' => ts('Number of bounces of this type required before the email address is put on bounce hold'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_bounce_type.hold_threshold',
'table_name' => 'civicrm_mailing_bounce_type',
'entity' => 'BounceType',
'bao' => 'CRM_Mailing_DAO_BounceType',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -174,10 +164,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_bounce_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_bounce_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -185,15 +176,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_bounce_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_bounce_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/Component.php b/CRM/Mailing/DAO/Component.php
deleted file mode 100644
index 589a09268b18..000000000000
--- a/CRM/Mailing/DAO/Component.php
+++ /dev/null
@@ -1,277 +0,0 @@
-__table = 'civicrm_mailing_component';
- parent::__construct();
- }
- /**
- * Returns all the column names of this table
- *
- * @return array
- */
- static function &fields() {
- if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
- 'name' => 'id',
- 'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Component ID') ,
- 'required' => true,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- ) ,
- 'name' => array(
- 'name' => 'name',
- 'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Component Name') ,
- 'description' => 'The name of this component',
- 'maxlength' => 64,
- 'size' => CRM_Utils_Type::BIG,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- ) ,
- 'component_type' => array(
- 'name' => 'component_type',
- 'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Component Type') ,
- 'description' => 'Type of Component.',
- 'maxlength' => 12,
- 'size' => CRM_Utils_Type::TWELVE,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- 'html' => array(
- 'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
- 'callback' => 'CRM_Core_SelectValues::mailingComponents',
- )
- ) ,
- 'subject' => array(
- 'name' => 'subject',
- 'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
- 'maxlength' => 255,
- 'size' => CRM_Utils_Type::HUGE,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- ) ,
- 'body_html' => array(
- 'name' => 'body_html',
- 'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Mailing Component Body HTML') ,
- 'description' => 'Body of the component in html format.',
- 'rows' => 8,
- 'cols' => 80,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'body_text' => array(
- 'name' => 'body_text',
- 'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Body Text') ,
- 'description' => 'Body of the component in text format.',
- 'rows' => 8,
- 'cols' => 80,
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- 'html' => array(
- 'type' => 'TextArea',
- ) ,
- ) ,
- 'is_default' => array(
- 'name' => 'is_default',
- 'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Mailing Component is Default?') ,
- 'description' => 'Is this the default component for this component_type?',
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- ) ,
- 'is_active' => array(
- 'name' => 'is_active',
- 'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Mailing Component Is Active?') ,
- 'description' => 'Is this property active?',
- 'table_name' => 'civicrm_mailing_component',
- 'entity' => 'Component',
- 'bao' => 'CRM_Mailing_BAO_Component',
- 'localizable' => 0,
- ) ,
- );
- CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
- }
- return Civi::$statics[__CLASS__]['fields'];
- }
- /**
- * Return a mapping from field-name to the corresponding key (as used in fields()).
- *
- * @return array
- * Array(string $name => string $uniqueName).
- */
- static function &fieldKeys() {
- if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
- Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
- }
- return Civi::$statics[__CLASS__]['fieldKeys'];
- }
- /**
- * Returns the names of this table
- *
- * @return string
- */
- static function getTableName() {
- return self::$_tableName;
- }
- /**
- * Returns if this table needs to be logged
- *
- * @return boolean
- */
- function getLog() {
- return self::$_log;
- }
- /**
- * Returns the list of fields that can be imported
- *
- * @param bool $prefix
- *
- * @return array
- */
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_component', $prefix, array());
- return $r;
- }
- /**
- * Returns the list of fields that can be exported
- *
- * @param bool $prefix
- *
- * @return array
- */
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_component', $prefix, array());
- return $r;
- }
- /**
- * Returns the list of indices
- */
- public static function indices($localize = TRUE) {
- $indices = array();
- return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
- }
-}
diff --git a/CRM/Mailing/DAO/Mailing.php b/CRM/Mailing/DAO/Mailing.php
index d9c55517f29d..9f727b0c260d 100644
--- a/CRM/Mailing/DAO/Mailing.php
+++ b/CRM/Mailing/DAO/Mailing.php
@@ -1,946 +1,1047 @@
__table = 'civicrm_mailing';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'header_id', 'civicrm_mailing_component', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'footer_id', 'civicrm_mailing_component', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'reply_id', 'civicrm_mailing_component', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'unsubscribe_id', 'civicrm_mailing_component', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'optout_id', 'civicrm_mailing_component', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'msg_template_id', 'civicrm_msg_template', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'scheduled_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'approver_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'sms_provider_id', 'civicrm_sms_provider', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'location_type_id', 'civicrm_location_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'header_id', 'civicrm_mailing_component', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'footer_id', 'civicrm_mailing_component', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'reply_id', 'civicrm_mailing_component', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'unsubscribe_id', 'civicrm_mailing_component', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'optout_id', 'civicrm_mailing_component', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'msg_template_id', 'civicrm_msg_template', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'scheduled_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'approver_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'sms_provider_id', 'civicrm_sms_provider', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'location_type_id', 'civicrm_location_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing ID') ,
- 'required' => true,
+ 'title' => ts('Mailing ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing.id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Domain') ,
- 'description' => 'Which site is this mailing for',
+ 'title' => ts('Mailing Domain'),
+ 'description' => ts('Which site is this mailing for'),
+ 'where' => 'civicrm_mailing.domain_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'header_id' => array(
+ ],
+ ],
+ 'header_id' => [
'name' => 'header_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Header') ,
- 'description' => 'FK to the header component.',
+ 'title' => ts('Mailing Header'),
+ 'description' => ts('FK to the header component.'),
+ 'where' => 'civicrm_mailing.header_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'footer_id' => array(
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ 'pseudoconstant' => [
+ 'table' => 'civicrm_mailing_component',
+ 'keyColumn' => 'id',
+ 'labelColumn' => 'name',
+ 'condition' => 'component_type = "Header"',
+ ],
+ ],
+ 'footer_id' => [
'name' => 'footer_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Footer') ,
- 'description' => 'FK to the footer component.',
+ 'title' => ts('Mailing Footer'),
+ 'description' => ts('FK to the footer component.'),
+ 'where' => 'civicrm_mailing.footer_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'reply_id' => array(
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ 'pseudoconstant' => [
+ 'table' => 'civicrm_mailing_component',
+ 'keyColumn' => 'id',
+ 'labelColumn' => 'name',
+ 'condition' => 'component_type = "Footer"',
+ ],
+ ],
+ 'reply_id' => [
'name' => 'reply_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Reply') ,
- 'description' => 'FK to the auto-responder component.',
+ 'title' => ts('Mailing Reply'),
+ 'description' => ts('FK to the auto-responder component.'),
+ 'where' => 'civicrm_mailing.reply_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'unsubscribe_id' => array(
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'unsubscribe_id' => [
'name' => 'unsubscribe_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Unsubscribe') ,
- 'description' => 'FK to the unsubscribe component.',
+ 'title' => ts('Mailing Unsubscribe'),
+ 'description' => ts('FK to the unsubscribe component.'),
+ 'where' => 'civicrm_mailing.unsubscribe_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'resubscribe_id' => array(
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'resubscribe_id' => [
'name' => 'resubscribe_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Resubscribe') ,
+ 'title' => ts('Mailing Resubscribe'),
+ 'where' => 'civicrm_mailing.resubscribe_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'optout_id' => array(
+ ],
+ 'optout_id' => [
'name' => 'optout_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Opt Out') ,
- 'description' => 'FK to the opt-out component.',
+ 'title' => ts('Mailing Opt Out'),
+ 'description' => ts('FK to the opt-out component.'),
+ 'where' => 'civicrm_mailing.optout_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'name' => array(
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Name') ,
- 'description' => 'Mailing Name.',
+ 'title' => ts('Mailing Name'),
+ 'description' => ts('Mailing Name.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing.name',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'mailing_type' => array(
+ ],
+ ],
+ 'mailing_type' => [
'name' => 'mailing_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Type') ,
- 'description' => 'differentiate between standalone mailings, A/B tests, and A/B final-winner',
+ 'title' => ts('Mailing Type'),
+ 'description' => ts('differentiate between standalone mailings, A/B tests, and A/B final-winner'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing.mailing_type',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_PseudoConstant::mailingTypes',
- )
- ) ,
- 'from_name' => array(
+ ],
+ ],
+ 'from_name' => [
'name' => 'from_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing From Name') ,
- 'description' => 'From Header of mailing',
+ 'title' => ts('Mailing From Name'),
+ 'description' => ts('From Header of mailing'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing.from_name',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'from_email' => array(
+ ],
+ ],
+ 'from_email' => [
'name' => 'from_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing From Email') ,
- 'description' => 'From Email of mailing',
+ 'title' => ts('Mailing From Email'),
+ 'description' => ts('From Email of mailing'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing.from_email',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'replyto_email' => array(
+ ],
+ ],
+ 'replyto_email' => [
'name' => 'replyto_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Replyto Email') ,
- 'description' => 'Reply-To Email of mailing',
+ 'title' => ts('Replyto Email'),
+ 'description' => ts('Reply-To Email of mailing'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing.replyto_email',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'template_type' => array(
+ ],
+ ],
+ 'template_type' => [
'name' => 'template_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Template Type') ,
- 'description' => 'The language/processing system used for email templates.',
- 'required' => true,
+ 'title' => ts('Template Type'),
+ 'description' => ts('The language/processing system used for email templates.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_mailing.template_type',
'default' => 'traditional',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_BAO_Mailing::getTemplateTypeNames',
- )
- ) ,
- 'template_options' => array(
+ ],
+ ],
+ 'template_options' => [
'name' => 'template_options',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Template Options (JSON)') ,
- 'description' => 'Advanced options used by the email templating system. (JSON encoded)',
+ 'title' => ts('Template Options (JSON)'),
+ 'description' => ts('Advanced options used by the email templating system. (JSON encoded)'),
+ 'where' => 'civicrm_mailing.template_options',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'subject' => array(
+ ],
+ 'subject' => [
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
- 'description' => 'Subject of mailing',
+ 'title' => ts('Subject'),
+ 'description' => ts('Subject of mailing'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing.subject',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'body_text' => array(
+ ],
+ ],
+ 'body_text' => [
'name' => 'body_text',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Body Text') ,
- 'description' => 'Body of the mailing in text format.',
+ 'title' => ts('Body Text'),
+ 'description' => ts('Body of the mailing in text format.'),
+ 'where' => 'civicrm_mailing.body_text',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'body_html' => array(
+ ],
+ 'body_html' => [
'name' => 'body_html',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Body Html') ,
- 'description' => 'Body of the mailing in html format.',
+ 'title' => ts('Body Html'),
+ 'description' => ts('Body of the mailing in html format.'),
+ 'where' => 'civicrm_mailing.body_html',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'url_tracking' => array(
+ ],
+ 'url_tracking' => [
'name' => 'url_tracking',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Url Tracking') ,
- 'description' => 'Should we track URL click-throughs for this mailing?',
+ 'title' => ts('Url Tracking'),
+ 'description' => ts('Should we track URL click-throughs for this mailing?'),
+ 'where' => 'civicrm_mailing.url_tracking',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'forward_replies' => array(
+ ],
+ ],
+ 'forward_replies' => [
'name' => 'forward_replies',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Forward Replies') ,
- 'description' => 'Should we forward replies back to the author?',
+ 'title' => ts('Forward Replies'),
+ 'description' => ts('Should we forward replies back to the author?'),
+ 'where' => 'civicrm_mailing.forward_replies',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'auto_responder' => array(
+ ],
+ ],
+ 'auto_responder' => [
'name' => 'auto_responder',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Auto Responder') ,
- 'description' => 'Should we enable the auto-responder?',
+ 'title' => ts('Auto Responder'),
+ 'description' => ts('Should we enable the auto-responder?'),
+ 'where' => 'civicrm_mailing.auto_responder',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'open_tracking' => array(
+ ],
+ ],
+ 'open_tracking' => [
'name' => 'open_tracking',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Track Mailing?') ,
- 'description' => 'Should we track when recipients open/read this mailing?',
+ 'title' => ts('Track Mailing?'),
+ 'description' => ts('Should we track when recipients open/read this mailing?'),
+ 'where' => 'civicrm_mailing.open_tracking',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'is_completed' => array(
+ ],
+ 'is_completed' => [
'name' => 'is_completed',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Mailing Completed') ,
- 'description' => 'Has at least one job associated with this mailing finished?',
+ 'title' => ts('Mailing Completed'),
+ 'description' => ts('Has at least one job associated with this mailing finished?'),
+ 'where' => 'civicrm_mailing.is_completed',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'msg_template_id' => array(
+ ],
+ ],
+ 'msg_template_id' => [
'name' => 'msg_template_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Message Template') ,
- 'description' => 'FK to the message template.',
+ 'title' => ts('Mailing Message Template'),
+ 'description' => ts('FK to the message template.'),
+ 'where' => 'civicrm_mailing.msg_template_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_MessageTemplate',
- ) ,
- 'override_verp' => array(
+ ],
+ 'override_verp' => [
'name' => 'override_verp',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Override Verp') ,
- 'description' => 'Should we overrite VERP address in Reply-To',
+ 'title' => ts('Override Verp'),
+ 'description' => ts('Should we overrite VERP address in Reply-To'),
+ 'where' => 'civicrm_mailing.override_verp',
+ 'default' => '0',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'created_id' => array(
+ ],
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Creator') ,
- 'description' => 'FK to Contact ID who first created this mailing',
+ 'title' => ts('Mailing Creator'),
+ 'description' => ts('FK to Contact ID who first created this mailing'),
+ 'where' => 'civicrm_mailing.created_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Created Date') ,
- 'description' => 'Date and time this mailing was created.',
- 'required' => false,
- 'default' => 'CURRENT_TIMESTAMP',
+ 'title' => ts('Mailing Created Date'),
+ 'description' => ts('Date and time this mailing was created.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing.created_date',
+ 'default' => 'NULL',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'scheduled_id' => array(
+ ],
+ ],
+ 'mailing_modified_date' => [
+ 'name' => 'modified_date',
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Modified Date'),
+ 'description' => ts('When the mailing (or closely related entity) was created or modified or deleted.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing.modified_date',
+ 'export' => TRUE,
+ 'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ 'scheduled_id' => [
'name' => 'scheduled_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Scheduled By') ,
- 'description' => 'FK to Contact ID who scheduled this mailing',
+ 'title' => ts('Scheduled By'),
+ 'description' => ts('FK to Contact ID who scheduled this mailing'),
+ 'where' => 'civicrm_mailing.scheduled_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'scheduled_date' => array(
+ ],
+ 'scheduled_date' => [
'name' => 'scheduled_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Scheduled Date') ,
- 'description' => 'Date and time this mailing was scheduled.',
- 'required' => false,
+ 'title' => ts('Mailing Scheduled Date'),
+ 'description' => ts('Date and time this mailing was scheduled.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing.scheduled_date',
'default' => 'NULL',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'approver_id' => array(
+ ],
+ ],
+ 'approver_id' => [
'name' => 'approver_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Approved By') ,
- 'description' => 'FK to Contact ID who approved this mailing',
+ 'title' => ts('Approved By'),
+ 'description' => ts('FK to Contact ID who approved this mailing'),
+ 'where' => 'civicrm_mailing.approver_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'approval_date' => array(
+ ],
+ 'approval_date' => [
'name' => 'approval_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Approved Date') ,
- 'description' => 'Date and time this mailing was approved.',
- 'required' => false,
+ 'title' => ts('Mailing Approved Date'),
+ 'description' => ts('Date and time this mailing was approved.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing.approval_date',
'default' => 'NULL',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'approval_status_id' => array(
+ ],
+ ],
+ 'approval_status_id' => [
'name' => 'approval_status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Approval Status') ,
- 'description' => 'The status of this mailing. Values: none, approved, rejected',
+ 'title' => ts('Approval Status'),
+ 'description' => ts('The status of this mailing. Values: none, approved, rejected'),
+ 'where' => 'civicrm_mailing.approval_status_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'mail_approval_status',
'optionEditPath' => 'civicrm/admin/options/mail_approval_status',
- )
- ) ,
- 'approval_note' => array(
+ ],
+ ],
+ 'approval_note' => [
'name' => 'approval_note',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Approval Note') ,
- 'description' => 'Note behind the decision.',
+ 'title' => ts('Approval Note'),
+ 'description' => ts('Note behind the decision.'),
+ 'where' => 'civicrm_mailing.approval_note',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_archived' => array(
+ ],
+ ],
+ 'is_archived' => [
'name' => 'is_archived',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Mailing Archived?') ,
- 'description' => 'Is this mailing archived?',
+ 'title' => ts('Is Mailing Archived?'),
+ 'description' => ts('Is this mailing archived?'),
+ 'where' => 'civicrm_mailing.is_archived',
+ 'default' => '0',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'visibility' => array(
+ ],
+ ],
+ 'visibility' => [
'name' => 'visibility',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Visibility') ,
- 'description' => 'In what context(s) is the mailing contents visible (online viewing)',
+ 'title' => ts('Mailing Visibility'),
+ 'description' => ts('In what context(s) is the mailing contents visible (online viewing)'),
'maxlength' => 40,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_mailing.visibility',
'default' => 'Public Pages',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::groupVisibility',
- )
- ) ,
- 'campaign_id' => array(
+ ],
+ ],
+ 'campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Campaign') ,
- 'description' => 'The campaign for which this mailing has been initiated.',
+ 'title' => ts('Mailing Campaign'),
+ 'description' => ts('The campaign for which this mailing has been initiated.'),
+ 'where' => 'civicrm_mailing.campaign_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'dedupe_email' => array(
+ ],
+ ],
+ 'dedupe_email' => [
'name' => 'dedupe_email',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('No Duplicate emails?') ,
- 'description' => 'Remove duplicate emails?',
+ 'title' => ts('No Duplicate emails?'),
+ 'description' => ts('Remove duplicate emails?'),
+ 'where' => 'civicrm_mailing.dedupe_email',
+ 'default' => '0',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'sms_provider_id' => array(
+ ],
+ ],
+ 'sms_provider_id' => [
'name' => 'sms_provider_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing SMS Provider') ,
+ 'title' => ts('Mailing SMS Provider'),
+ 'where' => 'civicrm_mailing.sms_provider_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_SMS_DAO_Provider',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'hash' => array(
+ ],
+ ],
+ 'hash' => [
'name' => 'hash',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Hash') ,
- 'description' => 'Key for validating requests related to this mailing.',
+ 'title' => ts('Mailing Hash'),
+ 'description' => ts('Key for validating requests related to this mailing.'),
'maxlength' => 16,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_mailing.hash',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- ) ,
- 'location_type_id' => array(
+ ],
+ 'location_type_id' => [
'name' => 'location_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Location Type') ,
- 'description' => 'With email_selection_method, determines which email address to use',
+ 'title' => ts('Location Type'),
+ 'description' => ts('With email_selection_method, determines which email address to use'),
+ 'where' => 'civicrm_mailing.location_type_id',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_LocationType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_location_type',
'keyColumn' => 'id',
'labelColumn' => 'display_name',
- )
- ) ,
- 'email_selection_method' => array(
+ ],
+ ],
+ 'email_selection_method' => [
'name' => 'email_selection_method',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Email Selection Method') ,
- 'description' => 'With location_type_id, determine how to choose the email address to use.',
+ 'title' => ts('Email Selection Method'),
+ 'description' => ts('With location_type_id, determine how to choose the email address to use.'),
'maxlength' => 20,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing.email_selection_method',
'default' => 'automatic',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::emailSelectMethods',
- )
- ) ,
- 'language' => array(
+ ],
+ ],
+ 'language' => [
'name' => 'language',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Language') ,
- 'description' => 'Language of the content of the mailing. Useful for tokens.',
+ 'title' => ts('Mailing Language'),
+ 'description' => ts('Language of the content of the mailing. Useful for tokens.'),
'maxlength' => 5,
'size' => CRM_Utils_Type::SIX,
+ 'where' => 'civicrm_mailing.language',
'table_name' => 'civicrm_mailing',
'entity' => 'Mailing',
'bao' => 'CRM_Mailing_BAO_Mailing',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'languages',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/languages',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -948,10 +1049,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -959,24 +1061,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_hash' => array(
+ $indices = [
+ 'index_hash' => [
'name' => 'index_hash',
- 'field' => array(
+ 'field' => [
0 => 'hash',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_mailing::0::hash',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/MailingAB.php b/CRM/Mailing/DAO/MailingAB.php
index b3997d94fb20..aa421ff0311c 100644
--- a/CRM/Mailing/DAO/MailingAB.php
+++ b/CRM/Mailing/DAO/MailingAB.php
@@ -1,359 +1,367 @@
__table = 'civicrm_mailing_abtest';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('MailingAB ID') ,
- 'required' => true,
+ 'title' => ts('MailingAB ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_abtest.id',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Name of the A/B test',
+ 'title' => ts('Name'),
+ 'description' => ts('Name of the A/B test'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_abtest.name',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'status' => array(
+ ],
+ 'status' => [
'name' => 'status',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Status') ,
- 'description' => 'Status',
+ 'title' => ts('Status'),
+ 'description' => ts('Status'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing_abtest.status',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_PseudoConstant::abStatus',
- )
- ) ,
- 'mailing_id_a' => array(
+ ],
+ ],
+ 'mailing_id_a' => [
'name' => 'mailing_id_a',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing ID (A)') ,
- 'description' => 'The first experimental mailing ("A" condition)',
+ 'title' => ts('Mailing ID (A)'),
+ 'description' => ts('The first experimental mailing ("A" condition)'),
+ 'where' => 'civicrm_mailing_abtest.mailing_id_a',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'mailing_id_b' => array(
+ ],
+ 'mailing_id_b' => [
'name' => 'mailing_id_b',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing ID (B)') ,
- 'description' => 'The second experimental mailing ("B" condition)',
+ 'title' => ts('Mailing ID (B)'),
+ 'description' => ts('The second experimental mailing ("B" condition)'),
+ 'where' => 'civicrm_mailing_abtest.mailing_id_b',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'mailing_id_c' => array(
+ ],
+ 'mailing_id_c' => [
'name' => 'mailing_id_c',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing ID (C)') ,
- 'description' => 'The final, general mailing (derived from A or B)',
+ 'title' => ts('Mailing ID (C)'),
+ 'description' => ts('The final, general mailing (derived from A or B)'),
+ 'where' => 'civicrm_mailing_abtest.mailing_id_c',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Domain ID') ,
- 'description' => 'Which site is this mailing for',
+ 'title' => ts('Domain ID'),
+ 'description' => ts('Which site is this mailing for'),
+ 'where' => 'civicrm_mailing_abtest.domain_id',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'testing_criteria' => array(
+ ],
+ 'testing_criteria' => [
'name' => 'testing_criteria',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Testing Criteria') ,
+ 'title' => ts('Testing Criteria'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing_abtest.testing_criteria',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_PseudoConstant::abTestCriteria',
- )
- ) ,
- 'winner_criteria' => array(
+ ],
+ ],
+ 'winner_criteria' => [
'name' => 'winner_criteria',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Winner Criteria') ,
+ 'title' => ts('Winner Criteria'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_mailing_abtest.winner_criteria',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_PseudoConstant::abWinnerCriteria',
- )
- ) ,
- 'specific_url' => array(
+ ],
+ ],
+ 'specific_url' => [
'name' => 'specific_url',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('URL for Winner Criteria') ,
- 'description' => 'What specific url to track',
+ 'title' => ts('URL for Winner Criteria'),
+ 'description' => ts('What specific url to track'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_abtest.specific_url',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'declare_winning_time' => array(
+ ],
+ 'declare_winning_time' => [
'name' => 'declare_winning_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Declaration Time') ,
- 'description' => 'In how much time to declare winner',
+ 'title' => ts('Declaration Time'),
+ 'description' => ts('In how much time to declare winner'),
+ 'where' => 'civicrm_mailing_abtest.declare_winning_time',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'group_percentage' => array(
+ ],
+ 'group_percentage' => [
'name' => 'group_percentage',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Percentage') ,
+ 'title' => ts('Group Percentage'),
+ 'where' => 'civicrm_mailing_abtest.group_percentage',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- ) ,
- 'created_id' => array(
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('AB Test Created By') ,
- 'description' => 'FK to Contact ID',
+ 'title' => ts('AB Test Created By'),
+ 'description' => ts('FK to Contact ID'),
+ 'where' => 'civicrm_mailing_abtest.created_id',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('AB Test Created Date') ,
- 'description' => 'When was this item created',
- 'required' => false,
+ 'title' => ts('AB Test Created Date'),
+ 'description' => ts('When was this item created'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_abtest.created_date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_mailing_abtest',
'entity' => 'MailingAB',
'bao' => 'CRM_Mailing_BAO_MailingAB',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -361,10 +369,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_abtest', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_abtest', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -372,15 +381,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_abtest', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_abtest', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/MailingComponent.php b/CRM/Mailing/DAO/MailingComponent.php
new file mode 100644
index 000000000000..beb28dd57785
--- /dev/null
+++ b/CRM/Mailing/DAO/MailingComponent.php
@@ -0,0 +1,282 @@
+__table = 'civicrm_mailing_component';
+ parent::__construct();
+ }
+
+ /**
+ * Returns all the column names of this table
+ *
+ * @return array
+ */
+ public static function &fields() {
+ if (!isset(Civi::$statics[__CLASS__]['fields'])) {
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
+ 'name' => 'id',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Mailing Component ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_component.id',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ ],
+ 'name' => [
+ 'name' => 'name',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Component Name'),
+ 'description' => ts('The name of this component'),
+ 'maxlength' => 64,
+ 'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_mailing_component.name',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ ],
+ 'component_type' => [
+ 'name' => 'component_type',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Mailing Component Type'),
+ 'description' => ts('Type of Component.'),
+ 'maxlength' => 12,
+ 'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_mailing_component.component_type',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
+ 'callback' => 'CRM_Core_SelectValues::mailingComponents',
+ ],
+ ],
+ 'subject' => [
+ 'name' => 'subject',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Subject'),
+ 'maxlength' => 255,
+ 'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_component.subject',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ ],
+ 'body_html' => [
+ 'name' => 'body_html',
+ 'type' => CRM_Utils_Type::T_TEXT,
+ 'title' => ts('Mailing Component Body HTML'),
+ 'description' => ts('Body of the component in html format.'),
+ 'rows' => 8,
+ 'cols' => 80,
+ 'where' => 'civicrm_mailing_component.body_html',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'TextArea',
+ ],
+ ],
+ 'body_text' => [
+ 'name' => 'body_text',
+ 'type' => CRM_Utils_Type::T_TEXT,
+ 'title' => ts('Body Text'),
+ 'description' => ts('Body of the component in text format.'),
+ 'rows' => 8,
+ 'cols' => 80,
+ 'where' => 'civicrm_mailing_component.body_text',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'TextArea',
+ ],
+ ],
+ 'is_default' => [
+ 'name' => 'is_default',
+ 'type' => CRM_Utils_Type::T_BOOLEAN,
+ 'title' => ts('Mailing Component is Default?'),
+ 'description' => ts('Is this the default component for this component_type?'),
+ 'where' => 'civicrm_mailing_component.is_default',
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ ],
+ 'is_active' => [
+ 'name' => 'is_active',
+ 'type' => CRM_Utils_Type::T_BOOLEAN,
+ 'title' => ts('Mailing Component Is Active?'),
+ 'description' => ts('Is this property active?'),
+ 'where' => 'civicrm_mailing_component.is_active',
+ 'table_name' => 'civicrm_mailing_component',
+ 'entity' => 'MailingComponent',
+ 'bao' => 'CRM_Mailing_BAO_MailingComponent',
+ 'localizable' => 0,
+ ],
+ ];
+ CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
+ }
+ return Civi::$statics[__CLASS__]['fields'];
+ }
+
+ /**
+ * Return a mapping from field-name to the corresponding key (as used in fields()).
+ *
+ * @return array
+ * Array(string $name => string $uniqueName).
+ */
+ public static function &fieldKeys() {
+ if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
+ Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
+ }
+ return Civi::$statics[__CLASS__]['fieldKeys'];
+ }
+
+ /**
+ * Returns the names of this table
+ *
+ * @return string
+ */
+ public static function getTableName() {
+ return self::$_tableName;
+ }
+
+ /**
+ * Returns if this table needs to be logged
+ *
+ * @return bool
+ */
+ public function getLog() {
+ return self::$_log;
+ }
+
+ /**
+ * Returns the list of fields that can be imported
+ *
+ * @param bool $prefix
+ *
+ * @return array
+ */
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_component', $prefix, []);
+ return $r;
+ }
+
+ /**
+ * Returns the list of fields that can be exported
+ *
+ * @param bool $prefix
+ *
+ * @return array
+ */
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_component', $prefix, []);
+ return $r;
+ }
+
+ /**
+ * Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
+ */
+ public static function indices($localize = TRUE) {
+ $indices = [];
+ return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
+ }
+
+}
diff --git a/CRM/Mailing/DAO/MailingGroup.php b/CRM/Mailing/DAO/MailingGroup.php
index acf0d827e27b..c645c1ac9a04 100644
--- a/CRM/Mailing/DAO/MailingGroup.php
+++ b/CRM/Mailing/DAO/MailingGroup.php
@@ -1,246 +1,243 @@
__table = 'civicrm_mailing_group';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mailing_id', 'civicrm_mailing', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mailing_id', 'civicrm_mailing', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Group ID') ,
- 'required' => true,
+ 'title' => ts('Mailing Group ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_group.id',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- ) ,
- 'mailing_id' => array(
+ ],
+ 'mailing_id' => [
'name' => 'mailing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing') ,
- 'description' => 'The ID of a previous mailing to include/exclude recipients.',
- 'required' => true,
+ 'title' => ts('Mailing'),
+ 'description' => ts('The ID of a previous mailing to include/exclude recipients.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_group.mailing_id',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_Mailing',
- ) ,
- 'group_type' => array(
+ ],
+ 'group_type' => [
'name' => 'group_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Group Type') ,
- 'description' => 'Are the members of the group included or excluded?.',
+ 'title' => ts('Mailing Group Type'),
+ 'description' => ts('Are the members of the group included or excluded?.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_mailing_group.group_type',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::getMailingGroupTypes',
- )
- ) ,
- 'entity_table' => array(
+ ],
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Group Entity Table') ,
- 'description' => 'Name of table where item being referenced is stored.',
- 'required' => true,
+ 'title' => ts('Mailing Group Entity Table'),
+ 'description' => ts('Name of table where item being referenced is stored.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_mailing_group.entity_table',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Mailing_BAO_Mailing::mailingGroupEntityTables',
- )
- ) ,
- 'entity_id' => array(
+ ],
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Group Entity') ,
- 'description' => 'Foreign key to the referenced item.',
- 'required' => true,
+ 'title' => ts('Mailing Group Entity'),
+ 'description' => ts('Foreign key to the referenced item.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_group.entity_id',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- ) ,
- 'search_id' => array(
+ ],
+ 'search_id' => [
'name' => 'search_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Group Search') ,
- 'description' => 'The filtering search. custom search id or -1 for civicrm api search',
+ 'title' => ts('Mailing Group Search'),
+ 'description' => ts('The filtering search. custom search id or -1 for civicrm api search'),
+ 'where' => 'civicrm_mailing_group.search_id',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- ) ,
- 'search_args' => array(
+ ],
+ 'search_args' => [
'name' => 'search_args',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Mailing Group Search Arguments') ,
- 'description' => 'The arguments to be sent to the search function',
+ 'title' => ts('Mailing Group Search Arguments'),
+ 'description' => ts('The arguments to be sent to the search function'),
+ 'where' => 'civicrm_mailing_group.search_args',
'table_name' => 'civicrm_mailing_group',
'entity' => 'MailingGroup',
'bao' => 'CRM_Mailing_DAO_MailingGroup',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -248,10 +245,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_group', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_group', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -259,15 +257,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_group', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_group', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/MailingJob.php b/CRM/Mailing/DAO/MailingJob.php
index ecdbe4705e77..265dca6c9f25 100644
--- a/CRM/Mailing/DAO/MailingJob.php
+++ b/CRM/Mailing/DAO/MailingJob.php
@@ -1,313 +1,322 @@
__table = 'civicrm_mailing_job';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mailing_id', 'civicrm_mailing', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_mailing_job', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mailing_id', 'civicrm_mailing', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_mailing_job', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Job ID') ,
- 'required' => true,
+ 'title' => ts('Mailing Job ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_job.id',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'mailing_id' => array(
+ ],
+ 'mailing_id' => [
'name' => 'mailing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing') ,
- 'description' => 'The ID of the mailing this Job will send.',
- 'required' => true,
+ 'title' => ts('Mailing'),
+ 'description' => ts('The ID of the mailing this Job will send.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_job.mailing_id',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_Mailing',
- ) ,
- 'scheduled_date' => array(
+ ],
+ 'scheduled_date' => [
'name' => 'scheduled_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Scheduled Date') ,
- 'description' => 'date on which this job was scheduled.',
- 'required' => false,
+ 'title' => ts('Mailing Scheduled Date'),
+ 'description' => ts('date on which this job was scheduled.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_job.scheduled_date',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'start_date' => array(
+ ],
+ 'mailing_job_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Job Start Date') ,
- 'description' => 'date on which this job was started.',
- 'required' => false,
+ 'title' => ts('Mailing Job Start Date'),
+ 'description' => ts('date on which this job was started.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_job.start_date',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'end_date' => array(
+ 'unique_title' => ts('Mailing Start Date'),
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Mailing Job End Date') ,
- 'description' => 'date on which this job ended.',
- 'required' => false,
+ 'title' => ts('Mailing Job End Date'),
+ 'description' => ts('date on which this job ended.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_job.end_date',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'status' => array(
+ ],
+ 'status' => [
'name' => 'status',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Job Status') ,
- 'description' => 'The state of this job',
+ 'title' => ts('Mailing Job Status'),
+ 'description' => ts('The state of this job'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_mailing_job.status',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::getMailingJobStatus',
- )
- ) ,
- 'is_test' => array(
+ ],
+ ],
+ 'is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Mailing Job Is Test?') ,
- 'description' => 'Is this job for a test mail?',
+ 'title' => ts('Mailing Job Is Test?'),
+ 'description' => ts('Is this job for a test mail?'),
+ 'where' => 'civicrm_mailing_job.is_test',
+ 'default' => '0',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'job_type' => array(
+ ],
+ 'job_type' => [
'name' => 'job_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Mailing Job Type') ,
- 'description' => 'Type of mailling job: null | child ',
+ 'title' => ts('Mailing Job Type'),
+ 'description' => ts('Type of mailling job: null | child '),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_mailing_job.job_type',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'parent_id' => array(
+ ],
+ 'parent_id' => [
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Job Parent') ,
- 'description' => 'Parent job id',
+ 'title' => ts('Mailing Job Parent'),
+ 'description' => ts('Parent job id'),
+ 'where' => 'civicrm_mailing_job.parent_id',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_MailingJob',
- ) ,
- 'job_offset' => array(
+ ],
+ 'job_offset' => [
'name' => 'job_offset',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Job Offset') ,
- 'description' => 'Offset of the child job',
+ 'title' => ts('Mailing Job Offset'),
+ 'description' => ts('Offset of the child job'),
+ 'where' => 'civicrm_mailing_job.job_offset',
+ 'default' => '0',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- 'job_limit' => array(
+ ],
+ 'job_limit' => [
'name' => 'job_limit',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Job Limit') ,
- 'description' => 'Queue size limit for each child job',
+ 'title' => ts('Mailing Job Limit'),
+ 'description' => ts('Queue size limit for each child job'),
+ 'where' => 'civicrm_mailing_job.job_limit',
+ 'default' => '0',
'table_name' => 'civicrm_mailing_job',
'entity' => 'MailingJob',
'bao' => 'CRM_Mailing_BAO_MailingJob',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -315,10 +324,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_job', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_job', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -326,15 +336,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_job', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_job', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/Recipients.php b/CRM/Mailing/DAO/Recipients.php
index 327369db4abf..f47f82da3549 100644
--- a/CRM/Mailing/DAO/Recipients.php
+++ b/CRM/Mailing/DAO/Recipients.php
@@ -1,207 +1,200 @@
__table = 'civicrm_mailing_recipients';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mailing_id', 'civicrm_mailing', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'email_id', 'civicrm_email', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'phone_id', 'civicrm_phone', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mailing_id', 'civicrm_mailing', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'email_id', 'civicrm_email', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'phone_id', 'civicrm_phone', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Recipients ID') ,
- 'required' => true,
+ 'title' => ts('Mailing Recipients ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_recipients.id',
'table_name' => 'civicrm_mailing_recipients',
'entity' => 'Recipients',
'bao' => 'CRM_Mailing_BAO_Recipients',
'localizable' => 0,
- ) ,
- 'mailing_id' => array(
+ ],
+ 'mailing_id' => [
'name' => 'mailing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing') ,
- 'description' => 'The ID of the mailing this Job will send.',
- 'required' => true,
+ 'title' => ts('Mailing'),
+ 'description' => ts('The ID of the mailing this Job will send.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_recipients.mailing_id',
'table_name' => 'civicrm_mailing_recipients',
'entity' => 'Recipients',
'bao' => 'CRM_Mailing_BAO_Recipients',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_Mailing',
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Recipient') ,
- 'description' => 'FK to Contact',
- 'required' => true,
+ 'title' => ts('Mailing Recipient'),
+ 'description' => ts('FK to Contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_recipients.contact_id',
'table_name' => 'civicrm_mailing_recipients',
'entity' => 'Recipients',
'bao' => 'CRM_Mailing_BAO_Recipients',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'email_id' => array(
+ ],
+ 'email_id' => [
'name' => 'email_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Recipient Email') ,
- 'description' => 'FK to Email',
+ 'title' => ts('Recipient Email'),
+ 'description' => ts('FK to Email'),
+ 'where' => 'civicrm_mailing_recipients.email_id',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_recipients',
'entity' => 'Recipients',
'bao' => 'CRM_Mailing_BAO_Recipients',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Email',
- ) ,
- 'phone_id' => array(
+ ],
+ 'phone_id' => [
'name' => 'phone_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Recipient Phone') ,
- 'description' => 'FK to Phone',
+ 'title' => ts('Recipient Phone'),
+ 'description' => ts('FK to Phone'),
+ 'where' => 'civicrm_mailing_recipients.phone_id',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_recipients',
'entity' => 'Recipients',
'bao' => 'CRM_Mailing_BAO_Recipients',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Phone',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -209,10 +202,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_recipients', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_recipients', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -220,15 +214,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_recipients', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_recipients', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/Spool.php b/CRM/Mailing/DAO/Spool.php
index f463bb7f9062..7b4de7e1f14d 100644
--- a/CRM/Mailing/DAO/Spool.php
+++ b/CRM/Mailing/DAO/Spool.php
@@ -1,234 +1,231 @@
__table = 'civicrm_mailing_spool';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'job_id', 'civicrm_mailing_job', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'job_id', 'civicrm_mailing_job', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Spool ID') ,
- 'required' => true,
+ 'title' => ts('Spool ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_spool.id',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- 'job_id' => array(
+ ],
+ 'job_id' => [
'name' => 'job_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Job') ,
- 'description' => 'The ID of the Job .',
- 'required' => true,
+ 'title' => ts('Mailing Job'),
+ 'description' => ts('The ID of the Job .'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_spool.job_id',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_MailingJob',
- ) ,
- 'recipient_email' => array(
+ ],
+ 'recipient_email' => [
'name' => 'recipient_email',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Recipient Email') ,
- 'description' => 'The email of the receipients this mail is to be sent.',
+ 'title' => ts('Recipient Email'),
+ 'description' => ts('The email of the receipients this mail is to be sent.'),
+ 'where' => 'civicrm_mailing_spool.recipient_email',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- 'headers' => array(
+ ],
+ 'headers' => [
'name' => 'headers',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Headers') ,
- 'description' => 'The header information of this mailing .',
+ 'title' => ts('Headers'),
+ 'description' => ts('The header information of this mailing .'),
+ 'where' => 'civicrm_mailing_spool.headers',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- 'body' => array(
+ ],
+ 'body' => [
'name' => 'body',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Body') ,
- 'description' => 'The body of this mailing.',
+ 'title' => ts('Body'),
+ 'description' => ts('The body of this mailing.'),
+ 'where' => 'civicrm_mailing_spool.body',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- 'added_at' => array(
+ ],
+ 'added_at' => [
'name' => 'added_at',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Added') ,
- 'description' => 'date on which this job was added.',
- 'required' => false,
+ 'title' => ts('Added'),
+ 'description' => ts('date on which this job was added.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_spool.added_at',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- 'removed_at' => array(
+ ],
+ 'removed_at' => [
'name' => 'removed_at',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Removed') ,
- 'description' => 'date on which this job was removed.',
- 'required' => false,
+ 'title' => ts('Removed'),
+ 'description' => ts('date on which this job was removed.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_mailing_spool.removed_at',
'default' => 'NULL',
'table_name' => 'civicrm_mailing_spool',
'entity' => 'Spool',
'bao' => 'CRM_Mailing_BAO_Spool',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -236,10 +233,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_spool', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_spool', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -247,15 +245,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_spool', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_spool', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/DAO/TrackableURL.php b/CRM/Mailing/DAO/TrackableURL.php
index 687cb86376a7..78867ac53af1 100644
--- a/CRM/Mailing/DAO/TrackableURL.php
+++ b/CRM/Mailing/DAO/TrackableURL.php
@@ -1,167 +1,156 @@
__table = 'civicrm_mailing_trackable_url';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mailing_id', 'civicrm_mailing', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mailing_id', 'civicrm_mailing', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Trackable URL ID') ,
- 'required' => true,
+ 'title' => ts('Trackable URL ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_trackable_url.id',
'table_name' => 'civicrm_mailing_trackable_url',
'entity' => 'TrackableURL',
'bao' => 'CRM_Mailing_BAO_TrackableURL',
'localizable' => 0,
- ) ,
- 'url' => array(
+ ],
+ 'url' => [
'name' => 'url',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Url') ,
- 'description' => 'The URL to be tracked.',
- 'required' => true,
+ 'title' => ts('Url'),
+ 'description' => ts('The URL to be tracked.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_trackable_url.url',
'table_name' => 'civicrm_mailing_trackable_url',
'entity' => 'TrackableURL',
'bao' => 'CRM_Mailing_BAO_TrackableURL',
'localizable' => 0,
- ) ,
- 'mailing_id' => array(
+ ],
+ 'mailing_id' => [
'name' => 'mailing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing') ,
- 'description' => 'FK to the mailing',
- 'required' => true,
+ 'title' => ts('Mailing'),
+ 'description' => ts('FK to the mailing'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_mailing_trackable_url.mailing_id',
'table_name' => 'civicrm_mailing_trackable_url',
'entity' => 'TrackableURL',
'bao' => 'CRM_Mailing_BAO_TrackableURL',
'localizable' => 0,
'FKClassName' => 'CRM_Mailing_DAO_Mailing',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -169,10 +158,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_trackable_url', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'mailing_trackable_url', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -180,15 +170,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_trackable_url', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'mailing_trackable_url', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Mailing/Event/BAO/Bounce.php b/CRM/Mailing/Event/BAO/Bounce.php
index ae9944f0b9ea..1f3c8ba8c24f 100644
--- a/CRM/Mailing/Event/BAO/Bounce.php
+++ b/CRM/Mailing/Event/BAO/Bounce.php
@@ -1,9 +1,9 @@
time_stamp = date('YmdHis');
+ $action = empty($params['id']) ? 'create' : 'edit';
+ CRM_Utils_Hook::pre($action, 'MailingEventBounce', CRM_Utils_Array::value('id', $params), $params);
+
// if we dont have a valid bounce type, we should set it
// to bounce_type_id 11 which is Syntax error. this allows such email
// addresses to be bounce a few more time before being put on hold
@@ -74,12 +77,21 @@ public static function create(&$params) {
}
}
+ // replace any invalid unicode characters with replacement characters
+ $params['bounce_reason'] = mb_convert_encoding($params['bounce_reason'], 'UTF-8', 'UTF-8');
+
+ // dev/mail#37 Replace 4-byte utf8 characaters with the unicode replacement character
+ // while CiviCRM does not support utf8mb4 for MySQL
+ $params['bounce_reason'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $params['bounce_reason']);
+
// CRM-11989
$params['bounce_reason'] = mb_strcut($params['bounce_reason'], 0, 254);
$bounce->copyValues($params);
$bounce->save();
+ CRM_Utils_Hook::post($action, 'MailingEventBounce', $bounce->id, $bounce);
+
if ($q->email_id) {
self::putEmailOnHold($q->email_id);
}
@@ -168,7 +180,7 @@ public static function &getRows(
$is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL
) {
- $dao = new CRM_Core_Dao();
+ $dao = new CRM_Core_DAO();
$bounce = self::getTableName();
$bounceType = CRM_Mailing_DAO_BounceType::getTableName();
diff --git a/CRM/Mailing/Event/BAO/Confirm.php b/CRM/Mailing/Event/BAO/Confirm.php
index 63f03d69567f..16b974429a9e 100644
--- a/CRM/Mailing/Event/BAO/Confirm.php
+++ b/CRM/Mailing/Event/BAO/Confirm.php
@@ -1,9 +1,9 @@
save();
CRM_Contact_BAO_GroupContact::addContactsToGroup(
- array($contact_id),
+ [$contact_id],
$se->group_id,
'Email',
'Added',
@@ -111,15 +111,13 @@ public static function confirm($contact_id, $subscribe_id, $hash) {
$group->id = $se->group_id;
$group->find(TRUE);
- $component = new CRM_Mailing_BAO_Component();
+ $component = new CRM_Mailing_BAO_MailingComponent();
$component->is_default = 1;
$component->is_active = 1;
$component->component_type = 'Welcome';
$component->find(TRUE);
- $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
-
$html = $component->body_html;
if ($component->body_text) {
@@ -140,17 +138,17 @@ public static function confirm($contact_id, $subscribe_id, $hash) {
$text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
$text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE);
- $mailParams = array(
+ $mailParams = [
'groupName' => 'Mailing Event ' . $component->component_type,
'subject' => $component->subject,
- 'from' => "\"$domainEmailName\" ' . implode('', $dataErrors) . '
' . ts('More information on tokens...') . '';
+ $errors['body_' . $type] = ts('The following errors were detected in %1 message:', [
+ 1 => $type,
+ ]) . '' . implode('', $dataErrors) . '
' . ts('More information on tokens...') . '';
}
}
return empty($errors) ? TRUE : $errors;
@@ -196,7 +194,7 @@ public static function dataRule($params, $files, $options) {
* mixed true or array of errors
*/
public static function formRule($params, $files, $options) {
- $errors = array();
+ $errors = [];
if (empty($params['body_text']) && empty($params['body_html'])) {
$errors['body_text'] = ts("Please provide either HTML or TEXT format for the Body.");
$errors['body_html'] = ts("Please provide either HTML or TEXT format for the Body.");
diff --git a/CRM/Mailing/Form/ForwardMailing.php b/CRM/Mailing/Form/ForwardMailing.php
index 83c212b7e438..3d7a04cf2c48 100644
--- a/CRM/Mailing/Form/ForwardMailing.php
+++ b/CRM/Mailing/Form/ForwardMailing.php
@@ -1,9 +1,9 @@
$mailing->subject)));
+ CRM_Utils_System::setTitle(ts('Forward Mailing: %1', [1 => $mailing->subject]));
$this->set('queue_id', $queue_id);
$this->set('job_id', $job_id);
@@ -73,28 +74,28 @@ public function preProcess() {
*/
public function buildQuickForm() {
for ($i = 0; $i < 5; $i++) {
- $this->add('text', "email_$i", ts('Email %1', array(1 => $i + 1)));
+ $this->add('text', "email_$i", ts('Email %1', [1 => $i + 1]));
$this->addRule("email_$i", ts('Email is not valid.'), 'email');
}
//insert message Text by selecting "Select Template option"
- $this->add('textarea', 'forward_comment', ts('Comment'), array('cols' => '80', 'rows' => '8'));
+ $this->add('textarea', 'forward_comment', ts('Comment'), ['cols' => '80', 'rows' => '8']);
$this->add('wysiwyg', 'html_comment',
ts('HTML Message'),
- array('cols' => '80', 'rows' => '8')
+ ['cols' => '80', 'rows' => '8']
);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Forward'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -107,12 +108,12 @@ public function postProcess() {
$timeStamp = date('YmdHis');
$formValues = $this->controller->exportValues($this->_name);
- $params = array();
+ $params = [];
$params['body_text'] = $formValues['forward_comment'];
$html_comment = $formValues['html_comment'];
$params['body_html'] = str_replace('%7B', '{', str_replace('%7D', '}', $html_comment));
- $emails = array();
+ $emails = [];
for ($i = 0; $i < 5; $i++) {
$email = $this->controller->exportValue($this->_name, "email_$i");
if (!empty($email)) {
@@ -122,7 +123,7 @@ public function postProcess() {
$forwarded = NULL;
foreach ($emails as $email) {
- $params = array(
+ $params = [
'version' => 3,
'job_id' => $job_id,
'event_queue_id' => $queue_id,
@@ -131,22 +132,22 @@ public function postProcess() {
'time_stamp' => $timeStamp,
'fromEmail' => $this->_fromEmail,
'params' => $params,
- );
+ ];
$result = civicrm_api('Mailing', 'event_forward', $params);
if (!civicrm_error($result)) {
$forwarded++;
}
}
- $status = ts('Mailing is not forwarded to the given email address.', array(
- 'count' => count($emails),
- 'plural' => 'Mailing is not forwarded to the given email addresses.',
- ));
+ $status = ts('Mailing is not forwarded to the given email address.', [
+ 'count' => count($emails),
+ 'plural' => 'Mailing is not forwarded to the given email addresses.',
+ ]);
if ($forwarded) {
- $status = ts('Mailing is forwarded successfully to %count email address.', array(
- 'count' => $forwarded,
- 'plural' => 'Mailing is forwarded successfully to %count email addresses.',
- ));
+ $status = ts('Mailing is forwarded successfully to %count email address.', [
+ 'count' => $forwarded,
+ 'plural' => 'Mailing is forwarded successfully to %count email addresses.',
+ ]);
}
CRM_Utils_System::setUFMessage($status);
diff --git a/CRM/Mailing/Form/Optout.php b/CRM/Mailing/Form/Optout.php
index 7fe3d2b2aecb..7473fe3af3bc 100644
--- a/CRM/Mailing/Form/Optout.php
+++ b/CRM/Mailing/Form/Optout.php
@@ -1,9 +1,9 @@
add('text', 'email_confirm', ts('Verify email address to opt out:'));
$this->addRule('email_confirm', ts('Email address is required to opt out.'), 'required');
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => ts('Opt Out'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -106,19 +106,18 @@ public function postProcess() {
}
$statusMsg = ts('Email: %1 has been successfully opted out',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
CRM_Core_Session::setStatus($statusMsg, '', 'success');
}
elseif ($result == FALSE) {
// Email address not verified
-
$statusMsg = ts('The email address: %1 you have entered does not match the email associated with this opt out request.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
}
diff --git a/CRM/Mailing/Form/Search.php b/CRM/Mailing/Form/Search.php
index 3c9b6b0fa083..6c03b4e9ef0d 100644
--- a/CRM/Mailing/Form/Search.php
+++ b/CRM/Mailing/Form/Search.php
@@ -1,9 +1,9 @@
_sms) ? ts('SMS Date') : ts('Mailing Date');
+ $this->addDatePickerRange('mailing', $dateFieldLabel);
$this->add('text', 'sort_name', ts('Created or Sent by'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
@@ -64,7 +65,7 @@ public function buildQuickForm() {
$enabledLanguages = CRM_Core_I18n::languages(TRUE);
if (count($enabledLanguages) > 1) {
- $this->addElement('select', 'language', ts('Language'), array('' => ts('- all languages -')) + $enabledLanguages, array('class' => 'crm-select2'));
+ $this->addElement('select', 'language', ts('Language'), ['' => ts('- all languages -')] + $enabledLanguages, ['class' => 'crm-select2']);
}
if ($parent->_sms) {
@@ -72,27 +73,27 @@ public function buildQuickForm() {
}
$this->add('hidden', 'hidden_find_mailings', 1);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
/**
* @return array
*/
public function setDefaultValues() {
- $defaults = $statusVals = array();
+ $defaults = $statusVals = [];
$parent = $this->controller->getParent();
if ($parent->get('unscheduled')) {
$defaults['status_unscheduled'] = 1;
}
if ($parent->get('scheduled')) {
- $statusVals = array('Scheduled', 'Complete', 'Running', 'Canceled');
+ $statusVals = array_keys(CRM_Core_SelectValues::getMailingJobStatus());
$defaults['is_archived'] = 0;
}
if ($parent->get('archived')) {
@@ -111,14 +112,20 @@ public function setDefaultValues() {
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
- CRM_Contact_BAO_Query::fixDateValues($params["mailing_relative"], $params['mailing_from'], $params['mailing_to']);
+ if (!empty($params['mailing_relative'])) {
+ list($params['mailing_low'], $params['mailing_high']) = CRM_Utils_Date::getFromTo($params['mailing_relative'], $params['mailing_low'], $params['mailing_high']);
+ unset($params['mailing_relative']);
+ }
+ elseif (!empty($params['mailing_high'])) {
+ $params['mailing_high'] .= ' ' . '23:59:59';
+ }
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array(
+ $fields = [
'mailing_name',
- 'mailing_from',
- 'mailing_to',
+ 'mailing_low',
+ 'mailing_high',
'sort_name',
'campaign_id',
'mailing_status',
@@ -127,22 +134,12 @@ public function postProcess() {
'is_archived',
'language',
'hidden_find_mailings',
- );
+ ];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
- if (in_array($field, array(
- 'mailing_from',
- 'mailing_to',
- )) && !$params["mailing_relative"]
- ) {
- $time = ($field == 'mailing_to') ? '235959' : NULL;
- $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
- }
- else {
- $parent->set($field, $params[$field]);
- }
+ $parent->set($field, $params[$field]);
}
else {
$parent->set($field, NULL);
diff --git a/CRM/Mailing/Form/Subscribe.php b/CRM/Mailing/Form/Subscribe.php
index dbe9ad5a4f06..56e34f1e2691 100644
--- a/CRM/Mailing/Form/Subscribe.php
+++ b/CRM/Mailing/Form/Subscribe.php
@@ -1,9 +1,9 @@
fetch()) {
$this->assign('groupName', $dao->title);
- CRM_Utils_System::setTitle(ts('Subscribe to Mailing List - %1', array(1 => $dao->title)));
+ CRM_Utils_System::setTitle(ts('Subscribe to Mailing List - %1', [1 => $dao->title]));
}
else {
CRM_Core_Error::statusBounce("The specified group is not configured for this action OR The group doesn't exist.");
@@ -101,9 +101,9 @@ public function buildQuickForm() {
AND $groupTypeCondition
ORDER BY title";
$dao = CRM_Core_DAO::executeQuery($query);
- $rows = array();
+ $rows = [];
while ($dao->fetch()) {
- $row = array();
+ $row = [];
$row['id'] = $dao->id;
$row['title'] = $dao->title;
$row['description'] = $dao->description;
@@ -118,7 +118,7 @@ public function buildQuickForm() {
CRM_Core_Error::fatal(ts('There are no public mailing list groups to display.'));
}
$this->assign('rows', $rows);
- $this->addFormRule(array('CRM_Mailing_Form_Subscribe', 'formRule'));
+ $this->addFormRule(['CRM_Mailing_Form_Subscribe', 'formRule']);
}
$addCaptcha = TRUE;
@@ -147,24 +147,20 @@ public function buildQuickForm() {
}
if ($addCaptcha) {
- // add captcha
- $captcha = CRM_Utils_ReCAPTCHA::singleton();
- $captcha->add($this);
- $this->assign('isCaptcha', TRUE);
+ CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Subscribe'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Subscribe'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -178,13 +174,13 @@ public static function formRule($fields) {
return TRUE;
}
}
- return array('_qf_default' => 'Please select one or more mailing lists.');
+ return ['_qf_default' => 'Please select one or more mailing lists.'];
}
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
- $groups = array();
+ $groups = [];
if ($this->_groupID) {
$groups[] = $this->_groupID;
}
diff --git a/CRM/Mailing/Form/Task.php b/CRM/Mailing/Form/Task.php
index 3b0f9acf240e..edd13fb523c2 100644
--- a/CRM/Mailing/Form/Task.php
+++ b/CRM/Mailing/Form/Task.php
@@ -1,9 +1,9 @@
controller->exportValues($form->get('searchFormName'));
$form->_task = CRM_Utils_Array::value('task', $values);
@@ -76,7 +55,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->assign('taskName', CRM_Utils_Array::value('task', $values));
// ids are mailing event queue ids
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -136,18 +115,17 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Mailing/Form/Task/AdhocMailing.php b/CRM/Mailing/Form/Task/AdhocMailing.php
index 6a06b30e867f..f08cf4993984 100644
--- a/CRM/Mailing/Form/Task/AdhocMailing.php
+++ b/CRM/Mailing/Form/Task/AdhocMailing.php
@@ -1,9 +1,9 @@
createHiddenGroup();
- $mailing = civicrm_api3('Mailing', 'create', array(
+ $mailing = civicrm_api3('Mailing', 'create', [
'name' => "",
'campaign_id' => NULL,
'replyto_email' => "",
'template_type' => $templateTypes[0]['name'],
- 'template_options' => array('nonce' => 1),
+ 'template_options' => ['nonce' => 1],
'subject' => "",
'body_html' => "",
'body_text' => "",
- 'groups' => array(
- 'include' => array($groupId),
- 'exclude' => array(),
- 'base' => array(),
- ),
- 'mailings' => array(
- 'include' => array(),
- 'exclude' => array(),
- ),
- ));
+ 'groups' => [
+ 'include' => [$groupId],
+ 'exclude' => [],
+ 'base' => [],
+ ],
+ 'mailings' => [
+ 'include' => [],
+ 'exclude' => [],
+ ],
+ ]);
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/a/', NULL, TRUE, '/mailing/' . $mailing['id']));
}
diff --git a/CRM/Mailing/Form/Task/Print.php b/CRM/Mailing/Form/Task/Print.php
index 206b92f1a289..0d1322edd4f6 100644
--- a/CRM/Mailing/Form/Task/Print.php
+++ b/CRM/Mailing/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Mailing Recipients'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Mailing Recipients'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Mailing/Form/Unsubscribe.php b/CRM/Mailing/Form/Unsubscribe.php
index a638a2f70fa5..33cee130f289 100644
--- a/CRM/Mailing/Form/Unsubscribe.php
+++ b/CRM/Mailing/Form/Unsubscribe.php
@@ -1,9 +1,9 @@
$email)
+ [1 => $email]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
$this->assign('groupExist', $groupExist);
@@ -85,17 +85,17 @@ public function buildQuickForm() {
$this->add('text', 'email_confirm', ts('Verify email address to unsubscribe:'));
$this->addRule('email_confirm', ts('Email address is required to unsubscribe.'), 'required');
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => ts('Unsubscribe'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -116,26 +116,25 @@ public function postProcess() {
if ($result == TRUE) {
// Email address verified
-
$groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job_id, $queue_id, $hash);
+
if (count($groups)) {
CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue_id, $groups, FALSE, $job_id);
}
$statusMsg = ts('Email: %1 has been successfully unsubscribed from this Mailing List/Group.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
CRM_Core_Session::setStatus($statusMsg, '', 'success');
}
elseif ($result == FALSE) {
// Email address not verified
-
$statusMsg = ts('The email address: %1 you have entered does not match the email associated with this unsubscribe request.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
diff --git a/CRM/Mailing/Info.php b/CRM/Mailing/Info.php
index f902b526c7fc..a674129e54aa 100644
--- a/CRM/Mailing/Info.php
+++ b/CRM/Mailing/Info.php
@@ -1,9 +1,9 @@
'CiviMail',
'translatedName' => ts('CiviMail'),
'title' => ts('CiviCRM Mailing Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -69,128 +69,99 @@ public function getAngularModules() {
&& !CRM_Core_Permission::check('schedule mailings')
&& !CRM_Core_Permission::check('approve mailings')
) {
- return array();
+ return [];
}
+ global $civicrm_root;
- $reportIds = array();
- $reportTypes = array('detail', 'opened', 'bounce', 'clicks');
+ $reportIds = [];
+ $reportTypes = ['detail', 'opened', 'bounce', 'clicks'];
foreach ($reportTypes as $report) {
- $result = civicrm_api3('ReportInstance', 'get', array(
+ $result = civicrm_api3('ReportInstance', 'get', [
'sequential' => 1,
- 'report_id' => 'mailing/' . $report));
- $reportIds[$report] = $result['values'][0]['id'];
+ 'report_id' => 'mailing/' . $report,
+ ]);
+ if (!empty($result['values'])) {
+ $reportIds[$report] = $result['values'][0]['id'];
+ }
}
- $result = array();
- $result['crmMailing'] = array(
- 'ext' => 'civicrm',
- 'js' => array(
- 'ang/crmMailing.js',
- 'ang/crmMailing/*.js',
- ),
- 'css' => array('ang/crmMailing.css'),
- 'partials' => array('ang/crmMailing'),
- );
- $result['crmMailingAB'] = array(
- 'ext' => 'civicrm',
- 'js' => array(
- 'ang/crmMailingAB.js',
- 'ang/crmMailingAB/*.js',
- 'ang/crmMailingAB/*/*.js',
- ),
- 'css' => array('ang/crmMailingAB.css'),
- 'partials' => array('ang/crmMailingAB'),
- );
- $result['crmD3'] = array(
- 'ext' => 'civicrm',
- 'js' => array(
- 'ang/crmD3.js',
- 'bower_components/d3/d3.min.js',
- ),
- );
+ $result = [];
+ $result['crmMailing'] = include "$civicrm_root/ang/crmMailing.ang.php";
+ $result['crmMailingAB'] = include "$civicrm_root/ang/crmMailingAB.ang.php";
+ $result['crmD3'] = include "$civicrm_root/ang/crmD3.ang.php";
$config = CRM_Core_Config::singleton();
$session = CRM_Core_Session::singleton();
$contactID = $session->get('userID');
- // Get past mailings.
- // CRM-16155 - Limit to a reasonable number.
- $civiMails = civicrm_api3('Mailing', 'get', array(
- 'is_completed' => 1,
- 'mailing_type' => array('IN' => array('standalone', 'winner')),
- 'domain_id' => CRM_Core_Config::domainID(),
- 'return' => array('id', 'name', 'scheduled_date'),
- 'sequential' => 1,
- 'options' => array(
- 'limit' => 500,
- 'sort' => 'is_archived asc, scheduled_date desc',
- ),
- ));
// Generic params.
- $params = array(
- 'options' => array('limit' => 0),
+ $params = [
+ 'options' => ['limit' => 0],
'sequential' => 1,
- );
-
- $groupNames = civicrm_api3('Group', 'get', $params + array(
+ ];
+ $groupNames = civicrm_api3('Group', 'get', $params + [
'is_active' => 1,
'check_permissions' => TRUE,
- 'return' => array('title', 'visibility', 'group_type', 'is_hidden'),
- ));
- $headerfooterList = civicrm_api3('MailingComponent', 'get', $params + array(
+ 'return' => ['title', 'visibility', 'group_type', 'is_hidden'],
+ ]);
+ $headerfooterList = civicrm_api3('MailingComponent', 'get', $params + [
'is_active' => 1,
- 'return' => array('name', 'component_type', 'is_default', 'body_html', 'body_text'),
- ));
+ 'return' => ['name', 'component_type', 'is_default', 'body_html', 'body_text'],
+ ]);
- $emailAdd = civicrm_api3('Email', 'get', array(
+ $emailAdd = civicrm_api3('Email', 'get', [
'sequential' => 1,
'return' => "email",
'contact_id' => $contactID,
- ));
+ ]);
- $mesTemplate = civicrm_api3('MessageTemplate', 'get', $params + array(
+ $mesTemplate = civicrm_api3('MessageTemplate', 'get', $params + [
'sequential' => 1,
'is_active' => 1,
- 'return' => array("id", "msg_title"),
- 'workflow_id' => array('IS NULL' => ""),
- ));
- $mailTokens = civicrm_api3('Mailing', 'gettokens', array(
- 'entity' => array('contact', 'mailing'),
+ 'return' => ["id", "msg_title"],
+ 'workflow_id' => ['IS NULL' => ""],
+ ]);
+ $mailTokens = civicrm_api3('Mailing', 'gettokens', [
+ 'entity' => ['contact', 'mailing'],
'sequential' => 1,
- ));
- $fromAddress = civicrm_api3('OptionValue', 'get', $params + array(
+ ]);
+ $fromAddress = civicrm_api3('OptionValue', 'get', $params + [
'option_group_id' => "from_email_address",
'domain_id' => CRM_Core_Config::domainID(),
- ));
+ ]);
$enabledLanguages = CRM_Core_I18n::languages(TRUE);
$isMultiLingual = (count($enabledLanguages) > 1);
+ // FlexMailer is a refactoring of CiviMail which provides new hooks/APIs/docs. If the sysadmin has opted to enable it, then use that instead of CiviMail.
+ $requiredTokens = defined('CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS') ? Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS, []) : CRM_Utils_Token::getRequiredTokens();
CRM_Core_Resources::singleton()
- ->addSetting(array(
- 'crmMailing' => array(
+ ->addSetting([
+ 'crmMailing' => [
'templateTypes' => CRM_Mailing_BAO_Mailing::getTemplateTypes(),
- 'civiMails' => $civiMails['values'],
+ 'civiMails' => [],
'campaignEnabled' => in_array('CiviCampaign', $config->enableComponents),
- 'groupNames' => $groupNames['values'],
+ 'groupNames' => [],
+ // @todo this is not used in core. Remove once Mosaico no longer depends on it.
+ 'testGroupNames' => $groupNames['values'],
'headerfooterList' => $headerfooterList['values'],
'mesTemplate' => $mesTemplate['values'],
'emailAdd' => $emailAdd['values'],
'mailTokens' => $mailTokens['values'],
'contactid' => $contactID,
- 'requiredTokens' => CRM_Utils_Token::getRequiredTokens(),
+ 'requiredTokens' => $requiredTokens,
'enableReplyTo' => (int) Civi::settings()->get('replyTo'),
'disableMandatoryTokensCheck' => (int) Civi::settings()->get('disable_mandatory_tokens_check'),
'fromAddress' => $fromAddress['values'],
- 'defaultTestEmail' => civicrm_api3('Contact', 'getvalue', array(
- 'id' => 'user_contact_id',
- 'return' => 'email',
- )),
+ 'defaultTestEmail' => civicrm_api3('Contact', 'getvalue', [
+ 'id' => 'user_contact_id',
+ 'return' => 'email',
+ ]),
'visibility' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::groupVisibility()),
'workflowEnabled' => CRM_Mailing_Info::workflowEnabled(),
'reportIds' => $reportIds,
'enabledLanguages' => $enabledLanguages,
'isMultiLingual' => $isMultiLingual,
- ),
- ))
- ->addPermissions(array(
+ ],
+ ])
+ ->addPermissions([
'view all contacts',
'edit all contacts',
'access CiviMail',
@@ -199,7 +170,7 @@ public function getAngularModules() {
'approve mailings',
'delete in CiviMail',
'edit message templates',
- ));
+ ]);
return $result;
}
@@ -237,33 +208,33 @@ public static function workflowEnabled() {
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviMail' => array(
+ $permissions = [
+ 'access CiviMail' => [
ts('access CiviMail'),
- ),
- 'access CiviMail subscribe/unsubscribe pages' => array(
+ ],
+ 'access CiviMail subscribe/unsubscribe pages' => [
ts('access CiviMail subscribe/unsubscribe pages'),
ts('Subscribe/unsubscribe from mailing list group'),
- ),
- 'delete in CiviMail' => array(
+ ],
+ 'delete in CiviMail' => [
ts('delete in CiviMail'),
ts('Delete Mailing'),
- ),
- 'view public CiviMail content' => array(
+ ],
+ 'view public CiviMail content' => [
ts('view public CiviMail content'),
- ),
- );
+ ],
+ ];
if (self::workflowEnabled() || $getAllUnconditionally) {
- $permissions['create mailings'] = array(
+ $permissions['create mailings'] = [
ts('create mailings'),
- );
- $permissions['schedule mailings'] = array(
+ ];
+ $permissions['schedule mailings'] = [
ts('schedule mailings'),
- );
- $permissions['approve mailings'] = array(
+ ];
+ $permissions['approve mailings'] = [
ts('approve mailings'),
- );
+ ];
}
if (!$descriptions) {
@@ -275,7 +246,6 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
return $permissions;
}
-
/**
* @inheritDoc
* @return null
@@ -298,12 +268,20 @@ public function getUserDashboardObject() {
* @return array
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Mailings'),
'id' => 'mailing',
'url' => 'mailing',
'weight' => 45,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-envelope-o';
}
/**
@@ -311,10 +289,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Mailings'),
'weight' => 20,
- );
+ ];
}
/**
diff --git a/CRM/Mailing/MailStore.php b/CRM/Mailing/MailStore.php
index 3bec5d9aec45..86b79c38b3f8 100644
--- a/CRM/Mailing/MailStore.php
+++ b/CRM/Mailing/MailStore.php
@@ -1,9 +1,9 @@
_debug) {
print "got to the end of the mailbox\n";
}
- return array();
+ return [];
}
- $mails = array();
+ $mails = [];
$parser = new ezcMailParser();
//set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
@@ -152,11 +155,11 @@ public function fetchNext($count = 1) {
public function maildir($name) {
$config = CRM_Core_Config::singleton();
$dir = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $name;
- foreach (array(
- 'cur',
- 'new',
- 'tmp',
- ) as $sub) {
+ foreach ([
+ 'cur',
+ 'new',
+ 'tmp',
+ ] as $sub) {
if (!file_exists($dir . DIRECTORY_SEPARATOR . $sub)) {
if ($this->_debug) {
print "creating $dir/$sub\n";
diff --git a/CRM/Mailing/MailStore/Imap.php b/CRM/Mailing/MailStore/Imap.php
index dc918f1d6df7..a805ee43a222 100644
--- a/CRM/Mailing/MailStore/Imap.php
+++ b/CRM/Mailing/MailStore/Imap.php
@@ -1,9 +1,9 @@
$ssl, 'uidReferencing' => TRUE);
+ $options = ['ssl' => $ssl, 'uidReferencing' => TRUE];
$this->_transport = new ezcMailImapTransport($host, NULL, $options);
$this->_transport->authenticate($username, $password);
$this->_transport->selectMailbox($folder);
- $this->_ignored = implode($this->_transport->getHierarchyDelimiter(), array($folder, 'CiviMail', 'ignored'));
- $this->_processed = implode($this->_transport->getHierarchyDelimiter(), array($folder, 'CiviMail', 'processed'));
+ $this->_ignored = implode($this->_transport->getHierarchyDelimiter(), [$folder, 'CiviMail', 'ignored']);
+ $this->_processed = implode($this->_transport->getHierarchyDelimiter(), [$folder, 'CiviMail', 'processed']);
$boxes = $this->_transport->listMailboxes();
if ($this->_debug) {
diff --git a/CRM/Mailing/MailStore/Localdir.php b/CRM/Mailing/MailStore/Localdir.php
index c00cf3adeaf9..8e9c66f1c813 100644
--- a/CRM/Mailing/MailStore/Localdir.php
+++ b/CRM/Mailing/MailStore/Localdir.php
@@ -1,9 +1,9 @@
_dir = $dir;
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
@@ -72,7 +72,7 @@ public function __construct($dir) {
* array of ezcMail objects
*/
public function fetchNext($count = 0) {
- $mails = array();
+ $mails = [];
$path = rtrim($this->_dir, DIRECTORY_SEPARATOR);
if ($this->_debug) {
@@ -95,7 +95,7 @@ public function fetchNext($count = 0) {
print "retrieving message $file\n";
}
- $set = new ezcMailFileSet(array($file));
+ $set = new ezcMailFileSet([$file]);
$parser = new ezcMailParser();
// set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
@@ -104,7 +104,7 @@ public function fetchNext($count = 0) {
if (!$mail) {
return CRM_Core_Error::createAPIError(ts('%1 could not be parsed',
- array(1 => $file)
+ [1 => $file]
));
}
$mails[$file] = $mail[0];
diff --git a/CRM/Mailing/MailStore/Maildir.php b/CRM/Mailing/MailStore/Maildir.php
index 7a1aeef4f4fa..90b371026ed4 100644
--- a/CRM/Mailing/MailStore/Maildir.php
+++ b/CRM/Mailing/MailStore/Maildir.php
@@ -1,9 +1,9 @@
_dir = $dir;
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
@@ -72,15 +72,15 @@ public function __construct($dir) {
* array of ezcMail objects
*/
public function fetchNext($count = 0) {
- $mails = array();
+ $mails = [];
$parser = new ezcMailParser();
// set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
- foreach (array(
- 'cur',
- 'new',
- ) as $subdir) {
+ foreach ([
+ 'cur',
+ 'new',
+ ] as $subdir) {
$dir = $this->_dir . DIRECTORY_SEPARATOR . $subdir;
foreach (scandir($dir) as $file) {
if ($file == '.' or $file == '..') {
@@ -94,7 +94,7 @@ public function fetchNext($count = 0) {
}
- $set = new ezcMailFileSet(array($path));
+ $set = new ezcMailFileSet([$path]);
$single = $parser->parseMail($set);
$mails[$path] = $single[0];
}
diff --git a/CRM/Mailing/MailStore/Mbox.php b/CRM/Mailing/MailStore/Mbox.php
index cda2dc234ea8..6ffadf4166e8 100644
--- a/CRM/Mailing/MailStore/Mbox.php
+++ b/CRM/Mailing/MailStore/Mbox.php
@@ -1,9 +1,9 @@
_leftToProcess = count($this->_transport->listMessages());
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
diff --git a/CRM/Mailing/MailStore/Pop3.php b/CRM/Mailing/MailStore/Pop3.php
index c0a8b98a1c40..c552c3e18c7b 100644
--- a/CRM/Mailing/MailStore/Pop3.php
+++ b/CRM/Mailing/MailStore/Pop3.php
@@ -1,9 +1,9 @@
$ssl);
+ $options = ['ssl' => $ssl];
$this->_transport = new ezcMailPop3Transport($host, NULL, $options);
$this->_transport->authenticate($username, $password);
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
diff --git a/CRM/Mailing/Page/AJAX.php b/CRM/Mailing/Page/AJAX.php
index 0b493a6c08b4..c2586c25071f 100644
--- a/CRM/Mailing/Page/AJAX.php
+++ b/CRM/Mailing/Page/AJAX.php
@@ -1,9 +1,9 @@
selectAdd();
$messageTemplate->selectAdd('msg_text, msg_html, msg_subject, pdf_format_id');
$messageTemplate->find(TRUE);
- $messages = array(
+ $messages = [
'subject' => $messageTemplate->msg_subject,
'msg_text' => $messageTemplate->msg_text,
'msg_html' => $messageTemplate->msg_html,
'pdf_format_id' => $messageTemplate->pdf_format_id,
- );
+ ];
$documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $templateId);
foreach ((array) $documentInfo as $info) {
@@ -67,7 +67,7 @@ public static function template() {
*/
public static function getContactMailings() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
- $params += CRM_Core_Page_AJAX::validateParams(array('contact_id' => 'Integer'));
+ $params += CRM_Core_Page_AJAX::validateParams(['contact_id' => 'Integer']);
// get the contact mailings
$mailings = CRM_Mailing_BAO_Mailing::getContactMailingSelector($params);
diff --git a/CRM/Mailing/Page/Browse.php b/CRM/Mailing/Page/Browse.php
index d9b59a46510c..abb1428e2aae 100644
--- a/CRM/Mailing/Page/Browse.php
+++ b/CRM/Mailing/Page/Browse.php
@@ -1,9 +1,9 @@
_unscheduled = $this->_archived = $archiveLinks = FALSE;
$this->_mailingId = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
$this->_sms = CRM_Utils_Request::retrieve('sms', 'Positive', $this);
+
+ if ($this->_sms) {
+ // if this is an SMS page, check that the user has permission to browse SMS
+ if (!CRM_Core_Permission::check('send SMS')) {
+ CRM_Core_Error::fatal(ts('You do not have permission to send SMS'));
+ }
+ }
+ else {
+ // If this is not an SMS page, check that the user has an appropriate
+ // permission (specific permissions have been copied from
+ // CRM/Mailing/xml/Menu/Mailing.xml)
+ if (!CRM_Core_Permission::check([['access CiviMail', 'approve mailings', 'create mailings', 'schedule mailings']])) {
+ CRM_Core_Error::fatal(ts('You do not have permission to view this page.'));
+ }
+ }
+
$this->assign('sms', $this->_sms);
// check that the user has permission to access mailing id
CRM_Mailing_BAO_Mailing::checkPermission($this->_mailingId);
@@ -165,6 +181,7 @@ public function run() {
if ($this->_action & CRM_Core_Action::DISABLE) {
if (CRM_Utils_Request::retrieve('confirmed', 'Boolean', $this)) {
CRM_Mailing_BAO_MailingJob::cancel($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
CRM_Utils_System::redirect($context);
}
else {
@@ -176,6 +193,22 @@ public function run() {
$controller->run();
}
}
+ elseif ($this->_action & CRM_Core_Action::CLOSE) {
+ if (!CRM_Core_Permission::checkActionPermission('CiviMail', CRM_Core_Action::CLOSE)) {
+ CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ }
+ CRM_Mailing_BAO_MailingJob::pause($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been paused. Active message deliveries may continue for a few minutes, but CiviMail will not begin delivery of any more batches.'), ts('Paused'), 'success');
+ CRM_Utils_System::redirect($context);
+ }
+ elseif ($this->_action & CRM_Core_Action::REOPEN) {
+ if (!CRM_Core_Permission::checkActionPermission('CiviMail', CRM_Core_Action::CLOSE)) {
+ CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ }
+ CRM_Mailing_BAO_MailingJob::resume($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been resumed.'), ts('Resumed'), 'success');
+ CRM_Utils_System::redirect($context);
+ }
elseif ($this->_action & CRM_Core_Action::DELETE) {
if (CRM_Utils_Request::retrieve('confirmed', 'Boolean', $this)) {
@@ -304,18 +337,18 @@ public function search() {
* @return string
*/
public function whereClause(&$params, $sortBy = TRUE) {
- $values = array();
+ $values = [];
- $clauses = array();
+ $clauses = [];
$title = $this->get('mailing_name');
// echo " name=$title ";
if ($title) {
$clauses[] = 'name LIKE %1';
if (strpos($title, '%') !== FALSE) {
- $params[1] = array($title, 'String', FALSE);
+ $params[1] = [$title, 'String', FALSE];
}
else {
- $params[1] = array($title, 'String', TRUE);
+ $params[1] = [$title, 'String', TRUE];
}
}
@@ -328,7 +361,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
$campainIds = $this->get('campaign_id');
if (!CRM_Utils_System::isNull($campainIds)) {
if (!is_array($campainIds)) {
- $campaignIds = array($campaignIds);
+ $campaignIds = [$campaignIds];
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campainIds)) . ' ) )';
}
diff --git a/CRM/Mailing/Page/Common.php b/CRM/Mailing/Page/Common.php
index 51fa8b2661f1..f420a0698ce3 100644
--- a/CRM/Mailing/Page/Common.php
+++ b/CRM/Mailing/Page/Common.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=update&id=%%id%%',
'title' => ts('Edit Mailing Component'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Mailing Component'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Mailing Component'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
diff --git a/CRM/Mailing/Page/Confirm.php b/CRM/Mailing/Page/Confirm.php
index b58fbc9028de..b126dac4281f 100644
--- a/CRM/Mailing/Page/Confirm.php
+++ b/CRM/Mailing/Page/Confirm.php
@@ -1,9 +1,9 @@
getVars($options, "CRM_Mailing_Controller_Send_$qfKey");
// get the options if control come from search context, CRM-3711
@@ -74,7 +74,7 @@ public function run() {
// get details of contact with token value including Custom Field Token Values.CRM-3734
$returnProperties = $mailing->getReturnProperties();
- $params = array('contact_id' => $session->get('userID'));
+ $params = ['contact_id' => $session->get('userID')];
$details = CRM_Utils_Token::getTokenDetails($params,
$returnProperties,
diff --git a/CRM/Mailing/Page/Report.php b/CRM/Mailing/Page/Report.php
index 8c01fed87b60..628672a01ede 100644
--- a/CRM/Mailing/Page/Report.php
+++ b/CRM/Mailing/Page/Report.php
@@ -1,9 +1,9 @@
assign('report', $report);
CRM_Utils_System::setTitle(ts('CiviMail Report: %1',
- array(1 => $report['mailing']['name'])
+ [1 => $report['mailing']['name']]
));
$this->assign('public_url', CRM_Mailing_BAO_Mailing::getPublicViewUrl($this->_mailing_id));
diff --git a/CRM/Mailing/Page/Resubscribe.php b/CRM/Mailing/Page/Resubscribe.php
index d950dd84f12c..8df64a00b9a6 100644
--- a/CRM/Mailing/Page/Resubscribe.php
+++ b/CRM/Mailing/Page/Resubscribe.php
@@ -1,9 +1,9 @@
$displayName)));
+ CRM_Utils_System::setTitle(ts('Mailings sent to %1', [1 => $displayName]));
}
/**
diff --git a/CRM/Mailing/Page/Unsubscribe.php b/CRM/Mailing/Page/Unsubscribe.php
index 61be1a0672ac..34da7195d930 100644
--- a/CRM/Mailing/Page/Unsubscribe.php
+++ b/CRM/Mailing/Page/Unsubscribe.php
@@ -1,9 +1,9 @@
_mailing = new CRM_Mailing_BAO_Mailing();
if (!is_numeric($this->_mailingID)) {
+
+ //lets get the id from the hash
+ $result_id = civicrm_api3('Mailing', 'get', [
+ 'return' => ['id'],
+ 'hash' => $this->_mailingID,
+ ]);
$this->_mailing->hash = $this->_mailingID;
+ $this->_mailingID = $result_id['id'];
}
elseif (is_numeric($this->_mailingID)) {
$this->_mailing->id = $this->_mailingID;
@@ -132,59 +147,27 @@ public function run($id = NULL, $contactID = NULL, $print = TRUE, $allowID = FAL
return NULL;
}
- CRM_Mailing_BAO_Mailing::tokenReplace($this->_mailing);
-
- // get and format attachments
- $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing',
- $this->_mailing->id
- );
-
- // get contact detail and compose if contact id exists
- $returnProperties = $this->_mailing->getReturnProperties();
- if (isset($this->_contactID)) {
- // get details of contact with token value including Custom Field Token Values.CRM-3734
- $params = array('contact_id' => $this->_contactID);
- $details = CRM_Utils_Token::getTokenDetails($params,
- $returnProperties,
- FALSE, TRUE, NULL,
- $this->_mailing->getFlattenedTokens(),
- get_class($this)
- );
- $details = $details[0][$this->_contactID];
- $contactId = $this->_contactID;
- }
- else {
- // get tokens that are not contact specific resolved
- $params = array('contact_id' => 0);
- $details = CRM_Utils_Token::getAnonymousTokenDetails($params,
- $returnProperties,
- TRUE, TRUE, NULL,
- $this->_mailing->getFlattenedTokens(),
- get_class($this)
- );
-
- $details = CRM_Utils_Array::value(0, $details[0]);
- $contactId = 0;
- }
- $mime = $this->_mailing->compose(NULL, NULL, NULL, $contactId,
- $this->_mailing->from_email,
- $this->_mailing->from_email,
- TRUE, $details, $attachments
- );
+ $contactId = isset($this->_contactID) ? $this->_contactID : 0;
+
+ $result = civicrm_api3('Mailing', 'preview', [
+ 'id' => $this->_mailingID,
+ 'contact_id' => $contactId,
+ ]);
+ $mailing = \CRM_Utils_Array::value('values', $result);
$title = NULL;
- if (isset($this->_mailing->body_html) && empty($_GET['text'])) {
+ if (isset($mailing['body_html']) && empty($_GET['text'])) {
$header = 'text/html; charset=utf-8';
- $content = $mime->getHTMLBody();
+ $content = $mailing['body_html'];
if (strpos($content, '') === FALSE && strpos($content, '
' . ts('%3. There are some contacts who have this membership type assigned to them. Search for contacts with this membership type from Find Members. If you are still getting this message after deleting these memberships, there may be contacts in the Trash (deleted) with this membership type. Try using Advanced Search and checking "Search in Trash".', array(
+ $message .= '
' . ts('%3. There are some contacts who have this membership type assigned to them. Search for contacts with this membership type from Find Members. If you are still getting this message after deleting these memberships, there may be contacts in the Trash (deleted) with this membership type. Try using Advanced Search and checking "Search in Trash".', [
1 => $findMembersURL,
2 => $deleteURL,
3 => $cnt,
- ));
+ ]);
$cnt++;
}
if (in_array('MembershipBlock', $status)) {
$deleteURL = CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1');
- $message .= ts('%2. This Membership Type is used in an Online Contribution page. Uncheck this membership type in the Memberships tab.', array(
+ $message .= ts('%2. This Membership Type is used in an Online Contribution page. Uncheck this membership type in the Memberships tab.', [
1 => $deleteURL,
2 => $cnt,
- ));
+ ]);
throw new CRM_Core_Exception($message);
}
}
@@ -214,17 +230,17 @@ public static function del($membershipTypeId) {
* An array of membershipType-details.
*/
public static function convertDayFormat(&$membershipType) {
- $periodDays = array(
+ $periodDays = [
'fixed_period_start_day',
'fixed_period_rollover_day',
- );
+ ];
foreach ($membershipType as $id => $details) {
foreach ($periodDays as $pDay) {
if (!empty($details[$pDay])) {
if ($details[$pDay] > 31) {
$month = substr($details[$pDay], 0, strlen($details[$pDay]) - 2);
$day = substr($details[$pDay], -2);
- $monthMap = array(
+ $monthMap = [
'1' => 'Jan',
'2' => 'Feb',
'3' => 'Mar',
@@ -237,7 +253,7 @@ public static function convertDayFormat(&$membershipType) {
'10' => 'Oct',
'11' => 'Nov',
'12' => 'Dec',
- );
+ ];
$membershipType[$id][$pDay] = $monthMap[$month] . ' ' . $day;
}
else {
@@ -251,12 +267,14 @@ public static function convertDayFormat(&$membershipType) {
/**
* Get membership Types.
*
+ * @deprecated use getAllMembershipTypes.
+ *
* @param bool $public
*
* @return array
*/
public static function getMembershipTypes($public = TRUE) {
- $membershipTypes = array();
+ $membershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
$membershipType->is_active = 1;
if ($public) {
@@ -267,26 +285,26 @@ public static function getMembershipTypes($public = TRUE) {
while ($membershipType->fetch()) {
$membershipTypes[$membershipType->id] = $membershipType->name;
}
- $membershipType->free();
return $membershipTypes;
}
/**
* Get membership Type Details.
*
+ * @deprecated use getMembershipType.
+ *
* @param int $membershipTypeId
*
* @return array|null
*/
public static function getMembershipTypeDetails($membershipTypeId) {
- $membershipTypeDetails = array();
+ $membershipTypeDetails = [];
$membershipType = new CRM_Member_DAO_MembershipType();
$membershipType->is_active = 1;
$membershipType->id = $membershipTypeId;
if ($membershipType->find(TRUE)) {
CRM_Core_DAO::storeValues($membershipType, $membershipTypeDetails);
- $membershipType->free();
return $membershipTypeDetails;
}
else {
@@ -314,11 +332,11 @@ public static function getDatesForMembershipType($membershipTypeId, $joinDate =
$membershipTypeDetails = self::getMembershipTypeDetails($membershipTypeId);
// Convert all dates to 'Y-m-d' format.
- foreach (array(
+ foreach ([
'joinDate',
'startDate',
'endDate',
- ) as $dateParam) {
+ ] as $dateParam) {
if (!empty($$dateParam)) {
$$dateParam = CRM_Utils_Date::processDate($$dateParam, NULL, FALSE, 'Y-m-d');
}
@@ -426,11 +444,11 @@ public static function getDatesForMembershipType($membershipTypeId, $joinDate =
}
}
- $membershipDates = array(
+ $membershipDates = [
'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
'join_date' => CRM_Utils_Date::customFormat($joinDate, '%Y%m%d'),
- );
+ ];
return $membershipDates;
}
@@ -493,6 +511,7 @@ public static function isDuringFixedAnnualRolloverPeriod($startDate, $membership
*
* @param int $membershipId
* @param $changeToday
+ * If provided, specify an alternative date to use as "today" for renewal
* @param int $membershipTypeID
* If provided, overrides the membership type of the $membershipID membership.
* @param int $numRenewTerms
@@ -504,11 +523,11 @@ public static function isDuringFixedAnnualRolloverPeriod($startDate, $membership
* array fo the start date, end date and join date of the membership
*/
public static function getRenewalDatesForMembershipType($membershipId, $changeToday = NULL, $membershipTypeID = NULL, $numRenewTerms = 1) {
- $params = array('id' => $membershipId);
+ $params = ['id' => $membershipId];
$membershipDetails = CRM_Member_BAO_Membership::getValues($params, $values);
$membershipDetails = $membershipDetails[$membershipId];
$statusID = $membershipDetails->status_id;
- $membershipDates = array();
+ $membershipDates = [];
if (!empty($membershipDetails->join_date)) {
$membershipDates['join_date'] = CRM_Utils_Date::customFormat($membershipDetails->join_date, '%Y%m%d');
}
@@ -536,6 +555,8 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
$date = $membershipDetails->end_date;
}
$date = explode('-', $date);
+ // We have to add 1 day first in case it's the end of the month, then subtract afterwards
+ // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
$logStartDate = date('Y-m-d', mktime(0, 0, 0,
(double) $date[1],
(double) ($date[2] + 1),
@@ -609,28 +630,6 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
return $membershipDates;
}
- /**
- * Retrieve all Membership Types associated.
- * with an Organization
- *
- * @param int $orgID
- * Id of Organization.
- *
- * @return array
- * array of the details of membership types
- */
- public static function getMembershipTypesByOrg($orgID) {
- $membershipTypes = array();
- $dao = new CRM_Member_DAO_MembershipType();
- $dao->member_of_contact_id = $orgID;
- $dao->find();
- while ($dao->fetch()) {
- $membershipTypes[$dao->id] = array();
- CRM_Core_DAO::storeValues($dao, $membershipTypes[$dao->id]);
- }
- return $membershipTypes;
- }
-
/**
* Retrieve all Membership Types with Member of Contact id.
*
@@ -640,7 +639,7 @@ public static function getMembershipTypesByOrg($orgID) {
* array of the details of membership types with Member of Contact id
*/
public static function getMemberOfContactByMemTypes($membershipTypes) {
- $memTypeOrganizations = array();
+ $memTypeOrganizations = [];
if (empty($membershipTypes)) {
return $memTypeOrganizations;
}
@@ -661,7 +660,7 @@ public static function getMemberOfContactByMemTypes($membershipTypes) {
* @return array
*/
public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
- $allMembershipTypes = array();
+ $allMembershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
@@ -686,7 +685,7 @@ public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
*/
public static function getMembershipTypeInfo() {
if (!self::$_membershipTypeInfo) {
- $orgs = $types = array();
+ $orgs = $types = [];
$query = 'SELECT memType.id, memType.name, memType.member_of_contact_id, c.sort_name
FROM civicrm_membership_type memType INNER JOIN civicrm_contact c ON c.id = memType.member_of_contact_id
@@ -697,12 +696,11 @@ public static function getMembershipTypeInfo() {
$types[$dao->member_of_contact_id][$dao->id] = $dao->name;
}
- self::$_membershipTypeInfo = array($orgs, $types);
+ self::$_membershipTypeInfo = [$orgs, $types];
}
return self::$_membershipTypeInfo;
}
-
/**
* @param array $params
* @param int $previousID
@@ -720,14 +718,14 @@ public static function createMembershipPriceField($params, $previousID, $members
}
$fieldLabel = 'Membership Amount';
$optionsIds = NULL;
- $fieldParams = array(
+ $fieldParams = [
'price_set_id ' => $priceSetId,
'name' => $fieldName,
- );
- $results = array();
+ ];
+ $results = [];
CRM_Price_BAO_PriceField::retrieve($fieldParams, $results);
if (empty($results)) {
- $fieldParams = array();
+ $fieldParams = [];
$fieldParams['label'] = $fieldLabel;
$fieldParams['name'] = $fieldName;
$fieldParams['price_set_id'] = $priceSetId;
@@ -749,11 +747,11 @@ public static function createMembershipPriceField($params, $previousID, $members
}
else {
$fieldID = $results['id'];
- $fieldValueParams = array(
+ $fieldValueParams = [
'price_field_id' => $fieldID,
'membership_type_id' => $membershipTypeId,
- );
- $results = array();
+ ];
+ $results = [];
CRM_Price_BAO_PriceFieldValue::retrieve($fieldValueParams, $results);
if (!empty($results)) {
$results['label'] = $results['name'] = $params['name'];
@@ -761,14 +759,14 @@ public static function createMembershipPriceField($params, $previousID, $members
$optionsIds['id'] = $results['id'];
}
else {
- $results = array(
+ $results = [
'price_field_id' => $fieldID,
'name' => $params['name'],
'label' => $params['name'],
'amount' => empty($params['minimum_fee']) ? 0 : $params['minimum_fee'],
'membership_type_id' => $membershipTypeId,
'is_active' => 1,
- );
+ ];
}
if ($previousID) {
@@ -792,41 +790,65 @@ public static function createMembershipPriceField($params, $previousID, $members
* @param array $params
*/
public static function updateAllPriceFieldValue($membershipTypeId, $params) {
- $updateFields = array();
- if (!empty($params['minimum_fee'])) {
- $amount = $params['minimum_fee'];
- }
- else {
- $amount = 0;
- }
-
- $updateValues = array(
- 2 => array('financial_type_id', 'financial_type_id', 'Integer'),
- 3 => array('label', 'name', 'String'),
- 4 => array('amount', 'minimum_fee', 'Float'),
- 5 => array('description', 'description', 'String'),
- );
-
- $queryParams = array(1 => array($membershipTypeId, 'Integer'));
- foreach ($updateValues as $key => $value) {
- if (array_key_exists($value[1], $params)) {
- $updateFields[] = "cpfv." . $value[0] . " = %$key";
- if ($value[1] == 'minimum_fee') {
- $fieldValue = $amount;
- }
- else {
- $fieldValue = $params[$value[1]];
+ $defaults = [];
+ $fieldsToUpdate = [
+ 'financial_type_id' => 'financial_type_id',
+ 'name' => 'label',
+ 'minimum_fee' => 'amount',
+ 'description' => 'description',
+ 'visibility' => 'visibility_id',
+ ];
+ $priceFieldValueBAO = new CRM_Price_BAO_PriceFieldValue();
+ $priceFieldValueBAO->membership_type_id = $membershipTypeId;
+ $priceFieldValueBAO->find();
+ while ($priceFieldValueBAO->fetch()) {
+ $updateParams = [
+ 'id' => $priceFieldValueBAO->id,
+ 'price_field_id' => $priceFieldValueBAO->price_field_id,
+ ];
+ //Get priceset details.
+ $fieldParams = ['fid' => $priceFieldValueBAO->price_field_id];
+ $setID = CRM_Price_BAO_PriceSet::getSetId($fieldParams);
+ $setParams = ['id' => $setID];
+ $setValues = CRM_Price_BAO_PriceSet::retrieve($setParams, $defaults);
+ if (!empty($setValues->is_quick_config) && $setValues->name != 'default_membership_type_amount') {
+ foreach ($fieldsToUpdate as $key => $value) {
+ if ($value == 'visibility_id' && !empty($params['visibility'])) {
+ $updateParams['visibility_id'] = CRM_Price_BAO_PriceField::getVisibilityOptionID(strtolower($params['visibility']));
+ }
+ else {
+ $updateParams[$value] = CRM_Utils_Array::value($key, $params);
+ }
}
- $queryParams[$key] = array($fieldValue, $value[2]);
+ CRM_Price_BAO_PriceFieldValue::add($updateParams);
}
}
+ }
- $query = "UPDATE `civicrm_price_field_value` cpfv
-INNER JOIN civicrm_price_field cpf on cpf.id = cpfv.price_field_id
-INNER JOIN civicrm_price_set cps on cps.id = cpf.price_set_id
-SET " . implode(' , ', $updateFields) . " WHERE cpfv.membership_type_id = %1
-AND cps.is_quick_config = 1 AND cps.name != 'default_membership_type_amount'";
- CRM_Core_DAO::executeQuery($query, $queryParams);
+ /**
+ * Cached wrapper for membership types.
+ *
+ * Since this is used from the batched script caching helps.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getAllMembershipTypes() {
+ if (!Civi::cache('metadata')->has(__CLASS__ . __FUNCTION__)) {
+ Civi::cache('metadata')->set(__CLASS__ . __FUNCTION__, civicrm_api3('MembershipType', 'get', ['options' => ['limit' => 0, 'sort' => 'weight']])['values']);
+ }
+ return Civi::cache('metadata')->get(__CLASS__ . __FUNCTION__);
+ }
+
+ /**
+ * Get a specific membership type (leveraging the cache).
+ *
+ * @param int $id
+ *
+ * @return mixed
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getMembershipType($id) {
+ return self::getAllMembershipTypes()[$id];
}
}
diff --git a/CRM/Member/BAO/Query.php b/CRM/Member/BAO/Query.php
index 79d9b7b39571..d8e0d9b9ea42 100644
--- a/CRM/Member/BAO/Query.php
+++ b/CRM/Member/BAO/Query.php
@@ -1,9 +1,9 @@
_returnProperties['join_date'])) {
- $query->_select['join_date'] = "civicrm_membership.join_date as join_date";
- $query->_element['join_date'] = 1;
+ if (!empty($query->_returnProperties['membership_join_date'])) {
+ $query->_select['membership_join_date'] = "civicrm_membership.join_date as membership_join_date";
+ $query->_element['membership_join_date'] = 1;
}
//add source
@@ -146,7 +146,7 @@ public static function where(&$query) {
continue;
}
if (substr($query->_params[$id][0], 0, 7) == 'member_' || substr($query->_params[$id][0], 0, 11) == 'membership_') {
- if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
+ if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
self::whereClauseSingle($query->_params[$id], $query);
@@ -161,28 +161,50 @@ public static function where(&$query) {
* @param CRM_Contact_BAO_Query $query
*/
public static function whereClauseSingle(&$values, &$query) {
+ if ($query->buildDateRangeQuery($values)) {
+ // @todo - move this to Contact_Query in or near the call to
+ // $this->buildRelativeDateQuery($values);
+ return;
+ }
list($name, $op, $value, $grouping) = $values;
switch ($name) {
case 'member_join_date_low':
case 'member_join_date_high':
+ Civi::log()->warning(
+ 'member_join_date field is deprecated please use membership_join_date field instead',
+ ['civi.tag' => 'deprecated']
+ );
+ $fldName = str_replace(['_low', '_high'], '', $name);
$query->dateQueryBuilder($values,
- 'civicrm_membership', 'member_join_date', 'join_date',
+ 'civicrm_membership', $fldName, 'join_date',
'Member Since'
);
return;
+ case 'membership_start_date':
case 'member_start_date_low':
case 'member_start_date_high':
+ Civi::log()->warning(
+ 'member_start_date field is deprecated please use membership_start_date field instead',
+ ['civi.tag' => 'deprecated']
+ );
+ $fldName = str_replace(['_low', '_high'], '', $name);
$query->dateQueryBuilder($values,
- 'civicrm_membership', 'member_start_date', 'start_date',
+ 'civicrm_membership', $fldName, 'start_date',
'Start Date'
);
return;
+ case 'membership_end_date':
case 'member_end_date_low':
case 'member_end_date_high':
+ Civi::log()->warning(
+ 'member_end_date field is deprecated please use membership_end_date field instead',
+ ['civi.tag' => 'deprecated']
+ );
+ $fldName = str_replace(['_low', '_high'], '', $name);
$query->dateQueryBuilder($values,
- 'civicrm_membership', 'member_end_date', 'end_date',
+ 'civicrm_membership', $fldName, 'end_date',
'End Date'
);
return;
@@ -193,7 +215,7 @@ public static function whereClauseSingle(&$values, &$query) {
if ($date) {
$query->_where[$grouping][] = "civicrm_membership.join_date {$op} {$date}";
$format = CRM_Utils_Date::customFormat(CRM_Utils_Date::format(array_reverse($value), '-'));
- $query->_qill[$grouping][] = ts('Member Since %2 %1', array(1 => $format, 2 => $op));
+ $query->_qill[$grouping][] = ts('Member Since %2 %1', [1 => $format, 2 => $op]);
}
return;
@@ -204,7 +226,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
$query->_where[$grouping][] = "civicrm_membership.source $op '{$value}'";
- $query->_qill[$grouping][] = ts('Source %2 %1', array(1 => $value, 2 => $op));
+ $query->_qill[$grouping][] = ts('Source %2 %1', [1 => $value, 2 => $op]);
$query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
return;
@@ -226,10 +248,11 @@ public static function whereClauseSingle(&$values, &$query) {
// the load function. The where clause and the whereTables are saved so they should suffice to generate the query
// to get a contact list. But, better to deal with in 4.8 now...
if (is_string($value) && strpos($value, ',') && $op == '=') {
- $value = array('IN' => explode(',', $value));
+ $value = ['IN' => explode(',', $value)];
}
case 'membership_id':
- case 'member_id': // CRM-18523 Updated to membership_id but kept member_id case for backwards compatibility
+ // CRM-18523 Updated to membership_id but kept member_id case for backwards compatibility
+ case 'member_id':
case 'member_campaign_id':
if (strpos($name, 'status') !== FALSE) {
@@ -278,7 +301,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'member_auto_renew':
$op = '=';
- $where = $qill = array();
+ $where = $qill = [];
foreach ($value as $val) {
if ($val == 1) {
$where[] = ' civicrm_membership.contribution_recur_id IS NULL';
@@ -371,6 +394,7 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_qill[$grouping][] = $value ? ts("Membership Status Is Overriden") : ts("Membership Status Is NOT Overriden");
$query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
return;
+
}
}
@@ -430,7 +454,7 @@ public static function defaultReturnProperties(
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_MEMBER) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -438,7 +462,7 @@ public static function defaultReturnProperties(
'membership_type' => 1,
'member_is_test' => 1,
'member_is_pay_later' => 1,
- 'join_date' => 1,
+ 'membership_join_date' => 1,
'membership_start_date' => 1,
'membership_end_date' => 1,
'membership_source' => 1,
@@ -449,8 +473,7 @@ public static function defaultReturnProperties(
'membership_recur_id' => 1,
'member_campaign_id' => 1,
'member_is_override' => 1,
- 'member_auto_renew' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom membership properties
@@ -466,39 +489,45 @@ public static function defaultReturnProperties(
return $properties;
}
+ /**
+ * Get the metadata for fields to be included on the grant search form.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getSearchFieldMetadata() {
+ $fields = [
+ 'membership_join_date',
+ 'membership_start_date',
+ 'membership_end_date',
+ ];
+ $metadata = civicrm_api3('Membership', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
/**
* Build the search form.
*
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
+ $form->addSearchFieldMetadata(['Membership' => self::getSearchFieldMetadata()]);
+ $form->addFormFieldsFromMetadata();
$membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label', FALSE, FALSE);
- $form->add('select', 'membership_status_id', ts('Membership Status'), $membershipStatus, FALSE, array(
+ $form->add('select', 'membership_status_id', ts('Membership Status'), $membershipStatus, FALSE, [
'id' => 'membership_status_id',
'multiple' => 'multiple',
'class' => 'crm-select2',
- ));
+ ]);
- $form->addEntityRef('membership_type_id', ts('Membership Type'), array(
+ $form->addEntityRef('membership_type_id', ts('Membership Type'), [
'entity' => 'MembershipType',
'multiple' => TRUE,
'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- ));
+ 'select' => ['minimumInputLength' => 0],
+ ]);
$form->addElement('text', 'member_source', ts('Source'));
- $form->add('number', 'membership_id', ts('Membership ID'), array('class' => 'four', 'min' => 1));
-
- CRM_Core_Form_Date::buildDateRange($form, 'member_join_date', 1, '_low', '_high', ts('From'), FALSE);
- $form->addElement('hidden', 'member_join_date_range_error');
-
- CRM_Core_Form_Date::buildDateRange($form, 'member_start_date', 1, '_low', '_high', ts('From'), FALSE);
- $form->addElement('hidden', 'member_start_date_range_error');
-
- CRM_Core_Form_Date::buildDateRange($form, 'member_end_date', 1, '_low', '_high', ts('From'), FALSE);
- $form->addElement('hidden', 'member_end_date_range_error');
-
- $form->addFormRule(array('CRM_Member_BAO_Query', 'formRule'), $form);
+ $form->add('number', 'membership_id', ts('Membership ID'), ['class' => 'four', 'min' => 1]);
$form->addYesNo('membership_is_current_member', ts('Current Member?'), TRUE);
$form->addYesNo('member_is_primary', ts('Primary Member?'), TRUE);
@@ -506,26 +535,26 @@ public static function buildSearchForm(&$form) {
$form->add('select', 'member_auto_renew',
ts('Auto-Renew Subscription Status?'),
- array(
+ [
'1' => ts('- None -'),
'2' => ts('In Progress'),
'3' => ts('Failed'),
'4' => ts('Cancelled'),
'5' => ts('Ended'),
'6' => ts('Any'),
- ),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))
+ ],
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
);
$form->addYesNo('member_test', ts('Membership is a Test?'), TRUE);
$form->addYesNo('member_is_override', ts('Membership Status Is Overriden?'), TRUE);
- self::addCustomFormFields($form, array('Membership'));
+ self::addCustomFormFields($form, ['Membership']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'member_campaign_id');
$form->assign('validCiviMember', TRUE);
- $form->setDefaults(array('member_test' => 0));
+ $form->setDefaults(['member_test' => 0]);
}
/**
@@ -535,31 +564,8 @@ public static function buildSearchForm(&$form) {
*/
public static function tableNames(&$tables) {
if (!empty($tables['civicrm_membership_log']) || !empty($tables['civicrm_membership_status']) || CRM_Utils_Array::value('civicrm_membership_type', $tables)) {
- $tables = array_merge(array('civicrm_membership' => 1), $tables);
- }
- }
-
- /**
- * Custom form rules.
- *
- * @param array $fields
- * @param array $files
- * @param CRM_Core_Form $form
- *
- * @return bool|array
- */
- public static function formRule($fields, $files, $form) {
- $errors = array();
-
- if ((empty($fields['member_join_date_low']) || empty($fields['member_join_date_high'])) && (empty($fields['member_start_date_low']) || empty($fields['member_start_date_high'])) && (empty($fields['member_end_date_low']) || empty($fields['member_end_date_high']))) {
- return TRUE;
+ $tables = array_merge(['civicrm_membership' => 1], $tables);
}
-
- CRM_Utils_Rule::validDateRange($fields, 'member_join_date', $errors, ts('Member Since'));
- CRM_Utils_Rule::validDateRange($fields, 'member_start_date', $errors, ts('Start Date'));
- CRM_Utils_Rule::validDateRange($fields, 'member_end_date', $errors, ts('End Date'));
-
- return empty($errors) ? TRUE : $errors;
}
}
diff --git a/CRM/Member/Controller/Search.php b/CRM/Member/Controller/Search.php
index c72c64293ca7..c1f9bcce080b 100644
--- a/CRM/Member/Controller/Search.php
+++ b/CRM/Member/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_membership';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_membership_status', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'owner_membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_recur_id', 'civicrm_contribution_recur', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_membership_status', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'owner_membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_recur_id', 'civicrm_contribution_recur', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'membership_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'membership_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.id',
'headerPattern' => '/^(m(embership\s)?id)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- ) ,
- 'membership_contact_id' => array(
+ ],
+ 'membership_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.contact_id',
'headerPattern' => '/contact(.?id)?/i',
'dataPattern' => '/^\d+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'membership_type_id' => array(
+ ],
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Id') ,
- 'description' => 'FK to Membership Type',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership Type Id'),
+ 'description' => ts('FK to Membership Type'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.membership_type_id',
'headerPattern' => '/^(m(embership\s)?type)$/i',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_membership_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'join_date' => array(
+ ],
+ ],
+ 'membership_join_date' => [
'name' => 'join_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Member Since') ,
- 'description' => 'Beginning of initial membership period (member since...).',
- 'import' => true,
+ 'title' => ts('Member Since'),
+ 'description' => ts('Beginning of initial membership period (member since...).'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.join_date',
'headerPattern' => '/^join|(j(oin\s)?date)$/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_start_date' => array(
+ ],
+ ],
+ 'membership_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Start Date') ,
- 'description' => 'Beginning of current uninterrupted membership period.',
- 'import' => true,
+ 'title' => ts('Membership Start Date'),
+ 'description' => ts('Beginning of current uninterrupted membership period.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.start_date',
'headerPattern' => '/(member(ship)?.)?start(s)?(.date$)?/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_end_date' => array(
+ ],
+ ],
+ 'membership_end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Expiration Date') ,
- 'description' => 'Current membership period expire date.',
- 'import' => true,
+ 'title' => ts('Membership Expiration Date'),
+ 'description' => ts('Current membership period expire date.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.end_date',
'headerPattern' => '/(member(ship)?.)?end(s)?(.date$)?/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_source' => array(
+ ],
+ ],
+ 'membership_source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Source') ,
+ 'title' => ts('Source'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership.source',
'headerPattern' => '/^(member(ship?))?source$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'status_id' => array(
+ ],
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status Id') ,
- 'description' => 'FK to Membership Status',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership Status Id'),
+ 'description' => ts('FK to Membership Status'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.status_id',
'headerPattern' => '/(member(ship|).)?(status)$/i',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipStatus',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_membership_status',
'keyColumn' => 'id',
'labelColumn' => 'label',
- )
- ) ,
- 'is_override' => array(
+ ],
+ ],
+ 'member_is_override' => [
'name' => 'is_override',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Status Override') ,
- 'description' => 'Admin users may set a manual status which overrides the calculated status. When this flag is true, automated status update scripts should NOT modify status for the record.',
- 'import' => true,
+ 'title' => ts('Status Override'),
+ 'description' => ts('Admin users may set a manual status which overrides the calculated status. When this flag is true, automated status update scripts should NOT modify status for the record.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_override',
'headerPattern' => '/override$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'owner_membership_id' => array(
+ ],
+ ],
+ 'status_override_end_date' => [
+ 'name' => 'status_override_end_date',
+ 'type' => CRM_Utils_Type::T_DATE,
+ 'title' => ts('Status Override End Date'),
+ 'description' => ts('Then end date of membership status override if \'Override until selected date\' override type is selected.'),
+ 'import' => TRUE,
+ 'where' => 'civicrm_membership.status_override_end_date',
+ 'export' => TRUE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ ],
+ ],
+ 'owner_membership_id' => [
'name' => 'owner_membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Primary Member ID') ,
- 'description' => 'Optional FK to Parent Membership.',
- 'export' => true,
+ 'title' => ts('Primary Member ID'),
+ 'description' => ts('Optional FK to Parent Membership.'),
'where' => 'civicrm_membership.owner_membership_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'max_related' => array(
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Related') ,
- 'description' => 'Maximum number of related memberships (membership_type override).',
+ 'title' => ts('Max Related'),
+ 'description' => ts('Maximum number of related memberships (membership_type override).'),
+ 'where' => 'civicrm_membership.max_related',
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'member_is_test' => array(
+ ],
+ ],
+ 'member_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_test',
'headerPattern' => '/(is.)?test(.member(ship)?)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'member_is_pay_later' => array(
+ ],
+ ],
+ 'member_is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Pay Later') ,
- 'import' => true,
+ 'title' => ts('Is Pay Later'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_pay_later',
'headerPattern' => '/(is.)?(pay(.)?later)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'contribution_recur_id' => array(
+ ],
+ ],
+ 'membership_recur_id' => [
'name' => 'contribution_recur_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Recurring Contribution') ,
- 'description' => 'Conditional foreign key to civicrm_contribution_recur id. Each membership in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.',
+ 'title' => ts('Membership Recurring Contribution'),
+ 'description' => ts('Conditional foreign key to civicrm_contribution_recur id. Each membership in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.'),
+ 'where' => 'civicrm_membership.contribution_recur_id',
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionRecur',
- ) ,
- 'member_campaign_id' => array(
+ ],
+ 'member_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this membership is attached.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this membership is attached.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -488,10 +503,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -499,24 +515,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_owner_membership_id' => array(
+ $indices = [
+ 'index_owner_membership_id' => [
'name' => 'index_owner_membership_id',
- 'field' => array(
+ 'field' => [
0 => 'owner_membership_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_membership::0::owner_membership_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipBlock.php b/CRM/Member/DAO/MembershipBlock.php
index f20ca244a47d..de4a3eda67c2 100644
--- a/CRM/Member/DAO/MembershipBlock.php
+++ b/CRM/Member/DAO/MembershipBlock.php
@@ -1,341 +1,353 @@
__table = 'civicrm_membership_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'entity_id', 'civicrm_contribution_page', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_default', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'entity_id', 'civicrm_contribution_page', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_default', 'civicrm_membership_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Block ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_block.id',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Entity Table') ,
- 'description' => 'Name for Membership Status',
+ 'title' => ts('Membership Block Entity Table'),
+ 'description' => ts('Name for Membership Status'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_block.entity_table',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block Entity ID') ,
- 'description' => 'FK to civicrm_contribution_page.id',
- 'required' => true,
+ 'title' => ts('Membership Block Entity ID'),
+ 'description' => ts('FK to civicrm_contribution_page.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_block.entity_id',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
- ) ,
- 'membership_types' => array(
+ ],
+ 'membership_types' => [
'name' => 'membership_types',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Membership Types') ,
- 'description' => 'Membership types to be exposed by this block',
+ 'title' => ts('Membership Block Membership Types'),
+ 'description' => ts('Membership types to be exposed by this block'),
'maxlength' => 1024,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.membership_types',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'membership_type_default' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'membership_type_default' => [
'name' => 'membership_type_default',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block Default Type') ,
- 'description' => 'Optional foreign key to membership_type',
+ 'title' => ts('Membership Block Default Type'),
+ 'description' => ts('Optional foreign key to membership_type'),
+ 'where' => 'civicrm_membership_block.membership_type_default',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- ) ,
- 'display_min_fee' => array(
+ ],
+ 'display_min_fee' => [
'name' => 'display_min_fee',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Membership Block Display Minimum Fee') ,
- 'description' => 'Display minimum membership fee',
+ 'title' => ts('Membership Block Display Minimum Fee'),
+ 'description' => ts('Display minimum membership fee'),
+ 'where' => 'civicrm_membership_block.display_min_fee',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'is_separate_payment' => array(
+ ],
+ 'is_separate_payment' => [
'name' => 'is_separate_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Membership Block Is Separate Payment') ,
- 'description' => 'Should membership transactions be processed separately',
+ 'title' => ts('Membership Block Is Separate Payment'),
+ 'description' => ts('Should membership transactions be processed separately'),
+ 'where' => 'civicrm_membership_block.is_separate_payment',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'new_title' => array(
+ ],
+ 'new_title' => [
'name' => 'new_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block New Title') ,
- 'description' => 'Title to display at top of block',
+ 'title' => ts('Membership Block New Title'),
+ 'description' => ts('Title to display at top of block'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.new_title',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'new_text' => array(
+ ],
+ 'new_text' => [
'name' => 'new_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block New Text') ,
- 'description' => 'Text to display below title',
+ 'title' => ts('Membership Block New Text'),
+ 'description' => ts('Text to display below title'),
+ 'where' => 'civicrm_membership_block.new_text',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'renewal_title' => array(
+ ],
+ 'renewal_title' => [
'name' => 'renewal_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Renewal Title') ,
- 'description' => 'Title for renewal',
+ 'title' => ts('Membership Block Renewal Title'),
+ 'description' => ts('Title for renewal'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.renewal_title',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'renewal_text' => array(
+ ],
+ 'renewal_text' => [
'name' => 'renewal_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block Renewal Text') ,
- 'description' => 'Text to display for member renewal',
+ 'title' => ts('Membership Block Renewal Text'),
+ 'description' => ts('Text to display for member renewal'),
+ 'where' => 'civicrm_membership_block.renewal_text',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'is_required' => array(
+ ],
+ 'is_required' => [
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Required') ,
- 'description' => 'Is membership sign up optional',
+ 'title' => ts('Is Required'),
+ 'description' => ts('Is membership sign up optional'),
+ 'where' => 'civicrm_membership_block.is_required',
+ 'default' => '0',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_block enabled',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_block enabled'),
+ 'where' => 'civicrm_membership_block.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -343,10 +355,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -354,15 +367,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipLog.php b/CRM/Member/DAO/MembershipLog.php
index 8b7f6b986e4c..47b6737f6bae 100644
--- a/CRM/Member/DAO/MembershipLog.php
+++ b/CRM/Member/DAO/MembershipLog.php
@@ -1,269 +1,273 @@
__table = 'civicrm_membership_log';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_membership_status', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'modified_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_membership_status', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'modified_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Log ID') ,
- 'required' => true,
+ 'title' => ts('Membership Log ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'membership_id' => array(
+ ],
+ 'membership_id' => [
'name' => 'membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership ID') ,
- 'description' => 'FK to Membership table',
- 'required' => true,
+ 'title' => ts('Membership ID'),
+ 'description' => ts('FK to Membership table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.membership_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'status_id' => array(
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status') ,
- 'description' => 'New status assigned to membership by this action. FK to Membership Status',
- 'required' => true,
+ 'title' => ts('Membership Status'),
+ 'description' => ts('New status assigned to membership by this action. FK to Membership Status'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.status_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipStatus',
- ) ,
- 'start_date' => array(
+ ],
+ 'start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Log Start Date') ,
- 'description' => 'New membership period start date',
+ 'title' => ts('Membership Log Start Date'),
+ 'description' => ts('New membership period start date'),
+ 'where' => 'civicrm_membership_log.start_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'end_date' => array(
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Log End Date') ,
- 'description' => 'New membership period expiration date.',
+ 'title' => ts('Membership Log End Date'),
+ 'description' => ts('New membership period expiration date.'),
+ 'where' => 'civicrm_membership_log.end_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'modified_id' => array(
+ ],
+ 'modified_id' => [
'name' => 'modified_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Log modified By') ,
- 'description' => 'FK to Contact ID of person under whose credentials this data modification was made.',
+ 'title' => ts('Membership Log modified By'),
+ 'description' => ts('FK to Contact ID of person under whose credentials this data modification was made.'),
+ 'where' => 'civicrm_membership_log.modified_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'modified_date' => array(
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Change Date') ,
- 'description' => 'Date this membership modification action was logged.',
+ 'title' => ts('Membership Change Date'),
+ 'description' => ts('Date this membership modification action was logged.'),
+ 'where' => 'civicrm_membership_log.modified_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'membership_type_id' => array(
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type ID') ,
- 'description' => 'FK to Membership Type.',
+ 'title' => ts('Membership Type ID'),
+ 'description' => ts('FK to Membership Type.'),
+ 'where' => 'civicrm_membership_log.membership_type_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- ) ,
- 'max_related' => array(
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Related Memberships') ,
- 'description' => 'Maximum number of related memberships.',
+ 'title' => ts('Maximum Related Memberships'),
+ 'description' => ts('Maximum number of related memberships.'),
+ 'where' => 'civicrm_membership_log.max_related',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -271,10 +275,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_log', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_log', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -282,15 +287,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_log', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_log', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipPayment.php b/CRM/Member/DAO/MembershipPayment.php
index 73af131b1e84..0495523c2ba9 100644
--- a/CRM/Member/DAO/MembershipPayment.php
+++ b/CRM/Member/DAO/MembershipPayment.php
@@ -1,168 +1,157 @@
__table = 'civicrm_membership_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Payment ID') ,
- 'required' => true,
+ 'title' => ts('Membership Payment ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_payment.id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
- ) ,
- 'membership_id' => array(
+ ],
+ 'membership_id' => [
'name' => 'membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership') ,
- 'description' => 'FK to Membership table',
- 'required' => true,
+ 'title' => ts('Membership'),
+ 'description' => ts('FK to Membership table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_payment.membership_id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'where' => 'civicrm_membership_payment.contribution_id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -170,10 +159,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -181,26 +171,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contribution_membership' => array(
+ $indices = [
+ 'UI_contribution_membership' => [
'name' => 'UI_contribution_membership',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'membership_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_membership_payment::1::contribution_id::membership_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipStatus.php b/CRM/Member/DAO/MembershipStatus.php
index 3d7f1d8dafdd..f0c111dbfeb6 100644
--- a/CRM/Member/DAO/MembershipStatus.php
+++ b/CRM/Member/DAO/MembershipStatus.php
@@ -1,384 +1,409 @@
__table = 'civicrm_membership_status';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Status ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_status.id',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'membership_status' => array(
+ ],
+ 'membership_status' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Status') ,
- 'description' => 'Name for Membership Status',
+ 'title' => ts('Membership Status'),
+ 'description' => ts('Name for Membership Status'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership_status.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Label for Membership Status',
+ 'title' => ts('Label'),
+ 'description' => ts('Label for Membership Status'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_status.label',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 1,
- ) ,
- 'start_event' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'start_event' => [
'name' => 'start_event',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Start Event') ,
- 'description' => 'Event when this status starts.',
+ 'title' => ts('Start Event'),
+ 'description' => ts('Event when this status starts.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_membership_status.start_event',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::eventDate',
- )
- ) ,
- 'start_event_adjust_unit' => array(
+ ],
+ ],
+ 'start_event_adjust_unit' => [
'name' => 'start_event_adjust_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Start Event Adjust Unit') ,
- 'description' => 'Unit used for adjusting from start_event.',
+ 'title' => ts('Start Event Adjust Unit'),
+ 'description' => ts('Unit used for adjusting from start_event.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_status.start_event_adjust_unit',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::unitList',
- )
- ) ,
- 'start_event_adjust_interval' => array(
+ ],
+ ],
+ 'start_event_adjust_interval' => [
'name' => 'start_event_adjust_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Start Event Adjust Interval') ,
- 'description' => 'Status range begins this many units from start_event.',
+ 'title' => ts('Start Event Adjust Interval'),
+ 'description' => ts('Status range begins this many units from start_event.'),
+ 'where' => 'civicrm_membership_status.start_event_adjust_interval',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'end_event' => array(
+ ],
+ 'end_event' => [
'name' => 'end_event',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('End Event') ,
- 'description' => 'Event after which this status ends.',
+ 'title' => ts('End Event'),
+ 'description' => ts('Event after which this status ends.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_membership_status.end_event',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::eventDate',
- )
- ) ,
- 'end_event_adjust_unit' => array(
+ ],
+ ],
+ 'end_event_adjust_unit' => [
'name' => 'end_event_adjust_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('End Event Adjust Unit') ,
- 'description' => 'Unit used for adjusting from the ending event.',
+ 'title' => ts('End Event Adjust Unit'),
+ 'description' => ts('Unit used for adjusting from the ending event.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_status.end_event_adjust_unit',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::unitList',
- )
- ) ,
- 'end_event_adjust_interval' => array(
+ ],
+ ],
+ 'end_event_adjust_interval' => [
'name' => 'end_event_adjust_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('End Event Adjust Interval') ,
- 'description' => 'Status range ends this many units from end_event.',
+ 'title' => ts('End Event Adjust Interval'),
+ 'description' => ts('Status range ends this many units from end_event.'),
+ 'where' => 'civicrm_membership_status.end_event_adjust_interval',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_current_member' => array(
+ ],
+ 'is_current_member' => [
'name' => 'is_current_member',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Current Membership?') ,
- 'description' => 'Does this status aggregate to current members (e.g. New, Renewed, Grace might all be TRUE... while Unrenewed, Lapsed, Inactive would be FALSE).',
+ 'title' => ts('Current Membership?'),
+ 'description' => ts('Does this status aggregate to current members (e.g. New, Renewed, Grace might all be TRUE... while Unrenewed, Lapsed, Inactive would be FALSE).'),
+ 'where' => 'civicrm_membership_status.is_current_member',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_admin' => array(
+ ],
+ 'is_admin' => [
'name' => 'is_admin',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Admin Assigned Only?') ,
- 'description' => 'Is this status for admin/manual assignment only.',
+ 'title' => ts('Administrator Only?'),
+ 'description' => ts('Is this status for admin/manual assignment only.'),
+ 'where' => 'civicrm_membership_status.is_admin',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'weight' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
+ 'title' => ts('Order'),
+ 'where' => 'civicrm_membership_status.weight',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Default Status?') ,
- 'description' => 'Assign this status to a membership record if no other status match is found.',
+ 'title' => ts('Default Status?'),
+ 'description' => ts('Assign this status to a membership record if no other status match is found.'),
+ 'where' => 'civicrm_membership_status.is_default',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_status enabled.',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_status enabled.'),
+ 'where' => 'civicrm_membership_status.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Reserved') ,
- 'description' => 'Is this membership_status reserved.',
+ 'title' => ts('Is Reserved'),
+ 'description' => ts('Is this membership_status reserved.'),
+ 'where' => 'civicrm_membership_status.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -386,10 +411,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_status', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_status', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -397,15 +423,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_status', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_status', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipType.php b/CRM/Member/DAO/MembershipType.php
index b0e32cc43bd1..01c5b69e6629 100644
--- a/CRM/Member/DAO/MembershipType.php
+++ b/CRM/Member/DAO/MembershipType.php
@@ -1,521 +1,574 @@
__table = 'civicrm_membership_type';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'member_of_contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'member_of_contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Type ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Domain') ,
- 'description' => 'Which Domain is this match entry for',
- 'required' => true,
+ 'title' => ts('Membership Type Domain'),
+ 'description' => ts('Which Domain is this match entry for'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.domain_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'membership_type' => array(
+ ],
+ ],
+ 'membership_type' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type') ,
- 'description' => 'Name of Membership Type',
+ 'title' => ts('Membership Type'),
+ 'description' => ts('Name of Membership Type'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership_type.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 1,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Name"),
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Description') ,
- 'description' => 'Description of Membership Type',
+ 'title' => ts('Membership Type Description'),
+ 'description' => ts('Description of Membership Type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.description',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'member_of_contact_id' => array(
+ 'label' => ts("Description"),
+ ],
+ ],
+ 'member_of_contact_id' => [
'name' => 'member_of_contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Organization') ,
- 'description' => 'Owner organization for this membership type. FK to Contact ID',
- 'required' => true,
+ 'title' => ts('Membership Type Organization'),
+ 'description' => ts('Owner organization for this membership type. FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.member_of_contact_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Financial Type') ,
- 'description' => 'If membership is paid by a contribution - what financial type should be used. FK to civicrm_financial_type.id',
- 'required' => true,
+ 'title' => ts('Membership Financial Type'),
+ 'description' => ts('If membership is paid by a contribution - what financial type should be used. FK to civicrm_financial_type.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.financial_type_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'minimum_fee' => array(
+ ],
+ ],
+ 'minimum_fee' => [
'name' => 'minimum_fee',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('membership Type Minimum Fee') ,
- 'description' => 'Minimum fee for this membership (0 for free/complimentary memberships).',
- 'precision' => array(
- 20,
- 2
- ) ,
+ 'title' => ts('Membership Type Minimum Fee'),
+ 'description' => ts('Minimum fee for this membership (0 for free/complimentary memberships).'),
+ 'precision' => [
+ 18,
+ 9,
+ ],
+ 'where' => 'civicrm_membership_type.minimum_fee',
+ 'default' => '0',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'duration_unit' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Minimum Fee"),
+ ],
+ ],
+ 'duration_unit' => [
'name' => 'duration_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Duration Unit') ,
- 'description' => 'Unit in which membership period is expressed.',
+ 'title' => ts('Membership Type Duration Unit'),
+ 'description' => ts('Unit in which membership period is expressed.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_type.duration_unit',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::membershipTypeUnitList',
- )
- ) ,
- 'duration_interval' => array(
+ ],
+ ],
+ 'duration_interval' => [
'name' => 'duration_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Duration Interval') ,
- 'description' => 'Number of duration units in membership period (e.g. 1 year, 12 months).',
+ 'title' => ts('Membership Type Duration Interval'),
+ 'description' => ts('Number of duration units in membership period (e.g. 1 year, 12 months).'),
+ 'where' => 'civicrm_membership_type.duration_interval',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'period_type' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'period_type' => [
'name' => 'period_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Plan') ,
- 'description' => 'Rolling membership period starts on signup date. Fixed membership periods start on fixed_period_start_day.',
+ 'title' => ts('Membership Type Plan'),
+ 'description' => ts('Rolling membership period starts on signup date. Fixed membership periods start on fixed_period_start_day.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_type.period_type',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::periodType',
- )
- ) ,
- 'fixed_period_start_day' => array(
+ ],
+ ],
+ 'fixed_period_start_day' => [
'name' => 'fixed_period_start_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Fixed Period Start Day') ,
- 'description' => 'For fixed period memberships, month and day (mmdd) on which subscription/membership will start. Period start is back-dated unless after rollover day.',
+ 'title' => ts('Fixed Period Start Day'),
+ 'description' => ts('For fixed period memberships, month and day (mmdd) on which subscription/membership will start. Period start is back-dated unless after rollover day.'),
+ 'where' => 'civicrm_membership_type.fixed_period_start_day',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'fixed_period_rollover_day' => array(
+ ],
+ 'fixed_period_rollover_day' => [
'name' => 'fixed_period_rollover_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Fixed Period Rollover Day') ,
- 'description' => 'For fixed period memberships, signups after this day (mmdd) rollover to next period.',
+ 'title' => ts('Fixed Period Rollover Day'),
+ 'description' => ts('For fixed period memberships, signups after this day (mmdd) rollover to next period.'),
+ 'where' => 'civicrm_membership_type.fixed_period_rollover_day',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'relationship_type_id' => array(
+ ],
+ 'relationship_type_id' => [
'name' => 'relationship_type_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Relationship') ,
- 'description' => 'FK to Relationship Type ID',
+ 'title' => ts('Membership Type Relationship'),
+ 'description' => ts('FK to Relationship Type ID'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_type.relationship_type_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'relationship_direction' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ ],
+ 'relationship_direction' => [
'name' => 'relationship_direction',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Direction') ,
+ 'title' => ts('Relationship Direction'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.relationship_direction',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'max_related' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Related Members for Type') ,
- 'description' => 'Maximum number of related memberships.',
+ 'title' => ts('Max Related Members for Type'),
+ 'description' => ts('Maximum number of related memberships.'),
+ 'where' => 'civicrm_membership_type.max_related',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'visibility' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Max Related"),
+ ],
+ ],
+ 'visibility' => [
'name' => 'visibility',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Visible') ,
+ 'title' => ts('Visible'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_type.visibility',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::memberVisibility',
- )
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
+ 'title' => ts('Order'),
+ 'where' => 'civicrm_membership_type.weight',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'receipt_text_signup' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'receipt_text_signup' => [
'name' => 'receipt_text_signup',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Receipt Text') ,
- 'description' => 'Receipt Text for membership signup',
+ 'title' => ts('Membership Type Receipt Text'),
+ 'description' => ts('Receipt Text for membership signup'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.receipt_text_signup',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'receipt_text_renewal' => array(
+ ],
+ ],
+ 'receipt_text_renewal' => [
'name' => 'receipt_text_renewal',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Renewal Text') ,
- 'description' => 'Receipt Text for membership renewal',
+ 'title' => ts('Membership Type Renewal Text'),
+ 'description' => ts('Receipt Text for membership renewal'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.receipt_text_renewal',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'auto_renew' => array(
+ ],
+ ],
+ 'auto_renew' => [
'name' => 'auto_renew',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Auto Renew') ,
- 'description' => '0 = No auto-renew option; 1 = Give option, but not required; 2 = Auto-renew required;',
+ 'title' => ts('Auto Renew'),
+ 'description' => ts('0 = No auto-renew option; 1 = Give option, but not required; 2 = Auto-renew required;'),
+ 'where' => 'civicrm_membership_type.auto_renew',
+ 'default' => '0',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'html' => [
+ 'type' => 'Radio',
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::memberAutoRenew',
- )
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_type enabled',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_type enabled'),
+ 'where' => 'civicrm_membership_type.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Enabled?"),
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -523,10 +576,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -534,24 +588,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_relationship_type_id' => array(
+ $indices = [
+ 'index_relationship_type_id' => [
'name' => 'index_relationship_type_id',
- 'field' => array(
+ 'field' => [
0 => 'relationship_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_membership_type::0::relationship_type_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/Form.php b/CRM/Member/Form.php
index 7c4196cf7f5e..3bd495fefefd 100644
--- a/CRM/Member/Form.php
+++ b/CRM/Member/Form.php
@@ -1,9 +1,9 @@
statusMessage[] = $message;
+ }
+
+ /**
+ * Get the status message.
+ *
+ * @return string
+ */
+ protected function getStatusMessage() {
+ return implode(' ', $this->statusMessage);
+ }
+
/**
* Values submitted to the form, processed along the way.
*
* @var array
*/
- protected $_params = array();
+ protected $_params = [];
+
+ /**
+ * Fields for the entity to be assigned to the template.
+ *
+ * Fields may have keys
+ * - name (required to show in tpl from the array)
+ * - description (optional, will appear below the field)
+ * - not-auto-addable - this class will not attempt to add the field using addField.
+ * (this will be automatically set if the field does not have html in it's metadata
+ * or is not a core field on the form's entity).
+ * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * - is_freeze (field should be frozen).
+ *
+ * @var array
+ */
+ protected $entityFields = [];
public function preProcess() {
// Check for edit permission.
@@ -102,16 +151,16 @@ public function preProcess() {
}
parent::preProcess();
- $params = array();
- $params['context'] = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'membership');
+ $params = [];
+ $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
$params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $params['mode'] = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
$this->setContextVariables($params);
$this->assign('context', $this->_context);
$this->assign('membershipMode', $this->_mode);
- $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, array(), TRUE);
+ $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, [], TRUE);
foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
if ($membershipType['auto_renew']) {
$this->_recurMembershipTypes[$index] = $membershipType;
@@ -129,9 +178,9 @@ public function preProcess() {
* defaults
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Member_BAO_Membership::retrieve($params, $defaults);
if (isset($defaults['minimum_fee'])) {
$defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
@@ -140,6 +189,13 @@ public function setDefaultValues() {
if (isset($defaults['status'])) {
$this->assign('membershipStatus', $defaults['status']);
}
+
+ if (!empty($defaults['is_override'])) {
+ $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
+ }
+ if (!empty($defaults['status_override_end_date'])) {
+ $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
+ }
}
if ($this->_action & CRM_Core_Action::ADD) {
@@ -153,6 +209,21 @@ public function setDefaultValues() {
$defaults['member_of_contact_id'], 'display_name'
);
}
+ if (!empty($defaults['membership_type_id'])) {
+ $this->_memType = $defaults['membership_type_id'];
+ }
+ if (is_numeric($this->_memType)) {
+ $defaults['membership_type_id'] = [];
+ $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
+ $this->_memType,
+ 'member_of_contact_id',
+ 'id'
+ );
+ $defaults['membership_type_id'][1] = $this->_memType;
+ }
+ else {
+ $defaults['membership_type_id'] = $this->_memType;
+ }
return $defaults;
}
@@ -160,14 +231,9 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
+ $this->assignSalesTaxMetadataToTemplate();
- if ($this->_mode) {
- $this->add('select', 'payment_processor_id',
- ts('Payment Processor'),
- $this->_processors, TRUE,
- array('onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');")
- );
- }
+ $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
// Build the form for auto renew. This is displayed when in credit card mode or update mode.
// The reason for showing it in update mode is not that clear.
@@ -177,7 +243,7 @@ public function buildQuickForm() {
}
$autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
- NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
+ NULL, ['onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );"]
);
if ($this->_action & CRM_Core_Action::UPDATE) {
$autoRenewElement->freeze();
@@ -193,48 +259,48 @@ public function buildQuickForm() {
$this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
if ($this->_action & CRM_Core_Action::RENEW) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Renew'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
elseif ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
@@ -289,13 +355,13 @@ public function storeContactFields($formValues) {
* @param array $params
*/
protected function setContextVariables($params) {
- $variables = array(
+ $variables = [
'action' => '_action',
'context' => '_context',
'id' => '_id',
'cid' => '_contactID',
'mode' => '_mode',
- );
+ ];
foreach ($variables as $paramKey => $classVar) {
if (isset($params[$paramKey]) && !isset($this->$classVar)) {
$this->$classVar = $params[$paramKey];
@@ -322,7 +388,7 @@ protected function setContextVariables($params) {
*/
protected function processRecurringContribution($paymentParams) {
$membershipID = $paymentParams['membership_type_id'][1];
- $contributionRecurParams = array(
+ $contributionRecurParams = [
'contact_id' => $paymentParams['contactID'],
'amount' => $paymentParams['total_amount'],
'contribution_status_id' => 'Pending',
@@ -332,18 +398,18 @@ protected function processRecurringContribution($paymentParams) {
'is_email_receipt' => $paymentParams['is_email_receipt'],
'payment_instrument_id' => $paymentParams['payment_instrument_id'],
'invoice_id' => $paymentParams['invoice_id'],
- );
+ ];
- $mapping = array(
+ $mapping = [
'frequency_interval' => 'duration_interval',
'frequency_unit' => 'duration_unit',
- );
- $membershipType = civicrm_api3('MembershipType', 'getsingle', array(
+ ];
+ $membershipType = civicrm_api3('MembershipType', 'getsingle', [
'id' => $membershipID,
'return' => $mapping,
- ));
+ ]);
- $returnParams = array('is_recur' => TRUE);
+ $returnParams = ['is_recur' => TRUE];
foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
$contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
$returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
@@ -364,14 +430,14 @@ protected function processRecurringContribution($paymentParams) {
*/
protected function ensurePriceParamsAreSet(&$formValues) {
foreach ($formValues as $key => $value) {
- if ((substr($key, 0, 6) == 'price_') && is_int(substr($key, 7))) {
+ if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
return;
}
}
$priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
$formValues['membership_type_id'][0],
$formValues['membership_type_id'][1],
- $formValues['total_amount'],
+ CRM_Utils_Array::value('total_amount', $formValues),
$this->_priceSetId
);
$formValues = array_merge($formValues, $priceFields['price_fields']);
diff --git a/CRM/Member/Form/Membership.php b/CRM/Member/Form/Membership.php
index 8d53bcf3e01f..45864f1202b6 100644
--- a/CRM/Member/Form/Membership.php
+++ b/CRM/Member/Form/Membership.php
@@ -1,9 +1,9 @@
entityFields = [
+ 'join_date' => [
+ 'name' => 'join_date',
+ 'description' => ts('Member Since'),
+ ],
+ 'start_date' => [
+ 'name' => 'start_date',
+ 'description' => ts('Start Date'),
+ ],
+ 'end_date' => [
+ 'name' => 'end_date',
+ 'description' => ts('End Date'),
+ ],
+ ];
+ }
+
+ /**
+ * Set the delete message.
*
- * @var array
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ''
+ . ts("WARNING: Deleting this membership will also delete any related payment (contribution) records." . ts("This action cannot be undone.")
+ . '
', $statusMsg);
- if ($receiptSend && !empty($mailSent)) {
- $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
- }
return $statusMsg;
}
/**
* @param $membership
- * @param $endDate
- * @param $receiptSend
- * @param $membershipTypes
- * @param $createdMemberships
- * @param $isRecur
- * @param $calcDates
- * @param $mailSend
*/
- protected function setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend) {
- $statusMsg = '';
- if (($this->_action & CRM_Core_Action::UPDATE)) {
- $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
- }
- elseif (($this->_action & CRM_Core_Action::ADD)) {
- $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
- $isRecur, $calcDates, $mailSend);
- }
-
- CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
+ protected function setStatusMessage($membership) {
//CRM-15187
// display message when membership type is changed
if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
@@ -1865,4 +1919,68 @@ protected function setStatusMessage($membership, $endDate, $receiptSend, $member
}
}
+ /**
+ * @return bool
+ */
+ protected function isUpdateToExistingRecurringMembership() {
+ $isRecur = FALSE;
+ if ($this->_action & CRM_Core_Action::UPDATE
+ && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
+ 'contribution_recur_id')
+ && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
+
+ $isRecur = TRUE;
+ }
+ return $isRecur;
+ }
+
+ /**
+ * Send a receipt for the membership.
+ *
+ * @param array $formValues
+ * @param \CRM_Member_BAO_Membership $membership
+ *
+ * @return bool
+ */
+ protected function emailMembershipReceipt($formValues, $membership) {
+ $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
+
+ return self::emailReceipt($this, $formValues, $membership, $customValues);
+ }
+
+ /**
+ * Filter the custom values from the input parameters (for display in the email).
+ *
+ * @todo figure out why the scary code this calls does & document.
+ *
+ * @param array $formValues
+ * @param \CRM_Member_BAO_Membership $membership
+ * @return array
+ */
+ protected function getCustomValuesForReceipt($formValues, $membership) {
+ $customFields = $customValues = [];
+ if (property_exists($this, '_groupTree')
+ && !empty($this->_groupTree)
+ ) {
+ foreach ($this->_groupTree as $groupID => $group) {
+ if ($groupID == 'info') {
+ continue;
+ }
+ foreach ($group['fields'] as $k => $field) {
+ $field['title'] = $field['label'];
+ $customFields["custom_{$k}"] = $field;
+ }
+ }
+ }
+
+ $members = [['member_id', '=', $membership->id, 0, 0]];
+ // check whether its a test drive
+ if ($this->_mode == 'test') {
+ $members[] = ['member_test', '=', 1, 0, 0];
+ }
+
+ CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
+ return $customValues;
+ }
+
}
diff --git a/CRM/Member/Form/MembershipBlock.php b/CRM/Member/Form/MembershipBlock.php
index 25a2751268eb..04eb474ebb95 100644
--- a/CRM/Member/Form/MembershipBlock.php
+++ b/CRM/Member/Form/MembershipBlock.php
@@ -1,9 +1,9 @@
_id)) {
$defaults = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
}
@@ -77,13 +76,13 @@ public function setDefaultValues() {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
$this->assign('isQuick', 1);
$this->_memPriceSetId = $priceSetId;
- $pFIDs = array();
+ $pFIDs = [];
if ($priceSetId) {
- CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = array(
+ CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = [
'html_type',
'name',
'label',
- ));
+ ]);
foreach ($pFIDs as $pid => $pValue) {
if ($pValue['html_type'] == 'Radio' && $pValue['name'] == 'membership_amount') {
$defaults['mem_price_field_id'] = $pValue['id'];
@@ -92,7 +91,7 @@ public function setDefaultValues() {
}
if (!empty($defaults['mem_price_field_id'])) {
- $options = array();
+ $options = [];
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($defaults['mem_price_field_id'], $options, 'id', 1);
foreach ($options as $k => $v) {
$newMembershipType[$v['membership_type_id']] = 1;
@@ -130,7 +129,7 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_required', ts('Require Membership Signup'));
$this->addElement('checkbox', 'display_min_fee', ts('Display Membership Fee'));
$this->addElement('checkbox', 'is_separate_payment', ts('Separate Membership Payment'));
- $this->addElement('text', 'membership_type_label', ts('Membership Types Label'), array('placeholder' => ts('Membership')));
+ $this->addElement('text', 'membership_type_label', ts('Membership Types Label'), ['placeholder' => ts('Membership')]);
$paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
$paymentProcessorIds = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
@@ -145,7 +144,7 @@ public function buildQuickForm() {
}
}
- $membership = $membershipDefault = $params = array();
+ $membership = $membershipDefault = $params = [];
foreach ($membershipTypes as $k => $v) {
$membership[] = $this->createElement('advcheckbox', $k, NULL, $v);
$membershipDefault[] = $this->createElement('radio', NULL, NULL, NULL, $k);
@@ -153,9 +152,9 @@ public function buildQuickForm() {
if ($isRecur) {
$autoRenew = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $k, 'auto_renew');
$membershipRequired[$k] = $autoRenew;
- $autoRenewOptions = array();
+ $autoRenewOptions = [];
if ($autoRenew) {
- $autoRenewOptions = array(ts('Not offered'), ts('Give option'), ts('Required'));
+ $autoRenewOptions = [ts('Not offered'), ts('Give option'), ts('Required')];
$this->addElement('select', "auto_renew_$k", ts('Auto-renew'), $autoRenewOptions);
//CRM-15573
if ($autoRenew == 2) {
@@ -172,7 +171,7 @@ public function buildQuickForm() {
$params['membership_types'] = serialize($membershipRequired);
CRM_Member_BAO_MembershipBlock::create($params);
}
- $this->add('hidden', "mem_price_field_id", '', array('id' => "mem_price_field_id"));
+ $this->add('hidden', "mem_price_field_id", '', ['id' => "mem_price_field_id"]);
$this->assign('is_recur', $isRecur);
if (isset($this->_renewOption)) {
$this->assign('auto_renew', $this->_renewOption);
@@ -181,7 +180,7 @@ public function buildQuickForm() {
$this->addGroup($membershipDefault, 'membership_type_default', ts('Membership Types Default'))
->setAttribute('allowClear', TRUE);
- $this->addFormRule(array('CRM_Member_Form_MembershipBlock', 'formRule'), $this->_id);
+ $this->addFormRule(['CRM_Member_Form_MembershipBlock', 'formRule'], $this->_id);
}
$price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
if (CRM_Utils_System::isNull($price)) {
@@ -190,23 +189,29 @@ public function buildQuickForm() {
else {
$this->assign('price', TRUE);
}
- $this->add('select', 'member_price_set_id', ts('Membership Price Set'), (array('' => ts('- none -')) + $price));
+ //$this->add('select', 'member_price_set_id', ts('Membership Price Set'), (['' => ts('- none -')] + $price));
+
+ $this->addField('member_price_set_id', [
+ 'entity' => 'PriceSet',
+ 'name' => 'price_set_id',
+ 'options' => $price,
+ ]);
$session = CRM_Core_Session::singleton();
$single = $session->get('singleForm');
if ($single) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
parent::buildQuickForm();
@@ -226,7 +231,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $contributionPageId = NULL) {
- $errors = array();
+ $errors = [];
if (!empty($params['member_price_set_id'])) {
//check if this price set has membership type both auto-renew and non-auto-renew memberships.
@@ -282,7 +287,7 @@ public static function formRule($params, $files, $contributionPageId = NULL) {
}
elseif (array_sum($membershipType) > CRM_Price_Form_Field::NUM_OPTION) {
// for CRM-13079
- $errors['membership_type'] = ts('You cannot select more than %1 choices. For more complex functionality, please use a Price Set.', array(1 => CRM_Price_Form_Field::NUM_OPTION));
+ $errors['membership_type'] = ts('You cannot select more than %1 choices. For more complex functionality, please use a Price Set.', [1 => CRM_Price_Form_Field::NUM_OPTION]);
}
elseif ($isRecur) {
if (empty($params['is_separate_payment']) && array_sum($membershipType) != 0) {
@@ -344,7 +349,7 @@ public function postProcess() {
$params['id'] = $membershipID;
}
- $membershipTypes = array();
+ $membershipTypes = [];
if (is_array($params['membership_type'])) {
foreach ($params['membership_type'] as $k => $v) {
if ($v) {
@@ -393,16 +398,16 @@ public function postProcess() {
$fieldParams['id'] = CRM_Utils_Array::value('mem_price_field_id', $params);
$priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('mem_price_field_id', $params), 'price_set_id');
}
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id' => $priceSetID,
'name' => 'membership_amount',
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (empty($editedResults['id'])) {
$fieldParams['name'] = strtolower(CRM_Utils_String::munge('Membership Amount', '_', 245));
if (empty($params['mem_price_field_id'])) {
- CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, array('price_set_id' => $priceSetID));
+ CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, ['price_set_id' => $priceSetID]);
}
$fieldParams['weight'] = 1;
}
@@ -416,7 +421,7 @@ public function postProcess() {
$fieldParams['is_required'] = !empty($params['is_required']) ? 1 : 0;
$fieldParams['is_display_amounts'] = !empty($params['display_min_fee']) ? 1 : 0;
$rowCount = 1;
- $options = array();
+ $options = [];
if (!empty($fieldParams['id'])) {
CRM_Core_PseudoConstant::populate($options, 'CRM_Price_DAO_PriceFieldValue', TRUE, 'membership_type_id', NULL, " price_field_id = {$fieldParams['id']} ");
}
@@ -471,12 +476,12 @@ public function postProcess() {
if ($deletePriceSet || !CRM_Utils_Array::value('member_is_active', $params, FALSE)) {
if ($this->_memPriceSetId) {
- $pFIDs = array();
- $conditionParams = array(
+ $pFIDs = [];
+ $conditionParams = [
'price_set_id' => $this->_memPriceSetId,
'html_type' => 'radio',
'name' => 'contribution_amount',
- );
+ ];
CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $conditionParams, $pFIDs);
if (empty($pFIDs['id'])) {
diff --git a/CRM/Member/Form/MembershipConfig.php b/CRM/Member/Form/MembershipConfig.php
index e3f2df0ba71d..60dc0a36a051 100644
--- a/CRM/Member/Form/MembershipConfig.php
+++ b/CRM/Member/Form/MembershipConfig.php
@@ -1,9 +1,9 @@
_id = $this->get('id');
- $this->_BAOName = $this->get('BAOName');
- }
-
/**
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
* @return array
* defaults
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
$baoName = $this->_BAOName;
$baoName::retrieve($params, $defaults);
}
@@ -111,48 +98,48 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::RENEW) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Renew'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
elseif ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/MembershipRenewal.php b/CRM/Member/Form/MembershipRenewal.php
index eaf5e2125724..02eb137ae548 100644
--- a/CRM/Member/Form/MembershipRenewal.php
+++ b/CRM/Member/Form/MembershipRenewal.php
@@ -1,9 +1,9 @@
array('default' => 'now'),
- );
+ public function setDeleteMessage() {}
/**
* Pre-process form.
*
* @throws \Exception
*/
+
+ /**
+ * Set the renewal notification status message.
+ */
+ public function setRenewalMessage() {
+ $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
+
+ if ($this->isMailSent) {
+ $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(
+ 1 => $this->_contributorEmail,
+ ));
+ }
+ CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
+ }
+
public function preProcess() {
// This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
@@ -176,13 +196,11 @@ public function preProcess() {
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
- $this->_memType = $defaults['membership_type_id'];
// set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
- list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
+ $now = date('Y-m-d');
$defaults['renewal_date'] = $now;
- $defaults['receive_date'] = $now;
- $defaults['receive_date_time'] = $currentTime;
+ $defaults['receive_date'] = $now . ' ' . date('H:i:s');
if ($defaults['id']) {
$defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
@@ -192,19 +210,6 @@ public function setDefaultValues() {
);
}
- if (is_numeric($this->_memType)) {
- $defaults['membership_type_id'] = array();
- $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
- $this->_memType,
- 'member_of_contact_id',
- 'id'
- );
- $defaults['membership_type_id'][1] = $this->_memType;
- }
- else {
- $defaults['membership_type_id'] = $this->_memType;
- }
-
$defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
//CRM-13420
@@ -225,9 +230,7 @@ public function setDefaultValues() {
$scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
$defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
- $renewalDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('renewal_date', $defaults),
- NULL, NULL, 'Y-m-d'
- );
+ $renewalDate = CRM_Utils_Array::value('renewal_date', $defaults);
$this->assign('renewalDate', $renewalDate);
$this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
@@ -245,19 +248,20 @@ public function buildQuickForm() {
parent::buildQuickForm();
$defaults = parent::setDefaultValues();
- $this->_memType = $defaults['membership_type_id'];
$this->assign('customDataType', 'Membership');
$this->assign('customDataSubType', $this->_memType);
$this->assign('entityID', $this->_id);
$selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
- $allMembershipInfo = array();
+ $allMembershipInfo = [];
- //CRM-16950
- $taxRates = CRM_Core_PseudoConstant::getTaxRates();
- $taxRate = CRM_Utils_Array::value($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id'], $taxRates);
+ // CRM-21485
+ if (is_array($defaults['membership_type_id'])) {
+ $defaults['membership_type_id'] = $defaults['membership_type_id'][1];
+ }
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
+ //CRM-16950
+ $taxRate = $this->getTaxRateForFinancialType($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id']);
// auto renew options if enabled for the membership
$options = CRM_Core_SelectValues::memberAutoRenew();
@@ -286,19 +290,20 @@ public function buildQuickForm() {
//CRM-16950
$taxAmount = NULL;
$totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
- if (CRM_Utils_Array::value($values['financial_type_id'], $taxRates)) {
+ // @todo - feels a bug - we use taxRate from the form default rather than from the specified type?!?
+ if ($this->getTaxRateForFinancialType($values['financial_type_id'])) {
$taxAmount = ($taxRate / 100) * CRM_Utils_Array::value('minimum_fee', $values);
$totalAmount = $totalAmount + $taxAmount;
}
// build membership info array, which is used to set the payment information block when
// membership type is selected.
- $allMembershipInfo[$key] = array(
+ $allMembershipInfo[$key] = [
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
'total_amount_numeric' => $totalAmount,
- 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", array(1 => CRM_Utils_Array::value('tax_term', $invoiceSettings), 2 => CRM_Utils_Money::format($taxAmount))) : $taxAmount,
- );
+ 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", [1 => $this->getSalesTaxTerm(), 2 => CRM_Utils_Money::format($taxAmount)]) : $taxAmount,
+ ];
if (!empty($values['auto_renew'])) {
$allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
@@ -325,49 +330,49 @@ public function buildQuickForm() {
$selOrgMemType[$index] = $orgMembershipType;
}
- $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);");
+ $js = ['onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);"];
$sel = &$this->addElement('hierselect',
'membership_type_id',
ts('Renewal Membership Organization and Type'), $js
);
- $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
- $elements = array();
+ $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
+ $elements = [];
if ($sel) {
$elements[] = $sel;
}
$this->applyFilter('__ALL__', 'trim');
- $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
+ $this->add('datepicker', 'renewal_date', ts('Date Renewal Entered'), [], FALSE, ['time' => FALSE]);
$this->add('select', 'financial_type_id', ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType()
);
- $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
+ $this->add('number', 'num_terms', ts('Extend Membership by'), ['onchange' => "setPaymentBlock();"], TRUE);
$this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
- $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
+ $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, ['onclick' => "checkPayment();"]);
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
- $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
$this->add('select', 'payment_instrument_id', ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
- FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
$this->add('text', 'trxn_id', ts('Transaction ID'));
$this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
- 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
+ 'objectExists', ['CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id']
);
$this->add('select', 'contribution_status_id', ts('Payment Status'),
- CRM_Contribute_PseudoConstant::contributionStatus()
+ CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('membership')
);
$this->add('text', 'check_number', ts('Check Number'),
@@ -379,7 +384,7 @@ public function buildQuickForm() {
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
}
$this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
- array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);")
+ ['onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
@@ -404,10 +409,10 @@ public function buildQuickForm() {
);
}
}
- $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
+ $this->addFormRule(['CRM_Member_Form_MembershipRenewal', 'formRule'], $this);
$this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
- $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
- $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
+ $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
+ $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
}
/**
@@ -415,12 +420,14 @@ public function buildQuickForm() {
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
+ * @param $files
+ * @param $self
*
* @return bool|array
* mixed true or array of errors
*/
- public static function formRule($params) {
- $errors = array();
+ public static function formRule($params, $files, $self) {
+ $errors = [];
if ($params['membership_type_id'][0] == 0) {
$errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link, and select a Membership Organization.');
}
@@ -428,6 +435,19 @@ public static function formRule($params) {
$errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link and select a Membership Type from the list.');
}
+ // CRM-20571
+ // Get the Join Date from Membership info as it is not available in the Renewal form
+ $joinDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $self->_id, 'join_date');
+
+ // CRM-20571: Check if the renewal date is not before Join Date, if it is then add to 'errors' array
+ // The fields in Renewal form come into this routine in $params array. 'renewal_date' is in the form
+ // We process both the dates before comparison using CRM utils so that they are in same date format
+ if (isset($params['renewal_date'])) {
+ if ($params['renewal_date'] < $joinDate) {
+ $errors['renewal_date'] = ts('Renewal date must be the same or later than Member since (Join Date).');
+ }
+ }
+
//total amount condition arise when membership type having no
//minimum fee
if (isset($params['record_contribution'])) {
@@ -454,43 +474,28 @@ public function postProcess() {
try {
$this->submit();
- $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
-
- if ($this->endDate) {
- $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(
- 1 => CRM_Utils_Date::customFormat(substr($this->endDate, 0, 8)),
- ));
- }
-
- if ($this->isMailSent) {
- $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(
- 1 => $this->_contributorEmail,
- ));
- return $statusMsg;
- }
- return $statusMsg;
+ $this->setRenewalMessage();
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
- CRM_Core_Error::displaySessionError($e->getMessage());
+ CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
));
}
-
- CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
}
/**
* Process form submission.
*
* This function is also accessed by a unit test.
+ *
+ * @throws \CRM_Core_Exception
*/
protected function submit() {
$this->storeContactFields($this->_params);
$this->beginPostProcess();
$now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
- $this->convertDateFieldsToMySQL($this->_params);
- $this->assign('receive_date', $this->_params['receive_date']);
+ $this->assign('receive_date', CRM_Utils_Array::value('receive_date', $this->_params, date('Y-m-d H:i:s')));
$this->processBillingAddress();
list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
$this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params,
@@ -525,6 +530,7 @@ protected function submit() {
$this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal");
$this->_params['amount'] = $this->_params['total_amount'];
$this->_params['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
+ $this->_params['receive_date'] = $now;
// at this point we've created a contact and stored its address etc
// all the payment processors expect the name and address to be in the passed params
@@ -557,7 +563,7 @@ protected function submit() {
$this->assign('trxn_id', $result['trxn_id']);
}
- $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($this->_params['renewal_date']) : NULL;
+ $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = $this->_params['renewal_date'] : NULL;
// check for test membership.
$isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
@@ -570,30 +576,30 @@ protected function submit() {
//if contribution status is pending then set pay later
$this->_params['is_pay_later'] = FALSE;
- if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
+ if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'))) {
$this->_params['is_pay_later'] = 1;
}
- // These variable sets prior to renewMembership may not be required for this form. They were in
+ // These variable sets prior to membership may not be required for this form. They were in
// a function this form shared with other forms.
$membershipSource = NULL;
if (!empty($this->_params['membership_source'])) {
$membershipSource = $this->_params['membership_source'];
}
- $isPending = ($this->_params['contribution_status_id'] == 2) ? TRUE : FALSE;
-
- list($renewMembership) = CRM_Member_BAO_Membership::processMembership(
+ // @todo Move this into CRM_Member_BAO_Membership::processMembership
+ $pending = ($this->_params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'));
+ list($membership) = CRM_Member_BAO_Membership::processMembership(
$this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
$renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
- $isPending,
+ $pending,
$contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id',
$this->_params)
);
- $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
+ $this->endDate = CRM_Utils_Date::processDate($membership->end_date);
- $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id,
+ $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membership->membership_type_id,
'name');
if (!empty($this->_params['record_contribution']) || $this->_mode) {
@@ -601,7 +607,7 @@ protected function submit() {
$this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
//create line items
- $lineItem = array();
+ $lineItem = [];
$this->_params = $this->setPriceSetParameters($this->_params);
CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
$this->_params, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId
@@ -624,10 +630,10 @@ protected function submit() {
if ($this->_contributorContactID != $this->_contactID) {
$this->_params['contribution_contact_id'] = $this->_contributorContactID;
if (!empty($this->_params['soft_credit_type_id'])) {
- $this->_params['soft_credit'] = array(
+ $this->_params['soft_credit'] = [
'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
'contact_id' => $this->_contactID,
- );
+ ];
}
}
$this->_params['contact_id'] = $this->_contactID;
@@ -635,10 +641,10 @@ protected function submit() {
// not a great pattern & ideally it would not receive as a reference. We assign our params as a
// temporary variable to avoid e-notice & to make it clear to future refactorer that
// this function is NOT reliant on that var being set
- $temporaryParams = array_merge($this->_params, array(
- 'membership_id' => $renewMembership->id,
+ $temporaryParams = array_merge($this->_params, [
+ 'membership_id' => $membership->id,
'contribution_recur_id' => $contributionRecurID,
- ));
+ ]);
//Remove `tax_amount` if it is not calculated.
if (CRM_Utils_Array::value('tax_amount', $temporaryParams) === 0) {
unset($temporaryParams['tax_amount']);
@@ -647,72 +653,82 @@ protected function submit() {
}
if (!empty($this->_params['send_receipt'])) {
+ $this->sendReceipt($membership);
+ }
+ }
- $receiptFrom = $this->_params['from_email_address'];
-
- if (!empty($this->_params['payment_instrument_id'])) {
- $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
- $this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
- }
- //get the group Tree
- $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
+ /**
+ * Send a receipt.
+ *
+ * @param array $membership
+ *
+ * @throws \CRM_Core_Exception
+ */
+ protected function sendReceipt($membership) {
+ $receiptFrom = $this->_params['from_email_address'];
- // retrieve custom data
- $customFields = $customValues = $fo = array();
- foreach ($this->_groupTree as $groupID => $group) {
- if ($groupID == 'info') {
- continue;
- }
- foreach ($group['fields'] as $k => $field) {
- $field['title'] = $field['label'];
- $customFields["custom_{$k}"] = $field;
- }
+ if (!empty($this->_params['payment_instrument_id'])) {
+ $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
+ $this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
+ }
+ //get the group Tree
+ $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->_id, FALSE, $this->_memType);
+
+ // retrieve custom data
+ $customFields = $customValues = $fo = [];
+ foreach ($this->_groupTree as $groupID => $group) {
+ if ($groupID == 'info') {
+ continue;
}
- $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
- // check whether its a test drive
- if ($this->_mode == 'test') {
- $members[] = array('member_test', '=', 1, 0, 0);
+ foreach ($group['fields'] as $k => $field) {
+ $field['title'] = $field['label'];
+ $customFields["custom_{$k}"] = $field;
}
- CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
+ }
+ $members = [['member_id', '=', $this->_membershipId, 0, 0]];
+ // check whether its a test drive
+ if ($this->_mode == 'test') {
+ $members[] = ['member_test', '=', 1, 0, 0];
+ }
+ CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
- $this->assign_by_ref('formValues', $this->_params);
- if (!empty($this->_params['contribution_id'])) {
- $this->assign('contributionID', $this->_params['contribution_id']);
- }
+ $this->assign_by_ref('formValues', $this->_params);
+ if (!empty($this->_params['contribution_id'])) {
+ $this->assign('contributionID', $this->_params['contribution_id']);
+ }
- $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
- $renewMembership->membership_type_id
+ $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
+ $membership->membership_type_id
+ ));
+ $this->assign('customValues', $customValues);
+ $this->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date));
+ $this->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date));
+ if ($this->_mode) {
+ $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
+ $this->_params,
+ $this->_bltID
));
- $this->assign('customValues', $customValues);
- $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
- $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
- if ($this->_mode) {
- $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
- $this->_params,
- $this->_bltID
- ));
- $this->assign('contributeMode', 'direct');
- $this->assign('isAmountzero', 0);
- $this->assign('is_pay_later', 0);
- $this->assign('isPrimary', 1);
- $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
- if ($this->_mode == 'test') {
- $this->assign('action', '1024');
- }
+ $this->assign('contributeMode', 'direct');
+ $this->assign('isAmountzero', 0);
+ $this->assign('is_pay_later', 0);
+ $this->assign('isPrimary', 1);
+ $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
+ if ($this->_mode == 'test') {
+ $this->assign('action', '1024');
}
-
- list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
- 'groupName' => 'msg_tpl_workflow_membership',
- 'valueName' => 'membership_offline_receipt',
- 'contactId' => $this->_receiptContactId,
- 'from' => $receiptFrom,
- 'toName' => $this->_contributorDisplayName,
- 'toEmail' => $this->_contributorEmail,
- 'isTest' => $this->_mode == 'test',
- )
- );
}
+
+ list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
+ [
+ 'groupName' => 'msg_tpl_workflow_membership',
+ 'valueName' => 'membership_offline_receipt',
+ 'contactId' => $this->_receiptContactId,
+ 'from' => $receiptFrom,
+ 'toName' => $this->_contributorDisplayName,
+ 'toEmail' => $this->_contributorEmail,
+ 'isTest' => $this->_mode == 'test',
+ ]
+ );
}
}
diff --git a/CRM/Member/Form/MembershipStatus.php b/CRM/Member/Form/MembershipStatus.php
index e20ec7f86cf6..5f644507e375 100644
--- a/CRM/Member/Form/MembershipStatus.php
+++ b/CRM/Member/Form/MembershipStatus.php
@@ -1,9 +1,9 @@
'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'label' => [
+ 'name' => 'label',
+ 'description' => ts("Display name for this Membership status (e.g. New, Current, Grace, Expired...)."),
+ 'required' => TRUE,
+ ],
+ 'is_admin' => [
+ 'name' => 'is_admin',
+ 'description' => ts("Check this box if this status is for use by administrative staff only. If checked, this status is never automatically assigned by CiviMember. It is assigned to a contact's Membership by checking the Status Override flag when adding or editing the Membership record. Start and End Event settings are ignored for Administrator statuses. EXAMPLE: This setting can be useful for special case statuses like 'Non-expiring', 'Barred' or 'Expelled', etc."),
+ ],
+ ];
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('You will not be able to delete this membership status if there are existing memberships with this status. You will need to check all your membership status rules afterwards to ensure that a valid status will always be available.') . " " . ts('Do you want to continue?');
+ }
+
+ public function preProcess() {
+ $this->_id = $this->get('id');
+ $this->_BAOName = 'CRM_Member_BAO_MembershipStatus';
+ }
/**
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
*/
public function setDefaultValues() {
- $defaults = parent::setDefaultValues();
+ $defaults = $this->getEntityDefaults();
+
+ if ($this->_action & CRM_Core_Action::ADD) {
+ $defaults['is_active'] = 1;
+ }
//finding default weight to be put
if (empty($defaults['weight'])) {
@@ -58,18 +121,15 @@ public function setDefaultValues() {
/**
* Build the form object.
- *
- * @return void
*/
public function buildQuickForm() {
+ self::buildQuickEntityForm();
parent::buildQuickForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
- $this->applyFilter('__ALL__', 'trim');
-
if ($this->_id) {
$name = $this->add('text', 'name', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'name')
@@ -77,27 +137,23 @@ public function buildQuickForm() {
$name->freeze();
$this->assign('id', $this->_id);
}
- $this->add('text', 'label', ts('Label'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'label'), TRUE
- );
$this->addRule('label', ts('A membership status with this label already exists. Please select another label.'),
- 'objectExists', array('CRM_Member_DAO_MembershipStatus', $this->_id, 'name')
+ 'objectExists', ['CRM_Member_DAO_MembershipStatus', $this->_id, 'name']
);
$this->add('select', 'start_event', ts('Start Event'), CRM_Core_SelectValues::eventDate(), TRUE);
- $this->add('select', 'start_event_adjust_unit', ts('Start Event Adjustment'), array('' => ts('- select -')) + CRM_Core_SelectValues::unitList());
+ $this->add('select', 'start_event_adjust_unit', ts('Start Event Adjustment'), ['' => ts('- select -')] + CRM_Core_SelectValues::unitList());
$this->add('text', 'start_event_adjust_interval', ts('Start Event Adjust Interval'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'start_event_adjust_interval')
);
- $this->add('select', 'end_event', ts('End Event'), array('' => ts('- select -')) + CRM_Core_SelectValues::eventDate());
- $this->add('select', 'end_event_adjust_unit', ts('End Event Adjustment'), array('' => ts('- select -')) + CRM_Core_SelectValues::unitList());
+ $this->add('select', 'end_event', ts('End Event'), ['' => ts('- select -')] + CRM_Core_SelectValues::eventDate());
+ $this->add('select', 'end_event_adjust_unit', ts('End Event Adjustment'), ['' => ts('- select -')] + CRM_Core_SelectValues::unitList());
$this->add('text', 'end_event_adjust_interval', ts('End Event Adjust Interval'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'end_event_adjust_interval')
);
$this->add('checkbox', 'is_current_member', ts('Current Membership?'));
- $this->add('checkbox', 'is_admin', ts('Administrator Only?'));
- $this->add('text', 'weight', ts('Order'),
+ $this->add('number', 'weight', ts('Order'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'weight')
);
$this->add('checkbox', 'is_default', ts('Default?'));
@@ -106,9 +162,6 @@ public function buildQuickForm() {
/**
* Process the form submission.
- *
- *
- * @return void
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
@@ -121,7 +174,6 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected membership status has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $params = $ids = array();
// store the submitted values in an array
$params = $this->exportValues();
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
@@ -130,7 +182,7 @@ public function postProcess() {
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['membershipStatus'] = $this->_id;
+ $params['id'] = $this->getEntityId();
}
$oldWeight = NULL;
if ($this->_id) {
@@ -143,9 +195,9 @@ public function postProcess() {
$params['name'] = $params['label'];
}
- $membershipStatus = CRM_Member_BAO_MembershipStatus::add($params, $ids);
+ $membershipStatus = CRM_Member_BAO_MembershipStatus::add($params);
CRM_Core_Session::setStatus(ts('The membership status \'%1\' has been saved.',
- array(1 => $membershipStatus->label)
+ [1 => $membershipStatus->label]
), ts('Saved'), 'success');
}
}
diff --git a/CRM/Member/Form/MembershipType.php b/CRM/Member/Form/MembershipType.php
index 026f7ab70e3e..1ffafe2a3324 100644
--- a/CRM/Member/Form/MembershipType.php
+++ b/CRM/Member/Form/MembershipType.php
@@ -1,9 +1,9 @@
'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * - is_freeze (field should be frozen).
+ *
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'name' => [
+ 'required' => 'TRUE',
+ 'name' => 'name',
+ 'description' => ts("e.g. 'Student', 'Senior', 'Honor Society'..."),
+ ],
+ 'description' => [
+ 'name' => 'description',
+ 'description' => ts("Description of this membership type for internal use. May include eligibility, benefits, terms, etc."),
+ ],
+ 'member_of_contact_id' => [
+ 'name' => 'member_of_contact_id',
+ 'description' => ts("Members assigned this membership type belong to which organization (e.g. this is for membership in 'Save the Whales - Northwest Chapter'). NOTE: This organization/group/chapter must exist as a CiviCRM Organization type contact."),
+ ],
+ 'minimum_fee' => [
+ 'name' => 'minimum_fee',
+ 'description' => ts('Minimum fee required for this membership type. For free/complimentary memberships - set minimum fee to zero (0). NOTE: When using CiviCRM to process sales taxes this should be the tax exclusive amount.'),
+ 'formatter' => 'crmMoney',
+ ],
+ 'financial_type_id' => [
+ 'name' => 'financial_type_id',
+ 'description' => ts('Select the financial type assigned to fees for this membership type (for example \'Membership Fees\'). This is required for all membership types - including free or complimentary memberships.'),
+ ],
+ 'auto_renew' => [
+ 'name' => 'auto_renew',
+ 'options' => CRM_Core_SelectValues::memberAutoRenew(),
+ 'place_holder' => ts('You will need to select and configure a supported payment processor (currently Authorize.Net, PayPal Pro, or PayPal Website Standard) in order to offer automatically renewing memberships.'),
+ ],
+ 'duration_interval' => [
+ 'name' => 'duration_interval',
+ 'required' => TRUE,
+ ],
+ 'duration_unit' => [
+ 'name' => 'duration_unit',
+ 'description' => ts('Duration of this membership (e.g. 30 days, 2 months, 5 years, 1 lifetime)'),
+ 'required' => TRUE,
+ ],
+ 'period_type' => [
+ 'name' => 'period_type',
+ 'description' => ts("Select 'rolling' if membership periods begin at date of signup. Select 'fixed' if membership periods begin on a set calendar date."),
+ 'help' => ['id' => 'period-type', 'file' => "CRM/Member/Page/MembershipType.hlp"],
+ 'required' => TRUE,
+ ],
+ 'fixed_period_start_day' => [
+ 'name' => 'fixed_period_start_day',
+ 'description' => ts("Month and day on which a fixed period membership or subscription begins. Example: A fixed period membership with Start Day set to Jan 01 means that membership periods would be 1/1/06 - 12/31/06 for anyone signing up during 2006."),
+ ],
+ 'fixed_period_rollover_day' => [
+ 'name' => 'fixed_period_rollover_day',
+ 'description' => ts('Membership signups on or after this date cover the following calendar year as well. Example: If the rollover day is November 30, membership period for signups during December will cover the following year.'),
+ ],
+ 'relationship_type_id' => [
+ 'name' => 'relationship_type_id',
+ ],
+ 'max_related' => [
+ 'name' => 'max_related',
+ 'description' => ts('Maximum number of related memberships (leave blank for unlimited).'),
+ ],
+ 'visibility' => [
+ 'name' => 'visibility',
+ 'description' => ts("Can this membership type be used for self-service signups ('Public'), or is it only for CiviCRM users with 'Edit Contributions' permission ('Admin')."),
+ ],
+ 'weight' => [
+ 'name' => 'weight',
+ ],
+ 'is_active' => [
+ 'name' => 'is_active',
+ ],
+ ];
+
+ if (!CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(['Recurring'])) {
+ $this->entityFields['auto_renew']['not-auto-addable'] = TRUE;
+ $this->entityFields['auto_renew']['documentation_link'] = ['page' => 'user/contributions/payment-processors'];
+ }
+ }
+
+ /**
+ * Deletion message to be assigned to the form.
+ *
+ * @var string
+ */
+ protected $deleteMessage;
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'MembershipType';
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('WARNING: Deleting this option will result in the loss of all membership records of this type.') . ts('This may mean the loss of a substantial amount of data, and the action cannot be undone.') . ts('Do you want to continue?');
+ }
+
+ /**
+ * Explicitly declare the form context.
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Max number of contacts we will display for membership-organisation
*/
@@ -61,8 +190,8 @@ public function preProcess() {
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
+ * defaults
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
@@ -77,19 +206,19 @@ public function setDefaultValues() {
// Set values for relation type select box
$relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_type_id']);
$relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_direction']);
- $defaults['relationship_type_id'] = array();
+ $defaults['relationship_type_id'] = [];
foreach ($relTypeIds as $key => $value) {
$defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
}
}
//setting default fixed_period_start_day & fixed_period_rollover_day
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
foreach ($periods as $per) {
if (isset($defaults[$per])) {
$date = $defaults[$per];
- $defaults[$per] = array();
+ $defaults[$per] = [];
if ($date > 31) {
$date = ($date < 999) ? '0' . $date : $date;
$defaults[$per]['M'] = substr($date, 0, 2);
@@ -109,38 +238,27 @@ public function setDefaultValues() {
* Build the form object.
*
* @return void
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function buildQuickForm() {
- parent::buildQuickForm();
+ self::buildQuickEntityForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
-
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
+ // This is a temporary variable as we work towards moving over towards using the EntityField.tpl.
+ // Fields in this array have been tested & in the tpl have been switched over to metadata.
+ // Note this kinda 'works from the top' - ie. once we hit a field that needs some thought we need
+ // to stop & make that one work.
+ $this->assign('tpl_standardised_fields', ['name', 'description', 'member_of_contact_id', 'minimum_fee']);
$this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
- 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)
- );
- $this->add('text', 'description', ts('Description'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')
- );
- $this->add('text', 'minimum_fee', ts('Minimum Fee'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')
+ 'objectExists', ['CRM_Member_DAO_MembershipType', $this->_id]
);
$this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
- $this->addSelect('duration_unit', array(), TRUE);
-
- //period type
- $this->addSelect('period_type', array(), TRUE);
-
- $this->add('text', 'duration_interval', ts('Duration Interval'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')
- );
-
- $props = array('api' => array('params' => array('contact_type' => 'Organization')));
+ $props = ['api' => ['params' => ['contact_type' => 'Organization']]];
$this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
//start day
@@ -148,11 +266,10 @@ public function buildQuickForm() {
CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
);
- //Auto-renew Option
- $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
+ // Add Auto-renew options if we have a payment processor that supports recurring contributions
$isAuthorize = FALSE;
- $options = array();
- if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
+ $options = [];
+ if (CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(['Recurring'])) {
$isAuthorize = TRUE;
$options = CRM_Core_SelectValues::memberAutoRenew();
}
@@ -160,7 +277,7 @@ public function buildQuickForm() {
$this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
$this->assign('authorize', $isAuthorize);
- //rollover day
+ // rollover day
$this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
);
@@ -168,7 +285,7 @@ public function buildQuickForm() {
CRM_Core_SelectValues::date(NULL, 'd'), FALSE
);
$this->add('select', 'financial_type_id', ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, array('class' => 'crm-select2')
+ ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, ['class' => 'crm-select2']
);
$relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
@@ -176,36 +293,26 @@ public function buildQuickForm() {
asort($relTypeInd);
}
$memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'),
- $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1));
+ $relTypeInd, FALSE, ['class' => 'crm-select2 huge', 'multiple' => 1]);
- $this->addSelect('visibility', array('placeholder' => NULL, 'option_url' => NULL));
-
- $this->add('text', 'weight', ts('Order'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')
- );
- $this->add('checkbox', 'is_active', ts('Enabled?'));
+ $this->addField('visibility', ['placeholder' => NULL, 'option_url' => NULL]);
$membershipRecords = FALSE;
if ($this->_action & CRM_Core_Action::UPDATE) {
- $membershipType = new CRM_Member_BAO_Membership();
- $membershipType->membership_type_id = $this->_id;
- if ($membershipType->find(TRUE)) {
- $membershipRecords = TRUE;
+ $result = civicrm_api3("Membership", "get", ["membership_type_id" => $this->_id, "options" => ["limit" => 1]]);
+ $membershipRecords = ($result["count"] > 0);
+ if ($membershipRecords) {
$memberRel->freeze();
}
}
$this->assign('membershipRecordsExists', $membershipRecords);
- $this->add('text', 'max_related', ts('Max related'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related')
- );
-
- $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
+ $this->addFormRule(['CRM_Member_Form_MembershipType', 'formRule']);
$this->assign('membershipTypeId', $this->_id);
- if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
+ if (Civi::settings()->get('deferred_revenue_enabled')) {
$deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
$this->assign('deferredFinancialType', array_keys($deferredFinancialType));
}
@@ -221,7 +328,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!$params['name']) {
$errors['name'] = ts('Please enter a membership type name.');
@@ -235,10 +342,10 @@ public static function formRule($params) {
$errors['duration_interval'] = ts('Please enter a duration interval.');
}
- if (in_array(CRM_Utils_Array::value('auto_renew', $params), array(
+ if (in_array(CRM_Utils_Array::value('auto_renew', $params), [
1,
2,
- ))) {
+ ])) {
if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
) {
@@ -255,7 +362,7 @@ public static function formRule($params) {
if (($params['period_type'] == 'fixed') &&
($params['duration_unit'] == 'year')
) {
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
foreach ($periods as $period) {
$month = $params[$period]['M'];
$date = $params[$period]['d'];
@@ -293,7 +400,6 @@ public static function formRule($params) {
/**
* Process the form submission.
*
- *
* @return void
*/
public function postProcess() {
@@ -307,43 +413,17 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $buttonName = $this->controller->getButtonName();
- $submitted = $this->controller->exportValues($this->_name);
-
- $fields = array(
- 'name',
- 'weight',
- 'is_active',
- 'member_of_contact_id',
- 'visibility',
- 'period_type',
- 'minimum_fee',
- 'description',
- 'auto_renew',
- 'duration_unit',
- 'duration_interval',
- 'financial_type_id',
- 'fixed_period_start_day',
- 'fixed_period_rollover_day',
- 'month_fixed_period_rollover_day',
- 'max_related',
- );
+ $params = $this->exportValues();
- $params = $ids = array();
- foreach ($fields as $fld) {
- $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
- }
-
- //clean money.
if ($params['minimum_fee']) {
$params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
}
$hasRelTypeVal = FALSE;
- if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
+ if (!CRM_Utils_System::isNull($params['relationship_type_id'])) {
// To insert relation ids and directions with value separator
- $relTypeDirs = $submitted['relationship_type_id'];
- $relIds = $relDirection = array();
+ $relTypeDirs = $params['relationship_type_id'];
+ $relIds = $relDirection = [];
foreach ($relTypeDirs as $key => $value) {
$relationId = explode('_', $value);
if (count($relationId) == 3 &&
@@ -360,7 +440,7 @@ public function postProcess() {
}
}
if (!$hasRelTypeVal) {
- $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'NULL';
+ $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'null';
}
if ($params['duration_unit'] == 'lifetime' &&
@@ -369,21 +449,21 @@ public function postProcess() {
$params['duration_interval'] = 1;
}
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
- foreach ($periods as $per) {
- if (!empty($params[$per]['M']) && !empty($params[$per]['d'])) {
- $mon = $params[$per]['M'];
- $dat = $params[$per]['d'];
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
+ foreach ($periods as $period) {
+ if (!empty($params[$period]['M']) && !empty($params[$period]['d'])) {
+ $mon = $params[$period]['M'];
+ $dat = $params[$period]['d'];
$mon = ($mon < 10) ? '0' . $mon : $mon;
$dat = ($dat < 10) ? '0' . $dat : $dat;
- $params[$per] = $mon . $dat;
+ $params[$period] = $mon . $dat;
}
- elseif ($per == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
+ elseif ($period == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
$params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
unset($params['month_fixed_period_rollover_day']);
}
else {
- $params[$per] = 'NULL';
+ $params[$period] = 'null';
}
}
$oldWeight = NULL;
@@ -398,15 +478,17 @@ public function postProcess() {
);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['membershipType'] = $this->_id;
+ $params['id'] = $this->_id;
}
- $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
+ $membershipTypeResult = civicrm_api3('MembershipType', 'create', $params);
+ $membershipTypeName = $membershipTypeResult['values'][$membershipTypeResult['id']]['name'];
- CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.',
- array(1 => $membershipType->name)
+ CRM_Core_Session::setStatus(ts("The membership type '%1' has been saved.",
+ [1 => $membershipTypeName]
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
+ $buttonName = $this->controller->getButtonName();
if ($buttonName == $this->getButtonName('upload', 'new')) {
$session->replaceUserContext(
CRM_Utils_System::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
@@ -423,18 +505,18 @@ public function postProcess() {
*/
public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
if ($previousID) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id ' => $priceSetId,
'name' => $previousID,
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (!empty($editedResults)) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_field_id' => $editedResults['id'],
'membership_type_id' => $membershipTypeId,
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
$optionsIds['option_id'][1] = CRM_Utils_Array::value('id', $editedResults);
}
diff --git a/CRM/Member/Form/MembershipView.php b/CRM/Member/Form/MembershipView.php
index 8bb29aa7d2d2..ceca87f219d8 100644
--- a/CRM/Member/Form/MembershipView.php
+++ b/CRM/Member/Form/MembershipView.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=delete&mid=%%mid%%&reset=1' . $this->addContext(),
'title' => ts('Cancel Related Membership'),
- ),
- CRM_Core_Action::ADD => array(
+ ],
+ CRM_Core_Action::ADD => [
'name' => ts('Create'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=create&rid=%%rid%%&reset=1' . $this->addContext(),
'title' => ts('Create Related Membership'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -103,13 +116,12 @@ public function relAction($action, $owner) {
$relatedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$relatedDisplayName = CRM_Contact_BAO_Contact::displayName($relatedContactId);
CRM_Member_BAO_Membership::del($id);
- CRM_Core_Session::setStatus(ts('Related membership for %1 has been deleted.', array(1 => $relatedDisplayName)),
+ CRM_Core_Session::setStatus(ts('Related membership for %1 has been deleted.', [1 => $relatedDisplayName]),
ts('Membership Deleted'), 'success');
break;
case 'create':
- $ids = array();
- $params = array(
+ $params = [
'contact_id' => CRM_Utils_Request::retrieve('rid', 'Positive', $this),
'membership_type_id' => $owner['membership_type_id'],
'owner_membership_id' => $owner['id'],
@@ -122,10 +134,12 @@ public function relAction($action, $owner) {
'status_id' => $owner['status_id'],
'skipStatusCal' => TRUE,
'createActivity' => TRUE,
- );
+ ];
+ // @todo stop passing $ids here (we are only doing so because of passbyreference)
+ $ids = [];
CRM_Member_BAO_Membership::create($params, $ids);
$relatedDisplayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
- CRM_Core_Session::setStatus(ts('Related membership for %1 has been created.', array(1 => $relatedDisplayName)),
+ CRM_Core_Session::setStatus(ts('Related membership for %1 has been created.', [1 => $relatedDisplayName]),
ts('Membership Added'), 'success');
break;
@@ -148,22 +162,22 @@ public function relAction($action, $owner) {
* @return void
*/
public function preProcess() {
-
- $values = array();
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
+ $values = [];
+ $this->membershipID = CRM_Utils_Request::retrieve('id', 'Positive', $this);
+ $this->contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
// Make sure context is assigned to template for condition where we come here view civicrm/membership/view
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $context);
- if ($id) {
- $params = array('id' => $id);
+ if ($this->membershipID) {
+ $params = ['id' => $this->membershipID];
CRM_Member_BAO_Membership::retrieve($params, $values);
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
$finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values['membership_type_id'], 'financial_type_id');
$finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
if (!CRM_Core_Permission::check('view contributions of type ' . $finType)) {
- CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
}
}
else {
@@ -181,12 +195,12 @@ public function preProcess() {
$this->assign('accessContribution', FALSE);
if (CRM_Core_Permission::access('CiviContribute')) {
$this->assign('accessContribution', TRUE);
- CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $id);
+ CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $this->membershipID);
}
//Provide information about membership source when it is the result of a relationship (CRM-1901)
$values['owner_membership_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
- $id,
+ $this->membershipID,
'owner_membership_id'
);
@@ -242,8 +256,7 @@ public function preProcess() {
$relTypeId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
$relDirection = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
foreach ($relTypeId as $rid) {
- $dir = each($relDirection);
- $relTypeDir[substr($dir['value'], 0, 1)][] = $rid;
+ $relTypeDir[substr($relDirection[0], 0, 1)][] = $rid;
}
// build query in 2 parts with a UNION if necessary
// _x and _y are replaced with _a and _b first, then vice-versa
@@ -260,7 +273,7 @@ public function preProcess() {
LEFT JOIN civicrm_membership_status ms ON ms.id = m.status_id
WHERE r.contact_id_y = {$values['contact_id']} AND r.is_active = 1 AND c.is_deleted = 0";
$query = '';
- foreach (array('a', 'b') as $dir) {
+ foreach (['a', 'b'] as $dir) {
if (isset($relTypeDir[$dir])) {
$query .= ($query ? ' UNION ' : '')
. str_replace('_y', '_' . $dir, str_replace('_x', '_' . ($dir == 'a' ? 'b' : 'a'), $select))
@@ -269,9 +282,9 @@ public function preProcess() {
}
$query .= " ORDER BY is_current_member DESC";
$dao = CRM_Core_DAO::executeQuery($query);
- $related = array();
+ $related = [];
$relatedRemaining = CRM_Utils_Array::value('max_related', $values, PHP_INT_MAX);
- $rowElememts = array(
+ $rowElememts = [
'id',
'cid',
'name',
@@ -282,21 +295,21 @@ public function preProcess() {
'end_date',
'is_current_member',
'status',
- );
+ ];
while ($dao->fetch()) {
- $row = array();
+ $row = [];
foreach ($rowElememts as $field) {
$row[$field] = $dao->$field;
}
if ($row['mid'] && ($row['is_current_member'] == 1)) {
$relatedRemaining--;
$row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::DELETE,
- array(
+ [
'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
'cid' => $row['cid'],
'mid' => $row['mid'],
- ),
+ ],
ts('more'),
FALSE,
'membership.relationship.action',
@@ -307,11 +320,11 @@ public function preProcess() {
else {
if ($relatedRemaining > 0) {
$row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::ADD,
- array(
+ [
'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
'cid' => $row['cid'],
'rid' => $row['cid'],
- ),
+ ],
ts('more'),
FALSE,
'membership.relationship.action',
@@ -328,10 +341,10 @@ public function preProcess() {
}
else {
if ($relatedRemaining < 100000) {
- $this->assign('related_text', ts('%1 available', array(1 => $relatedRemaining)));
+ $this->assign('related_text', ts('%1 available', [1 => $relatedRemaining]));
}
else {
- $this->assign('related_text', ts('Unlimited', array(1 => $relatedRemaining)));
+ $this->assign('related_text', ts('Unlimited', [1 => $relatedRemaining]));
}
}
}
@@ -353,7 +366,7 @@ public function preProcess() {
"action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -375,21 +388,21 @@ public function preProcess() {
CRM_Member_Page_Tab::setContext($this, $values['contact_id']);
- $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $id, "membership_type_id");
+ $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $this->membershipID, "membership_type_id");
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $id, 0, $memType);
- CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $id);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->membershipID, 0, $memType);
+ CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->membershipID);
- $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'contribution_recur_id');
+ $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->membershipID, 'contribution_recur_id');
$autoRenew = $isRecur ? TRUE : FALSE;
}
if (!empty($values['is_test'])) {
- $values['membership_type'] .= ' (test) ';
+ $values['membership_type'] = CRM_Core_TestEntity::appendTestText($values['membership_type']);
}
- $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($id);
+ $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->membershipID);
$values['auto_renew'] = ($autoRenew && !$subscriptionCancelled) ? 'Yes' : 'No';
//do check for campaigns
@@ -407,14 +420,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Search.php b/CRM/Member/Form/Search.php
index 0ff54544bb29..3d7afe8ffcd6 100644
--- a/CRM/Member/Form/Search.php
+++ b/CRM/Member/Form/Search.php
@@ -1,9 +1,9 @@
_done = FALSE;
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
-
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -106,6 +95,8 @@ public function preProcess() {
}
if ($this->_force) {
+ $this->addSearchFieldMetadata(['Membership' => CRM_Member_BAO_Query::getSearchFieldMetadata()]);
+ $this->addFormFieldsFromMetadata();
$this->postProcess();
$this->set('force', 0);
}
@@ -153,7 +144,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Member_BAO_Query::buildSearchForm($this);
@@ -163,9 +154,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Member_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Member_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -192,6 +181,36 @@ protected function getSortNameLabelWithOutEmail() {
return ts('Member Name');
}
+ /**
+ * Get the label for the tag field.
+ *
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
+ *
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Member Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getGroupLabel() {
+ return ts('Member Group(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Member Contact Type');
+ }
+
/**
* The post processing of the form gets done here.
*
@@ -210,8 +229,7 @@ public function postProcess() {
}
$this->_done = TRUE;
-
- $this->_formValues = $this->controller->exportValues($this->_name);
+ $this->setFormValues();
$this->fixFormValues();
@@ -275,17 +293,6 @@ public function postProcess() {
$controller->run();
}
- /**
- * Set default values.
- *
- * @todo - can this function override be removed?
- *
- * @return array
- */
- public function setDefaultValues() {
- return $this->_defaults;
- }
-
/**
* If this search has been forced then see if there are any get values, and if so over-ride the post values.
*
@@ -305,8 +312,8 @@ public function fixFormValues() {
$membershipType = CRM_Utils_Request::retrieve('type', 'String');
if ($membershipType) {
- $this->_formValues['membership_type_id'] = array($membershipType);
- $this->_defaults['membership_type_id'] = array($membershipType);
+ $this->_formValues['membership_type_id'] = [$membershipType];
+ $this->_defaults['membership_type_id'] = [$membershipType];
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive');
@@ -353,8 +360,8 @@ public function fixFormValues() {
//LCD also allow restrictions to membership owner via GET
$owner = CRM_Utils_Request::retrieve('owner', 'String');
- if ($owner) {
- $this->_formValues['member_is_primary'] = $this->_defaults['member_is_primary'] = 2;
+ if (in_array($owner, ['0', '1'])) {
+ $this->_formValues['member_is_primary'] = $this->_defaults['member_is_primary'] = $owner;
}
}
diff --git a/CRM/Member/Form/Task.php b/CRM/Member/Form/Task.php
index 7624334c19e5..7cc08118ee44 100644
--- a/CRM/Member/Form/Task.php
+++ b/CRM/Member/Form/Task.php
@@ -1,9 +1,9 @@
_memberIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_memberIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
- $memberTasks = CRM_Member_Task::tasks();
- $form->assign('taskName', $memberTasks[$form->_task]);
+ $tasks = CRM_Member_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission());
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -156,7 +130,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_memberIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_memberIds,
'civicrm_membership'
);
}
@@ -174,17 +148,17 @@ public function setContactIDs() {
* @return void
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => $backType,
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Task/Batch.php b/CRM/Member/Form/Task/Batch.php
index 32e513a47d93..35cc5a6b0988 100644
--- a/CRM/Member/Form/Task/Batch.php
+++ b/CRM/Member/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Name')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Name')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -96,12 +96,12 @@ public function buildQuickForm() {
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -119,24 +119,24 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Update Members(s)'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_memberIds);
//load all campaigns.
if (array_key_exists('member_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Member_DAO_Membership',
TRUE, 'campaign_id', 'id',
@@ -150,7 +150,7 @@ public function buildQuickForm() {
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
- $entityColumnValue = array();
+ $entityColumnValue = [];
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
@@ -175,7 +175,7 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple memberships."), ts('Unsupported Field Type'), 'error');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple memberships."), ts('Unsupported Field Type'), 'error');
}
$this->addDefaultButtons(ts('Update Memberships'));
@@ -192,7 +192,7 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_memberIds as $memberId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $memberId, 'Membership');
}
@@ -208,13 +208,16 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
- $dates = array(
- 'join_date',
+ // @todo extract submit functions &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test
+ // handling of custom data, specifically checkbox fields.
+ $dates = [
+ 'membership_join_date',
'membership_start_date',
'membership_end_date',
- );
+ ];
if (isset($params['field'])) {
- $customFields = array();
+ $customFields = [];
foreach ($params['field'] as $key => $value) {
$ids['membership'] = $key;
if (!empty($value['membership_source'])) {
diff --git a/CRM/Member/Form/Task/Delete.php b/CRM/Member/Form/Task/Delete.php
index 21efb65d0b2c..a53b2bd34b9c 100644
--- a/CRM/Member/Form/Task/Delete.php
+++ b/CRM/Member/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count memberships deleted.', 'count' => $deleted));
+ $msg = ts('%count membership deleted.', ['plural' => '%count memberships deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Member/Form/Task/Email.php b/CRM/Member/Form/Task/Email.php
index 2efd8140ec92..d58985192307 100644
--- a/CRM/Member/Form/Task/Email.php
+++ b/CRM/Member/Form/Task/Email.php
@@ -1,9 +1,9 @@
array('IN' => $this->_memberIds),
+ $labelRows = [];
+ $memberships = civicrm_api3('membership', 'get', [
+ 'id' => ['IN' => $this->_memberIds],
'return' => 'contact_id',
- ));
+ ]);
foreach ($memberships['values'] as $id => $membership) {
if (isset($rows[$membership['contact_id']])) {
$labelRows[$id] = $rows[$membership['contact_id']];
@@ -142,7 +142,7 @@ public function postProcess() {
}
//call function to create labels
CRM_Contact_Form_Task_LabelCommon::createLabel($labelRows, $labelName);
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
}
diff --git a/CRM/Member/Form/Task/PDFLetter.php b/CRM/Member/Form/Task/PDFLetter.php
index 04176fc47d37..cb917cec1c75 100644
--- a/CRM/Member/Form/Task/PDFLetter.php
+++ b/CRM/Member/Form/Task/PDFLetter.php
@@ -1,9 +1,9 @@
postProcessHook();
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
@@ -55,13 +55,13 @@ public static function postProcessMembers(&$form, $membershipIDs, $skipOnHold, $
*/
public static function generateHTML($membershipIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $html_message, $categories) {
$memberships = CRM_Utils_Token::getMembershipTokenDetails($membershipIDs);
- $html = array();
+ $html = [];
foreach ($membershipIDs as $membershipID) {
$membership = $memberships[$membershipID];
// get contact information
$contactId = $membership['contact_id'];
- $params = array('contact_id' => $contactId);
+ $params = ['contact_id' => $contactId];
//getTokenDetails is much like calling the api contact.get function - but - with some minor
// special handlings. It precedes the existence of the api
list($contacts) = CRM_Utils_Token::getTokenDetails(
diff --git a/CRM/Member/Form/Task/PickProfile.php b/CRM/Member/Form/Task/PickProfile.php
index 1f5aefb07d30..68b6ba1b53c7 100644
--- a/CRM/Member/Form/Task/PickProfile.php
+++ b/CRM/Member/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_memberIds) > $this->_maxMembers) {
- CRM_Core_Session::setStatus(ts("The maximum number of members you can select for Update multiple memberships is %1. You have selected %2. Please select fewer members from your search results and try again.", array(
+ CRM_Core_Session::setStatus(ts("The maximum number of members you can select for Update multiple memberships is %1. You have selected %2. Please select fewer members from your search results and try again.", [
1 => $this->_maxMembers,
2 => count($this->_memberIds),
- )), ts('Update multiple records error'), 'error');
+ ]), ts('Update multiple records error'), 'error');
$validate = TRUE;
}
@@ -91,18 +93,18 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $types = array('Membership');
+ $types = ['Membership'];
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
if (empty($profiles)) {
- CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple memberships. Navigate to Administer CiviCRM >> CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts('Update multiple records error'), 'error');
+ CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple memberships. Navigate to Administer CiviCRM >> CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", [1 => $types[0]]), ts('Update multiple records error'), 'error');
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -114,7 +116,7 @@ public function buildQuickForm() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Member_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Member_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Member/Form/Task/Print.php b/CRM/Member/Form/Task/Print.php
index 7c89789747eb..423a3d588bbb 100644
--- a/CRM/Member/Form/Task/Print.php
+++ b/CRM/Member/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Print Members'),
- 'js' => array('onclick' => 'window.print()'),
+ 'js' => ['onclick' => 'window.print()'],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'back',
'name' => ts('Done'),
- ),
- ));
+ ],
+ ]);
}
/**
diff --git a/CRM/Member/Form/Task/Result.php b/CRM/Member/Form/Task/Result.php
index 3f2e3dc30dcc..7f68f5c76f38 100644
--- a/CRM/Member/Form/Task/Result.php
+++ b/CRM/Member/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Task/SearchTaskHookSample.php b/CRM/Member/Form/Task/SearchTaskHookSample.php
index bccbea6f5e91..9a780079f66e 100644
--- a/CRM/Member/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Member/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_memberIds);
@@ -61,12 +61,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'start_date' => CRM_Utils_Date::customFormat($dao->start_date),
'end_date' => CRM_Utils_Date::customFormat($dao->end_date),
'source' => $dao->source,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -77,13 +77,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Import/Controller.php b/CRM/Member/Import/Controller.php
index 5148f9643c43..f0483d0284f7 100644
--- a/CRM/Member/Import/Controller.php
+++ b/CRM/Member/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Member/Import/Field.php b/CRM/Member/Import/Field.php
index 5be748109877..68720b2be78c 100644
--- a/CRM/Member/Import/Field.php
+++ b/CRM/Member/Import/Field.php
@@ -1,9 +1,9 @@
_value);
case 'trxn_id':
- static $seenTrxnIds = array();
+ static $seenTrxnIds = [];
if (in_array($this->_value, $seenTrxnIds)) {
return FALSE;
}
diff --git a/CRM/Member/Import/Form/DataSource.php b/CRM/Member/Import/Form/DataSource.php
index 11eb187608b3..46342000a65b 100644
--- a/CRM/Member/Import/Form/DataSource.php
+++ b/CRM/Member/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Insert new Membership'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -61,9 +61,9 @@ public function buildQuickForm() {
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('Import mode')
);
- $this->setDefaults(array(
+ $this->setDefaults([
'onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP,
- ));
+ ]);
$this->addContactTypeSelector();
}
@@ -74,12 +74,12 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Member_Import_Parser_Membership');
}
diff --git a/CRM/Member/Import/Form/MapField.php b/CRM/Member/Import/Form/MapField.php
index bfab1fdddeca..fa849f6449fd 100644
--- a/CRM/Member/Import/Form/MapField.php
+++ b/CRM/Member/Import/Form/MapField.php
@@ -1,9 +1,9 @@
$params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Membership',
- 'name'
- ),
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
diff --git a/CRM/Member/Import/Form/Preview.php b/CRM/Member/Import/Form/Preview.php
index a595b0a28ded..33eba538071a 100644
--- a/CRM/Member/Import/Form/Preview.php
+++ b/CRM/Member/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -98,7 +98,8 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
+ $this->setStatusUrl();
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -120,9 +121,9 @@ public function postProcess() {
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
- $mapperLocType = array();
- $mapperPhoneType = array();
+ $mapperKeys = [];
+ $mapperLocType = [];
+ $mapperPhoneType = [];
// Note: we keep the multi-dimension array (even thought it's not
// needed in the case of memberships import) so that we can merge
// the common code with contacts import later and subclass contact
@@ -150,7 +151,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -161,17 +162,18 @@ public function postProcess() {
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
- $onDuplicate
+ $onDuplicate,
+ $this->get('statusID'),
+ $this->get('totalRowCount')
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
-
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Member/Import/Form/Summary.php b/CRM/Member/Import/Form/Summary.php
index ebd8345710f7..f4940ff02c9d 100644
--- a/CRM/Member/Import/Form/Summary.php
+++ b/CRM/Member/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -105,7 +105,7 @@ public function preProcess() {
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Member/Import/Parser.php b/CRM/Member/Import/Parser.php
index fe2ae708ada4..3edd35bb5471 100644
--- a/CRM/Member/Import/Parser.php
+++ b/CRM/Member/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
+ if ($statusID) {
+ $this->progressImport($statusID);
+ $startTimestamp = $currTimestamp = $prevTimestamp = time();
+ }
while (!feof($fd)) {
$this->_lineCount++;
@@ -146,7 +153,6 @@ public function run(
}
/* trim whitespace around the values */
-
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
@@ -168,6 +174,9 @@ public function run(
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
+ if ($statusID && (($this->_lineCount % 50) == 0)) {
+ $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
+ }
}
else {
$returnCode = self::ERROR;
@@ -191,11 +200,9 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
- }
+ $recordNumber = $this->_lineCount;
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -244,27 +251,27 @@ public function run(
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('Reason'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('Reason'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('View Membership URL'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -300,7 +307,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -405,7 +412,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @return void
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Member/Import/Parser/Membership.php b/CRM/Member/Import/Parser/Membership.php
index 7d1124726566..224261207bfc 100644
--- a/CRM/Member/Import/Parser/Membership.php
+++ b/CRM/Member/Import/Parser/Membership.php
@@ -1,9 +1,9 @@
_mapperKeys = &$mapperKeys;
+ $this->_mapperKeys = $mapperKeys;
}
/**
@@ -73,30 +71,27 @@ public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneTyp
* @return void
*/
public function init() {
- $fields = CRM_Member_BAO_Membership::importableFields($this->_contactType, FALSE);
+ $this->fieldMetadata = CRM_Member_BAO_Membership::importableFields($this->_contactType, FALSE);
- foreach ($fields as $name => $field) {
+ foreach ($this->fieldMetadata as $name => $field) {
+ // @todo - we don't really need to do all this.... fieldMetadata is just fine to use as is.
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newMemberships = array();
+ $this->_newMemberships = [];
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
- $this->_contactIdIndex = -1;
$this->_membershipTypeIndex = -1;
$this->_membershipStatusIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
- case 'membership_contact_id':
- $this->_contactIdIndex = $index;
- break;
case 'membership_type_id':
$this->_membershipTypeIndex = $index;
@@ -211,7 +206,19 @@ public function summary(&$values) {
}
break;
+ case 'status_override_end_date':
+ if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
+ if (!CRM_Utils_Rule::date($params[$key])) {
+ CRM_Contact_Import_Parser_Contact::addToErrorMsg('Status Override End Date', $errorMessage);
+ }
+ }
+ else {
+ CRM_Contact_Import_Parser_Contact::addToErrorMsg('Status Override End Date', $errorMessage);
+ }
+ break;
+
case 'membership_type_id':
+ // @todo - squish into membership status - can use same lines here too.
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
if (!CRM_Utils_Array::crmInArray($val, $membershipTypes) &&
!array_key_exists($val, $membershipTypes)
@@ -221,7 +228,7 @@ public function summary(&$values) {
break;
case 'status_id':
- if (!CRM_Utils_Array::crmInArray($val, CRM_Member_PseudoConstant::membershipStatus())) {
+ if (!empty($val) && !$this->parsePseudoConstantField($val, $this->fieldMetadata[$key])) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Membership Status', $errorMessage);
}
break;
@@ -278,16 +285,17 @@ public function import($onDuplicate, &$values) {
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
- $formatted = array();
- $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
+ $formatted = [];
+ $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Membership';
+ $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
- $dateLabels = array(
+ $dateLabels = [
'join_date' => ts('Member Since'),
'membership_start_date' => ts('Start Date'),
'membership_end_date' => ts('End Date'),
- );
+ ];
foreach ($params as $key => $val) {
if ($val) {
switch ($key) {
@@ -312,13 +320,11 @@ public function import($onDuplicate, &$values) {
break;
case 'status_id':
- if (!is_numeric($val)) {
- unset($params['status_id']);
- $params['membership_status'] = $val;
- }
+ // @todo - we can do this based on the presence of 'pseudoconstant' in the metadata rather than field specific.
+ $params[$key] = $this->parsePseudoConstantField($val, $this->fieldMetadata[$key]);
break;
- case 'is_override':
+ case 'member_is_override':
$params[$key] = CRM_Utils_String::strtobool($val);
break;
}
@@ -335,13 +341,7 @@ public function import($onDuplicate, &$values) {
}
//date-Format part ends
- static $indieFields = NULL;
- if ($indieFields == NULL) {
- $tempIndieFields = CRM_Member_DAO_Membership::import();
- $indieFields = $tempIndieFields;
- }
-
- $formatValues = array();
+ $formatValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -363,7 +363,7 @@ public function import($onDuplicate, &$values) {
else {
//fix for CRM-2219 Update Membership
// onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
- if (!empty($formatted['is_override']) && empty($formatted['status_id'])) {
+ if (!empty($formatted['member_is_override']) && empty($formatted['status_id'])) {
array_unshift($values, 'Required parameter missing: Status');
return CRM_Import_Parser::ERROR;
}
@@ -371,7 +371,7 @@ public function import($onDuplicate, &$values) {
if (!empty($formatValues['membership_id'])) {
$dao = new CRM_Member_BAO_Membership();
$dao->id = $formatValues['membership_id'];
- $dates = array('join_date', 'start_date', 'end_date');
+ $dates = ['join_date', 'start_date', 'end_date'];
foreach ($dates as $v) {
if (empty($formatted[$v])) {
$formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
@@ -383,15 +383,15 @@ public function import($onDuplicate, &$values) {
'Membership'
);
if ($dao->find(TRUE)) {
- $ids = array(
- 'membership' => $formatValues['membership_id'],
- 'userId' => $session->get('userID'),
- );
-
if (empty($params['line_item']) && !empty($formatted['membership_type_id'])) {
CRM_Price_BAO_LineItem::getLineItemArray($formatted, NULL, 'membership', $formatted['membership_type_id']);
}
+ // @todo stop passing $ids array (and put details in $formatted if required)
+ $ids = [
+ 'membership' => $formatValues['membership_id'],
+ 'userId' => $session->get('userID'),
+ ];
$newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
if (civicrm_error($newMembership)) {
array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
@@ -414,13 +414,8 @@ public function import($onDuplicate, &$values) {
$endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
$joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
- if ($this->_contactIdIndex < 0) {
-
- //retrieve contact id using contact dedupe rule
- $formatValues['contact_type'] = $this->_contactType;
- $formatValues['version'] = 3;
- require_once 'CRM/Utils/DeprecatedUtils.php';
- $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
+ if (!$this->isContactIDColumnPresent()) {
+ $error = $this->checkContactDuplicate($formatValues);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
@@ -443,7 +438,7 @@ public function import($onDuplicate, &$values) {
//fix for CRM-3570, exclude the statuses those having is_admin = 1
//now user can import is_admin if is override is true.
$excludeIsAdmin = FALSE;
- if (empty($formatted['is_override'])) {
+ if (empty($formatted['member_is_override'])) {
$formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
}
$calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
@@ -458,7 +453,7 @@ public function import($onDuplicate, &$values) {
if (empty($formatted['status_id'])) {
$formatted['status_id'] = $calcStatus['id'];
}
- elseif (empty($formatted['is_override'])) {
+ elseif (empty($formatted['member_is_override'])) {
if (empty($calcStatus)) {
array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
return CRM_Import_Parser::ERROR;
@@ -478,10 +473,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = '';
@@ -533,7 +528,7 @@ public function import($onDuplicate, &$values) {
//fix for CRM-3570, exclude the statuses those having is_admin = 1
//now user can import is_admin if is override is true.
$excludeIsAdmin = FALSE;
- if (empty($formatted['is_override'])) {
+ if (empty($formatted['member_is_override'])) {
$formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
}
$calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
@@ -547,7 +542,7 @@ public function import($onDuplicate, &$values) {
if (empty($formatted['status_id'])) {
$formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
}
- elseif (empty($formatted['is_override'])) {
+ elseif (empty($formatted['member_is_override'])) {
if (empty($calcStatus)) {
array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
return CRM_Import_Parser::ERROR;
@@ -598,11 +593,11 @@ public function fini() {
*
*/
public function formattedDates($calcDates, &$formatted) {
- $dates = array(
+ $dates = [
'join_date',
'start_date',
'end_date',
- );
+ ];
foreach ($dates as $d) {
if (isset($formatted[$d]) &&
@@ -651,10 +646,10 @@ public function membership_format_params($params, &$values, $create = FALSE) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
$values[$key] = $value;
$type = $customFields[$customFieldID]['html_type'];
- if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
+ if ($type == 'CheckBox' || $type == 'Multi-Select') {
$mulValues = explode(',', $value);
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
- $values[$key] = array();
+ $values[$key] = [];
foreach ($mulValues as $v1) {
foreach ($customOption as $customValueID => $customLabel) {
$customValue = $customLabel['value'];
@@ -679,7 +674,7 @@ public function membership_format_params($params, &$values, $create = FALSE) {
throw new Exception("contact_id not valid: $value");
}
$dao = new CRM_Core_DAO();
- $qParams = array();
+ $qParams = [];
$svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
$qParams
);
@@ -714,30 +709,6 @@ public function membership_format_params($params, &$values, $create = FALSE) {
$values['membership_type_id'] = $membershipTypeId;
break;
- case 'status_id':
- if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
- throw new Exception('Invalid Membership Status Id');
- }
- $values[$key] = $value;
- break;
-
- case 'membership_status':
- $membershipStatusId = CRM_Utils_Array::key(ucfirst($value),
- CRM_Member_PseudoConstant::membershipStatus()
- );
- if ($membershipStatusId) {
- if (!empty($values['status_id']) &&
- $membershipStatusId != $values['status_id']
- ) {
- throw new Exception('Mismatched membership Status and Membership Status Id');
- }
- }
- else {
- throw new Exception('Invalid Membership Status');
- }
- $values['status_id'] = $membershipStatusId;
- break;
-
default:
break;
}
@@ -750,11 +721,11 @@ public function membership_format_params($params, &$values, $create = FALSE) {
// membership_end_date and membership_source. So, if $values contains
// membership_start_date, membership_end_date or membership_source,
// convert it to start_date, end_date or source
- $changes = array(
+ $changes = [
'membership_start_date' => 'start_date',
'membership_end_date' => 'end_date',
'membership_source' => 'source',
- );
+ ];
foreach ($changes as $orgVal => $changeVal) {
if (isset($values[$orgVal])) {
@@ -767,4 +738,13 @@ public function membership_format_params($params, &$values, $create = FALSE) {
return NULL;
}
+ /**
+ * Is the contact ID mapped.
+ *
+ * @return bool
+ */
+ protected function isContactIDColumnPresent(): bool {
+ return in_array('membership_contact_id', $this->_mapperKeys, TRUE);
+ }
+
}
diff --git a/CRM/Member/Info.php b/CRM/Member/Info.php
index 4d7e6d594fd0..059c72072607 100644
--- a/CRM/Member/Info.php
+++ b/CRM/Member/Info.php
@@ -1,9 +1,9 @@
'CiviMember',
'translatedName' => ts('CiviMember'),
'title' => ts('CiviCRM Membership Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* Provides permissions that are used by component.
@@ -82,20 +83,20 @@ public function getInfo() {
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviMember' => array(
+ $permissions = [
+ 'access CiviMember' => [
ts('access CiviMember'),
ts('View memberships'),
- ),
- 'edit memberships' => array(
+ ],
+ 'edit memberships' => [
ts('edit memberships'),
ts('Create and update memberships'),
- ),
- 'delete in CiviMember' => array(
+ ],
+ 'delete in CiviMember' => [
ts('delete in CiviMember'),
ts('Delete memberships'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -115,19 +116,20 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Memberships'),
'title' => ts('Your Membership(s)'),
// this is CiviContribute specific permission, since
// there is no permission that could be checked for
// CiviMember
- 'perm' => array('make online contributions'),
+ 'perm' => ['make online contributions'],
'weight' => 30,
- );
+ ];
}
/**
@@ -139,15 +141,24 @@ public function getUserDashboardElement() {
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Memberships'),
'url' => 'membership',
'weight' => 30,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-id-badge';
}
/**
@@ -159,14 +170,15 @@ public function registerTab() {
* collection of required pane settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Memberships'),
'weight' => 30,
- );
+ ];
}
/**
@@ -179,6 +191,7 @@ public function registerAdvancedSearchPane() {
* @return array|null
* collection of activity types
*/
+
/**
* @return array|null
*/
@@ -195,20 +208,20 @@ public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviMember') &&
CRM_Core_Permission::check('edit memberships')
) {
- $shortCut[] = array(
+ $shortCut[] = [
'path' => 'civicrm/member/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-membership',
'title' => ts('Membership'),
- );
+ ];
if ($newCredit) {
$title = ts('Membership') . '
(' . ts('credit card') . ')';
- $shortCut[0]['shortCuts'][] = array(
+ $shortCut[0]['shortCuts'][] = [
'path' => 'civicrm/member/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-membership-cc',
'title' => $title,
- );
+ ];
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
diff --git a/CRM/Member/Page/AJAX.php b/CRM/Member/Page/AJAX.php
index 5e364ded053e..b309dc37f480 100644
--- a/CRM/Member/Page/AJAX.php
+++ b/CRM/Member/Page/AJAX.php
@@ -1,9 +1,9 @@
array($memType, 'Positive')));
- $properties = array('financial_type_id', 'total_amount', 'name', 'auto_renew');
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$memType, 'Positive']]);
+ $properties = ['financial_type_id', 'total_amount', 'name', 'auto_renew'];
while ($dao->fetch()) {
foreach ($properties as $property) {
$details[$property] = $dao->$property;
diff --git a/CRM/Member/Page/DashBoard.php b/CRM/Member/Page/DashBoard.php
index ac9b8c434d43..b9bf7885fd60 100644
--- a/CRM/Member/Page/DashBoard.php
+++ b/CRM/Member/Page/DashBoard.php
@@ -1,9 +1,9 @@
$details) {
- foreach ($details as $key => $value) {
- switch ($key) {
- case 'premonth':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$preMonth&joinEnd=$preMonthEnd&start=$preMonth&end=$preMonthEnd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$prePreMonthEnd&start=$preMonth&end=$preMonthEnd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd");
- break;
-
- case 'month':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$monthStart&joinEnd=$ymd&start=$monthStart&end=$ymd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preMonthStart&start=$monthStart&end=$ymd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd");
- break;
-
- case 'year':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$yearStart&joinEnd=$ymd&start=$yearStart&end=$ymd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preYearStart&start=$yearStart&end=$ymd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd");
- break;
-
- case 'current':
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID");
- break;
-
- case 'total':
- if (!$isCurrentMonth) {
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
- "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID"
- );
- }
- else {
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
- "reset=1&force=1&status=$status"
- );
- }
- break;
-
- //LCD add owner urls
-
- case 'premonth_owner':
- $membershipSummary[$typeID][$key]['premonth_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd&owner=1");
- break;
-
- case 'month_owner':
- $membershipSummary[$typeID][$key]['month_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd&owner=1");
- break;
-
- case 'year_owner':
- $membershipSummary[$typeID][$key]['year_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd&owner=1");
- break;
-
- case 'current_owner':
- $membershipSummary[$typeID][$key]['current_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&owner=1");
- break;
-
- case 'total_owner':
- if (!$isCurrentMonth) {
- $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID&owner=1");
- }
- else {
- $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&owner=1");
- }
- break;
- //LCD end
- }
- }
- }
- @codingStandardsIgnoreEnd */
-
- // Temporary replacement for current totals column
-
foreach ($membershipSummary as $typeID => $details) {
if (!$isCurrentMonth) {
$membershipSummary[$typeID]['total']['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
@@ -306,65 +228,38 @@ public function preProcess() {
$totalCount['premonth']['new'] = array(
'count' => $newCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['premonth']['renew'] = array(
'count' => $renewCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['premonth']['total'] = array(
'count' => $totalCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['month']['new'] = array(
'count' => $newCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['month']['renew'] = array(
'count' => $renewCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['month']['total'] = array(
'count' => $totalCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['new'] = array(
'count' => $newCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['renew'] = array(
'count' => $renewCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['total'] = array(
'count' => $totalCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['current']['total'] = array(
@@ -428,9 +323,9 @@ public function preProcess() {
$this->assign('membershipSummary', $membershipSummary);
$this->assign('totalCount', $totalCount);
- $this->assign('month', date('F', $monthStartTs));
+ $this->assign('month', CRM_Utils_Date::customFormatTs($monthStartTs, '%B'));
$this->assign('year', date('Y', $monthStartTs));
- $this->assign('premonth', date('F', strtotime($preMonth)));
+ $this->assign('premonth', CRM_Utils_Date::customFormat($preMonth, '%B'));
$this->assign('currentMonth', date('F'));
$this->assign('currentYear', date('Y'));
$this->assign('isCurrent', $isCurrentMonth);
diff --git a/CRM/Member/Page/MembershipStatus.php b/CRM/Member/Page/MembershipStatus.php
index 415aae7bcf74..c4e4b605d0c3 100644
--- a/CRM/Member/Page/MembershipStatus.php
+++ b/CRM/Member/Page/MembershipStatus.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipStatus',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Status'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Membership Status'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Membership Status'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/member/membershipStatus',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Membership Status'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
- /**
- * Run the page.
- *
- * This method is called after the page is created. It checks for the
- * type of action and executes that action.
- * Finally it calls the parent's run method.
- *
- * @return void
- */
- public function run() {
- // get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String',
- // default to 'browse'
- $this, FALSE, 'browse'
- );
-
- // assign vars to templates
- $this->assign('action', $action);
- $id = CRM_Utils_Request::retrieve('id', 'Positive',
- $this, FALSE, 0
- );
-
- // what action to take ?
- if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $this->edit($action, $id);
- }
- // finally browse the custom groups
- $this->browse();
-
- // parent run
- return parent::run();
- }
-
/**
* Browse all custom data groups.
*
@@ -134,14 +101,14 @@ public function run() {
*/
public function browse() {
// get all custom groups sorted by weight
- $membershipStatus = array();
+ $membershipStatus = [];
$dao = new CRM_Member_DAO_MembershipStatus();
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
- $membershipStatus[$dao->id] = array();
+ $membershipStatus[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membershipStatus[$dao->id]);
// form all action links
@@ -155,7 +122,7 @@ public function browse() {
$action -= CRM_Core_Action::DISABLE;
}
$membershipStatus[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'membershipStatus.manage.action',
diff --git a/CRM/Member/Page/MembershipType.php b/CRM/Member/Page/MembershipType.php
index 7c83f7e6356e..e7807d67dad4 100644
--- a/CRM/Member/Page/MembershipType.php
+++ b/CRM/Member/Page/MembershipType.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipType/add',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Membership Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Membership Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/member/membershipType/add',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Membership Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -107,7 +107,7 @@ public function run() {
*/
public function browse() {
// get all membership types sorted by weight
- $membershipType = array();
+ $membershipType = [];
$dao = new CRM_Member_DAO_MembershipType();
$dao->orderBy('weight');
@@ -120,7 +120,7 @@ public function browse() {
continue;
}
$links = self::links();
- $membershipType[$dao->id] = array();
+ $membershipType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membershipType[$dao->id]);
$membershipType[$dao->id]['period_type'] = CRM_Utils_Array::value($dao->period_type, CRM_Core_SelectValues::periodType(), '');
@@ -162,7 +162,7 @@ public function browse() {
}
$membershipType[$dao->id]['order'] = $membershipType[$dao->id]['weight'];
$membershipType[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'membershipType.manage.action',
diff --git a/CRM/Member/Page/RecurringContributions.php b/CRM/Member/Page/RecurringContributions.php
new file mode 100644
index 000000000000..546350457f15
--- /dev/null
+++ b/CRM/Member/Page/RecurringContributions.php
@@ -0,0 +1,144 @@
+membershipID = CRM_Utils_Request::retrieve('membershipID', 'Positive', $this);
+ $this->contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
+
+ $this->loadRecurringContributions();
+
+ return parent::run();
+ }
+
+ /**
+ * Loads recurring contributions and assigns them to the form, to be used on
+ * the template.
+ */
+ private function loadRecurringContributions() {
+ $recurringContributions = $this->getRecurContributions($this->membershipID);
+
+ if (!empty($recurringContributions)) {
+ $this->assign('recurRows', $recurringContributions);
+ $this->assign('recur', TRUE);
+ }
+ }
+
+ /**
+ * Obtains list of recurring contributions associated to a membership.
+ *
+ * @param int $membershipID
+ *
+ * @return array
+ */
+ private function getRecurContributions($membershipID) {
+ $result = civicrm_api3('MembershipPayment', 'get', [
+ 'sequential' => 1,
+ 'contribution_id.contribution_recur_id.id' => ['IS NOT NULL' => TRUE],
+ 'options' => ['limit' => 0],
+ 'return' => [
+ 'contribution_id.contribution_recur_id.id',
+ 'contribution_id.contribution_recur_id.contact_id',
+ 'contribution_id.contribution_recur_id.start_date',
+ 'contribution_id.contribution_recur_id.end_date',
+ 'contribution_id.contribution_recur_id.next_sched_contribution_date',
+ 'contribution_id.contribution_recur_id.amount',
+ 'contribution_id.contribution_recur_id.currency',
+ 'contribution_id.contribution_recur_id.frequency_unit',
+ 'contribution_id.contribution_recur_id.frequency_interval',
+ 'contribution_id.contribution_recur_id.installments',
+ 'contribution_id.contribution_recur_id.contribution_status_id',
+ 'contribution_id.contribution_recur_id.is_test',
+ 'contribution_id.contribution_recur_id.payment_processor_id',
+ ],
+ 'membership_id' => $membershipID,
+ ]);
+ $recurringContributions = [];
+ $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label');
+
+ foreach ($result['values'] as $payment) {
+ $recurringContributionID = $payment['contribution_id.contribution_recur_id.id'];
+ $alreadyProcessed = isset($recurringContributions[$recurringContributionID]);
+
+ if ($alreadyProcessed) {
+ continue;
+ }
+
+ foreach ($payment as $field => $value) {
+ $key = strtr($field, ['contribution_id.contribution_recur_id.' => '']);
+ $recurringContributions[$recurringContributionID][$key] = $value;
+ }
+
+ $contactID = $recurringContributions[$recurringContributionID]['contact_id'];
+ $contributionStatusID = $recurringContributions[$recurringContributionID]['contribution_status_id'];
+
+ $recurringContributions[$recurringContributionID]['id'] = $recurringContributionID;
+ $recurringContributions[$recurringContributionID]['contactId'] = $contactID;
+ $recurringContributions[$recurringContributionID]['contribution_status'] = CRM_Utils_Array::value($contributionStatusID, $contributionStatuses);
+
+ $this->setActionsForRecurringContribution($recurringContributionID, $recurringContributions[$recurringContributionID]);
+ }
+ return $recurringContributions;
+ }
+
+ /**
+ * Calculates and assigns the actions available for given recurring
+ * contribution.
+ *
+ * @param int $recurID
+ * @param array $recurringContribution
+ */
+ private function setActionsForRecurringContribution($recurID, &$recurringContribution) {
+ $action = array_sum(array_keys(CRM_Contribute_Page_Tab::recurLinks($recurID, 'contribution')));
+
+ // no action allowed if it's not active
+ $recurringContribution['is_active'] = ($recurringContribution['contribution_status_id'] != 3);
+
+ if ($recurringContribution['is_active']) {
+ $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurringContribution['id'], 'recur');
+ $hideUpdate = $details->membership_id & $details->auto_renew;
+
+ if ($hideUpdate) {
+ $action -= CRM_Core_Action::UPDATE;
+ }
+
+ $recurringContribution['action'] = CRM_Core_Action::formLink(
+ CRM_Contribute_Page_Tab::recurLinks($recurID, 'contribution'),
+ $action,
+ [
+ 'cid' => $this->contactID,
+ 'crid' => $recurID,
+ 'cxt' => 'contribution',
+ ],
+ ts('more'),
+ FALSE,
+ 'contribution.selector.recurring',
+ 'Contribution',
+ $recurID
+ );
+ }
+ }
+
+}
diff --git a/CRM/Member/Page/Tab.php b/CRM/Member/Page/Tab.php
index 1599af196745..9d6f944e1158 100644
--- a/CRM/Member/Page/Tab.php
+++ b/CRM/Member/Page/Tab.php
@@ -1,9 +1,9 @@
contact_id = $this->_contactId;
- $dao->is_test = 0;
$dao->whereAdd($addWhere);
- //$dao->orderBy('name');
$dao->find();
//CRM--4418, check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit memberships')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -83,7 +81,7 @@ public function browse() {
//checks membership of contact itself
while ($dao->fetch()) {
- $membership[$dao->id] = array();
+ $membership[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
//carry campaign.
@@ -91,7 +89,7 @@ public function browse() {
//get the membership status and type values.
$statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
- foreach (array('status', 'membership_type') as $fld) {
+ foreach (['status', 'membership_type'] as $fld) {
$membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
}
if (!empty($statusANDType[$dao->id]['is_current_member'])) {
@@ -110,9 +108,7 @@ public function browse() {
$paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity(
$membership[$dao->id]['membership_id'], 'membership', 'obj');
if (!empty($paymentObject)) {
- // @todo - get this working with syntax style $paymentObject->supports(array
- //('updateSubscriptionBillingInfo'));
- $isUpdateBilling = $paymentObject->isSupported('updateSubscriptionBillingInfo');
+ $isUpdateBilling = $paymentObject->supports('updateSubscriptionBillingInfo');
}
// @todo - get this working with syntax style $paymentObject->supports(array
@@ -128,10 +124,10 @@ public function browse() {
self::getPermissionedLinks($dao->membership_type_id, $links);
$membership[$dao->id]['action'] = CRM_Core_Action::formLink($links,
$currentMask,
- array(
+ [
'id' => $dao->id,
'cid' => $this->_contactId,
- ),
+ ],
ts('Renew') . '...',
FALSE,
'membership.tab.row',
@@ -144,10 +140,10 @@ public function browse() {
self::getPermissionedLinks($dao->membership_type_id, $links);
$membership[$dao->id]['action'] = CRM_Core_Action::formLink($links,
$mask,
- array(
+ [
'id' => $dao->id,
'cid' => $this->_contactId,
- ),
+ ],
ts('more'),
FALSE,
'membership.tab.row',
@@ -156,11 +152,14 @@ public function browse() {
);
}
- //does membership have auto renew CRM-7137.
- if (!empty($membership[$dao->id]['contribution_recur_id']) &&
- !CRM_Member_BAO_Membership::isSubscriptionCancelled($membership[$dao->id]['membership_id'])
- ) {
- $membership[$dao->id]['auto_renew'] = 1;
+ // Display Auto-renew status on page (0=disabled, 1=enabled, 2=enabled, but error
+ if (!empty($membership[$dao->id]['contribution_recur_id'])) {
+ if (CRM_Member_BAO_Membership::isSubscriptionCancelled($membership[$dao->id]['membership_id'])) {
+ $membership[$dao->id]['auto_renew'] = 2;
+ }
+ else {
+ $membership[$dao->id]['auto_renew'] = 1;
+ }
}
else {
$membership[$dao->id]['auto_renew'] = 0;
@@ -180,10 +179,10 @@ public function browse() {
WHERE m.owner_membership_id = {$dao->id} AND m.is_test = 0 AND ms.is_current_member = 1 AND ct.is_deleted = 0";
$num_related = CRM_Core_DAO::singleValueQuery($query);
$max_related = CRM_Utils_Array::value('max_related', $membership[$dao->id]);
- $membership[$dao->id]['related_count'] = ($max_related == '' ? ts('%1 created', array(1 => $num_related)) : ts('%1 out of %2', array(
+ $membership[$dao->id]['related_count'] = ($max_related == '' ? ts('%1 created', [1 => $num_related]) : ts('%1 out of %2', [
1 => $num_related,
2 => $max_related,
- )));
+ ]));
}
else {
$membership[$dao->id]['related_count'] = ts('N/A');
@@ -192,14 +191,21 @@ public function browse() {
//Below code gives list of all Membership Types associated
//with an Organization(CRM-2016)
- $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypesByOrg($this->_contactId);
+ $membershipTypesResult = civicrm_api3('MembershipType', 'get', [
+ 'member_of_contact_id' => $this->_contactId,
+ 'options' => [
+ 'limit' => 0,
+ ],
+ ]);
+ $membershipTypes = CRM_Utils_Array::value('values', $membershipTypesResult, NULL);
+
foreach ($membershipTypes as $key => $value) {
$membershipTypes[$key]['action'] = CRM_Core_Action::formLink(self::membershipTypeslinks(),
$mask,
- array(
+ [
'id' => $value['id'],
'cid' => $this->_contactId,
- ),
+ ],
ts('more'),
FALSE,
'membershipType.organization.action',
@@ -219,10 +225,10 @@ public function browse() {
$this->assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
'#tab_rel' => CRM_Contact_BAO_Contact::getCountComponent('rel', $this->_contactId),
- );
+ ];
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
@@ -254,7 +260,7 @@ public function view() {
*/
public function edit() {
// set https for offline cc transaction
- $mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
@@ -296,7 +302,7 @@ public function edit() {
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -380,7 +386,7 @@ public function run() {
* @param int $contactId
*/
public static function setContext(&$form, $contactId = NULL) {
- $context = CRM_Utils_Request::retrieve('context', 'String', $form, FALSE, 'search');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'search');
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $form);
@@ -486,43 +492,43 @@ public static function &links(
$isUpdateBilling = FALSE
) {
if (!CRM_Utils_Array::value('view', self::$_links)) {
- self::$_links['view'] = array(
- CRM_Core_Action::VIEW => array(
+ self::$_links['view'] = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('View Membership'),
- ),
- );
+ ],
+ ];
}
if (!CRM_Utils_Array::value('all', self::$_links)) {
- $extraLinks = array(
- CRM_Core_Action::UPDATE => array(
+ $extraLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=update&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Edit Membership'),
- ),
- CRM_Core_Action::RENEW => array(
+ ],
+ CRM_Core_Action::RENEW => [
'name' => ts('Renew'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Renew Membership'),
- ),
- CRM_Core_Action::FOLLOWUP => array(
+ ],
+ CRM_Core_Action::FOLLOWUP => [
'name' => ts('Renew-Credit Card'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member&mode=live',
'title' => ts('Renew Membership Using Credit Card'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Delete Membership'),
- ),
- );
+ ],
+ ];
if (!$isPaymentProcessor || !$accessContribution) {
//unset the renew with credit card when payment
//processor is not available or user is not permitted to create contributions
@@ -533,25 +539,25 @@ public static function &links(
if ($isCancelSupported) {
$cancelMessage = ts('WARNING: If you cancel the recurring contribution associated with this membership, the membership will no longer be renewed automatically. However, the current membership status will not be affected.');
- self::$_links['all'][CRM_Core_Action::DISABLE] = array(
+ self::$_links['all'][CRM_Core_Action::DISABLE] = [
'name' => ts('Cancel Auto-renewal'),
'url' => 'civicrm/contribute/unsubscribe',
'qs' => 'reset=1&cid=%%cid%%&mid=%%id%%&context=membership&selectedChild=member',
'title' => ts('Cancel Auto Renew Subscription'),
'extra' => 'onclick = "if (confirm(\'' . $cancelMessage . '\') ) { return true; else return false;}"',
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::DISABLE])) {
unset(self::$_links['all'][CRM_Core_Action::DISABLE]);
}
if ($isUpdateBilling) {
- self::$_links['all'][CRM_Core_Action::MAP] = array(
+ self::$_links['all'][CRM_Core_Action::MAP] = [
'name' => ts('Change Billing Details'),
'url' => 'civicrm/contribute/updatebilling',
'qs' => 'reset=1&cid=%%cid%%&mid=%%id%%&context=membership&selectedChild=member',
'title' => ts('Change Billing Details'),
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::MAP])) {
unset(self::$_links['all'][CRM_Core_Action::MAP]);
@@ -567,20 +573,20 @@ public static function &links(
*/
public static function &membershipTypesLinks() {
if (!self::$_membershipTypesLinks) {
- self::$_membershipTypesLinks = array(
- CRM_Core_Action::VIEW => array(
+ self::$_membershipTypesLinks = [
+ CRM_Core_Action::VIEW => [
'name' => ts('Members'),
'url' => 'civicrm/member/search/',
'qs' => 'reset=1&force=1&type=%%id%%',
'title' => ts('Search'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipType',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Type'),
- ),
- );
+ ],
+ ];
}
return self::$_membershipTypesLinks;
}
diff --git a/CRM/Member/Page/UserDashboard.php b/CRM/Member/Page/UserDashboard.php
index c83c4ce73e0f..5240ee9d818a 100644
--- a/CRM/Member/Page/UserDashboard.php
+++ b/CRM/Member/Page/UserDashboard.php
@@ -1,9 +1,9 @@
contact_id = $this->_contactId;
$dao->is_test = 0;
$dao->find();
while ($dao->fetch()) {
- $membership[$dao->id] = array();
+ $membership[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
//get the membership status and type values.
$statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
- foreach (array(
+ foreach ([
'status',
'membership_type',
- ) as $fld) {
+ ] as $fld) {
$membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
}
if (!empty($statusANDType[$dao->id]['is_current_member'])) {
diff --git a/CRM/Member/PseudoConstant.php b/CRM/Member/PseudoConstant.php
index e51bf25bfac6..dedf38aaaf0d 100644
--- a/CRM/Member/PseudoConstant.php
+++ b/CRM/Member/PseudoConstant.php
@@ -1,9 +1,9 @@
array(
+ self::$_links['view'] = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=member' . $extraParams,
'title' => ts('View Membership'),
- ),
- );
+ ],
+ ];
}
if (!isset(self::$_links['all']) || !self::$_links['all']) {
- $extraLinks = array(
- CRM_Core_Action::UPDATE => array(
+ $extraLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Membership'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Membership'),
- ),
- CRM_Core_Action::RENEW => array(
+ ],
+ CRM_Core_Action::RENEW => [
'name' => ts('Renew'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=renew&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Renew Membership'),
- ),
- CRM_Core_Action::FOLLOWUP => array(
+ ],
+ CRM_Core_Action::FOLLOWUP => [
'name' => ts('Renew-Credit Card'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=%%cxt%%&mode=live' . $extraParams,
'title' => ts('Renew Membership Using Credit Card'),
- ),
- );
+ ],
+ ];
if (!$isPaymentProcessor || !$accessContribution) {
//unset the renew with credit card when payment
//processor is not available or user not permitted to make contributions
@@ -251,12 +251,12 @@ public static function &links(
}
if ($isCancelSupported) {
- self::$_links['all'][CRM_Core_Action::DISABLE] = array(
+ self::$_links['all'][CRM_Core_Action::DISABLE] = [
'name' => ts('Cancel Auto-renewal'),
'url' => 'civicrm/contribute/unsubscribe',
'qs' => 'reset=1&mid=%%id%%&context=%%cxt%%' . $extraParams,
'title' => ts('Cancel Auto Renew Subscription'),
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::DISABLE])) {
unset(self::$_links['all'][CRM_Core_Action::DISABLE]);
@@ -316,7 +316,7 @@ public function getTotalCount($action) {
* @param string $output
* What should the result set include (web/email/csv).
*
- * @return int
+ * @return array
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
@@ -350,10 +350,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
//CRM-4418 check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit memberships')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -363,7 +363,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
@@ -377,7 +377,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['campaign_id'] = $result->member_campaign_id;
if (!empty($row['member_is_test'])) {
- $row['membership_type'] = $row['membership_type'] . " (test)";
+ $row['membership_type'] = CRM_Core_TestEntity::appendTestText($row['membership_type']);
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->membership_id;
@@ -413,11 +413,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
$row['action'] = CRM_Core_Action::formLink($links,
$currentMask,
- array(
+ [
'id' => $result->membership_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('Renew') . '...',
FALSE,
'membership.selector.row',
@@ -428,11 +428,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
else {
$links = self::links('view');
$row['action'] = CRM_Core_Action::formLink($links, $mask,
- array(
+ [
'id' => $result->membership_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'membership.selector.row',
@@ -441,14 +441,18 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
}
- //does membership have auto renew CRM-7137.
- $autoRenew = FALSE;
- if (isset($result->membership_recur_id) && $result->membership_recur_id &&
- !CRM_Member_BAO_Membership::isSubscriptionCancelled($row['membership_id'])
- ) {
- $autoRenew = TRUE;
+ // Display Auto-renew status on page (0=disabled, 1=enabled, 2=enabled, but error
+ if (!empty($result->membership_recur_id)) {
+ if (CRM_Member_BAO_Membership::isSubscriptionCancelled($row['membership_id'])) {
+ $row['auto_renew'] = 2;
+ }
+ else {
+ $row['auto_renew'] = 1;
+ }
+ }
+ else {
+ $row['auto_renew'] = 0;
}
- $row['auto_renew'] = $autoRenew;
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
@@ -481,52 +485,52 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Type'),
'sort' => 'membership_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Member Since'),
- 'sort' => 'join_date',
+ 'sort' => 'membership_join_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Start Date'),
'sort' => 'membership_start_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('End Date'),
'sort' => 'membership_end_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Source'),
'sort' => 'membership_source',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'membership_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Auto-renew?'),
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
@@ -539,7 +543,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Member/StateMachine/Search.php b/CRM/Member/StateMachine/Search.php
index 49453bc2753c..fe95f9dcab7b 100644
--- a/CRM/Member/StateMachine/Search.php
+++ b/CRM/Member/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Member_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -80,7 +80,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Member/StatusOverrideTypes.php b/CRM/Member/StatusOverrideTypes.php
new file mode 100644
index 000000000000..05770d4da2d4
--- /dev/null
+++ b/CRM/Member/StatusOverrideTypes.php
@@ -0,0 +1,116 @@
+ 'Type 1 Label'] format
+ */
+ public static function getSelectOptions() {
+ return [
+ self::NO => ts('No'),
+ self::PERMANENT => ts('Override Permanently'),
+ self::UNTIL_DATE => ts('Override Until Selected Date'),
+ ];
+ }
+
+ /**
+ * Determines if the override type means
+ * that the membership is overridden or not.
+ * For now, only "NO" type means that the membership
+ * status is not overridden.
+ *
+ * @param $overrideType
+ *
+ * @return bool
+ */
+ public static function isOverridden($overrideType) {
+ if ($overrideType == self::NO) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isNo($overrideType) {
+ if ($overrideType != self::NO) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isPermanent($overrideType) {
+ if ($overrideType != self::PERMANENT) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isUntilDate($overrideType) {
+ if ($overrideType != self::UNTIL_DATE) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+}
diff --git a/CRM/Member/Task.php b/CRM/Member/Task.php
index 7f2da7b08e72..3d17b53fdf82 100644
--- a/CRM/Member/Task.php
+++ b/CRM/Member/Task.php
@@ -1,9 +1,9 @@
array(
+ public static function tasks() {
+ if (!self::$_tasks) {
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete memberships'),
'class' => 'CRM_Member_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Member_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export members'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
- 'title' => ts('Email - send now'),
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
'class' => 'CRM_Member_Form_Task_Email',
'result' => TRUE,
- ),
- 5 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple memberships'),
- 'class' => array(
+ 'class' => [
'CRM_Member_Form_Task_PickProfile',
'CRM_Member_Form_Task_Batch',
- ),
+ ],
'result' => TRUE,
- ),
- 6 => array(
+ ],
+ self::LABEL_MEMBERS => [
'title' => ts('Mailing labels - print'),
- 'class' => array(
+ 'class' => [
'CRM_Member_Form_Task_Label',
- ),
+ ],
'result' => TRUE,
- ),
- 7 => array(
+ ],
+ self::PDF_LETTER => [
'title' => ts('Print/merge document for memberships'),
'class' => 'CRM_Member_Form_Task_PDFLetter',
'result' => FALSE,
- ),
- );
+ ],
+ self::SAVE_SEARCH => [
+ 'title' => ts('Group - create smart group'),
+ 'class' => 'CRM_Contact_Form_Task_SaveSearch',
+ 'result' => TRUE,
+ ],
+ self::SAVE_SEARCH_UPDATE => [
+ 'title' => ts('Group - update smart group'),
+ 'class' => 'CRM_Contact_Form_Task_SaveSearch_Update',
+ 'result' => TRUE,
+ ],
+ ];
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviMember')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit memberships')) {
- unset(self::$_tasks[5]);
+ unset(self::$_tasks[self::BATCH_UPDATE]);
}
- CRM_Utils_Hook::searchTasks('membership', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
@@ -134,13 +140,8 @@ public static function &tasks() {
* @return array
* the set of task titles
*/
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
+ public static function taskTitles() {
+ return parent::taskTitles();
}
/**
@@ -148,27 +149,29 @@ public static function &taskTitles() {
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit memberships')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- 4 => self::$_tasks[4]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ self::TASK_EMAIL => self::$_tasks[self::TASK_EMAIL]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviMember')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -184,13 +187,10 @@ public static function &permissionedTaskTitles($permission) {
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+ // Make the print task the default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Member/Tokens.php b/CRM/Member/Tokens.php
index 7fe6496a292d..455ba74ffa72 100644
--- a/CRM/Member/Tokens.php
+++ b/CRM/Member/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -45,7 +45,7 @@ class CRM_Member_Tokens extends \Civi\Token\AbstractTokenSubscriber {
*/
public function __construct() {
parent::__construct('membership', array_merge(
- array(
+ [
'fee' => ts('Membership Fee'),
'id' => ts('Membership ID'),
'join_date' => ts('Membership Join Date'),
@@ -53,8 +53,8 @@ public function __construct() {
'end_date' => ts('Membership End Date'),
'status' => ts('Membership Status'),
'type' => ts('Membership Type'),
- ),
- $this->getCustomTokens('Membership')
+ ],
+ CRM_Utils_Token::getCustomFieldTokens('Membership')
));
}
@@ -63,8 +63,7 @@ public function __construct() {
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_membership';
}
@@ -92,9 +91,12 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$actionSearchResult = $row->context['actionSearchResult'];
- if (in_array($field, array('start_date', 'end_date', 'join_date'))) {
+ if (in_array($field, ['start_date', 'end_date', 'join_date'])) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
+ elseif ($field == 'fee') {
+ $row->tokens($entity, $field, \CRM_Utils_Money::format($actionSearchResult->$field, NULL, NULL, TRUE));
+ }
elseif (isset($actionSearchResult->$field)) {
$row->tokens($entity, $field, $actionSearchResult->$field);
}
diff --git a/CRM/Note/Form/Note.php b/CRM/Note/Form/Note.php
index be20ded1b99e..9e1cfeebde32 100644
--- a/CRM/Note/Form/Note.php
+++ b/CRM/Note/Form/Note.php
@@ -1,9 +1,9 @@
_action & CRM_Core_Action::UPDATE) {
if (isset($this->_id)) {
@@ -112,6 +112,20 @@ public function setDefaultValues() {
return $defaults;
}
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'Note';
+ }
+
+ /**
+ * Explicitly declare the form context.
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Build the form object.
*
@@ -119,41 +133,39 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
return;
}
- $this->add('text', 'subject', ts('Subject:'), array('size' => 20));
- $this->add('textarea', 'note', ts('Note:'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note', 'note'), TRUE);
- $this->add('select', 'privacy', ts('Privacy:'), CRM_Core_OptionGroup::values('note_privacy'));
-
+ $this->addField('subject');
+ $this->addField('note', [], TRUE);
+ $this->addField('privacy');
$this->add('hidden', 'parent_id');
// add attachments part
CRM_Core_BAO_File::buildAttachment($this, 'civicrm_note', $this->_id, NULL, TRUE);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
}
@@ -190,7 +202,7 @@ public function postProcess() {
// add attachments as needed
CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_note', $params['id']);
- $ids = array();
+ $ids = [];
$note = CRM_Core_BAO_Note::add($params, $ids);
CRM_Core_Session::setStatus(ts('Your Note has been saved.'), ts('Saved'), 'success');
diff --git a/CRM/PCP/BAO/PCP.php b/CRM/PCP/BAO/PCP.php
index 16f38739c335..c747805cbc59 100644
--- a/CRM/PCP/BAO/PCP.php
+++ b/CRM/PCP/BAO/PCP.php
@@ -1,9 +1,9 @@
array($contactId, 'Integer'));
+ $params = [1 => [$contactId, 'Integer']];
$pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params);
- $pcpInfo = array();
+ $pcpInfo = [];
$hide = $mask = array_sum(array_keys($links['all']));
- $contactPCPPages = array();
+ $contactPCPPages = [];
$event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$contribute = CRM_Contribute_PseudoConstant::contributionPage();
@@ -128,11 +128,11 @@ public static function getPcpDashboardInfo($contactId) {
while ($pcpInfoDao->fetch()) {
$mask = $hide;
if ($links) {
- $replace = array(
+ $replace = [
'pcpId' => $pcpInfoDao->id,
'pcpBlock' => $pcpInfoDao->pcp_block_id,
'pageComponent' => $pcpInfoDao->page_type,
- );
+ ];
}
$pcpLink = $links['all'];
@@ -156,14 +156,14 @@ public static function getPcpDashboardInfo($contactId) {
$component = $pcpInfoDao->page_type;
$pageTitle = CRM_Utils_Array::value($pcpInfoDao->page_id, $$component);
- $pcpInfo[] = array(
+ $pcpInfo[] = [
'pageTitle' => $pageTitle,
'pcpId' => $pcpInfoDao->id,
'pcpTitle' => $pcpInfoDao->title,
'pcpStatus' => $pcpStatus[$pcpInfoDao->status_id],
'action' => $action,
'class' => $class,
- );
+ ];
$contactPCPPages[$pcpInfoDao->page_type][] = $pcpInfoDao->page_id;
}
@@ -188,30 +188,30 @@ public static function getPcpDashboardInfo($contactId) {
ORDER BY target_entity_type, target_entity_id
";
$pcpBlockDao = CRM_Core_DAO::executeQuery($query);
- $pcpBlock = array();
+ $pcpBlock = [];
$mask = 0;
while ($pcpBlockDao->fetch()) {
if ($links) {
- $replace = array(
+ $replace = [
'pageId' => $pcpBlockDao->target_entity_id,
'pageComponent' => $pcpBlockDao->target_entity_type,
- );
+ ];
}
$pcpLink = $links['add'];
$action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'),
FALSE, 'pcp.dashboard.other', "{$pcpBlockDao->target_entity_type}_PCP", $pcpBlockDao->target_entity_id);
$component = $pcpBlockDao->target_entity_type;
if ($pageTitle = CRM_Utils_Array::value($pcpBlockDao->target_entity_id, $$component)) {
- $pcpBlock[] = array(
+ $pcpBlock[] = [
'pageId' => $pcpBlockDao->target_entity_id,
'pageTitle' => $pageTitle,
'action' => $action,
- );
+ ];
}
}
- return array($pcpBlock, $pcpInfo);
+ return [$pcpBlock, $pcpInfo];
}
/**
@@ -224,14 +224,22 @@ public static function getPcpDashboardInfo($contactId) {
* Total amount
*/
public static function thermoMeter($pcpId) {
+ $completedStatusId = CRM_Core_PseudoConstant::getKey(
+ 'CRM_Contribute_BAO_Contribution',
+ 'contribution_status_id',
+ 'Completed'
+ );
$query = "
SELECT SUM(cc.total_amount) as total
FROM civicrm_pcp pcp
LEFT JOIN civicrm_contribution_soft cs ON ( pcp.id = cs.pcp_id )
LEFT JOIN civicrm_contribution cc ON ( cs.contribution_id = cc.id)
-WHERE pcp.id = %1 AND cc.contribution_status_id =1 AND cc.is_test = 0";
+WHERE pcp.id = %1 AND cc.contribution_status_id = %2 AND cc.is_test = 0";
- $params = array(1 => array($pcpId, 'Integer'));
+ $params = [
+ 1 => [$pcpId, 'Integer'],
+ 2 => [$completedStatusId, 'Integer'],
+ ];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -244,17 +252,26 @@ public static function thermoMeter($pcpId) {
* @return array
*/
public static function honorRoll($pcpId) {
+ $completedStatusId = CRM_Core_PseudoConstant::getKey(
+ 'CRM_Contribute_BAO_Contribution',
+ 'contribution_status_id',
+ 'Completed'
+ );
$query = "
SELECT cc.id, cs.pcp_roll_nickname, cs.pcp_personal_note,
cc.total_amount, cc.currency
FROM civicrm_contribution cc
LEFT JOIN civicrm_contribution_soft cs ON cc.id = cs.contribution_id
- WHERE cs.pcp_id = {$pcpId}
+ WHERE cs.pcp_id = %1
AND cs.pcp_display_in_roll = 1
- AND contribution_status_id = 1
+ AND contribution_status_id = %2
AND is_test = 0";
- $dao = CRM_Core_DAO::executeQuery($query);
- $honor = array();
+ $params = [
+ 1 => [$pcpId, 'Integer'],
+ 2 => [$completedStatusId, 'Integer'],
+ ];
+ $dao = CRM_Core_DAO::executeQuery($query, $params);
+ $honor = [];
while ($dao->fetch()) {
$honor[$dao->id]['nickname'] = ucwords($dao->pcp_roll_nickname);
$honor[$dao->id]['total_amount'] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
@@ -273,61 +290,61 @@ public static function &pcpLinks() {
if (!(self::$_pcpLinks)) {
$deleteExtra = ts('Are you sure you want to delete this Personal Campaign Page?') . '\n' . ts('This action cannot be undone.');
- self::$_pcpLinks['add'] = array(
- CRM_Core_Action::ADD => array(
+ self::$_pcpLinks['add'] = [
+ CRM_Core_Action::ADD => [
'name' => ts('Create a Personal Campaign Page'),
'class' => 'no-popup',
'url' => 'civicrm/contribute/campaign',
'qs' => 'action=add&reset=1&pageId=%%pageId%%&component=%%pageComponent%%',
'title' => ts('Configure'),
- ),
- );
+ ],
+ ];
- self::$_pcpLinks['all'] = array(
- CRM_Core_Action::UPDATE => array(
+ self::$_pcpLinks['all'] = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Your Page'),
'url' => 'civicrm/pcp/info',
'qs' => 'action=update&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Configure'),
- ),
- CRM_Core_Action::DETACH => array(
+ ],
+ CRM_Core_Action::DETACH => [
'name' => ts('Tell Friends'),
'url' => 'civicrm/friend',
'qs' => 'eid=%%pcpId%%&blockId=%%pcpBlock%%&reset=1&pcomponent=pcp&component=%%pageComponent%%',
'title' => ts('Tell Friends'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('URL for this Page'),
'url' => 'civicrm/pcp/info',
'qs' => 'reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('URL for this Page'),
- ),
- CRM_Core_Action::BROWSE => array(
+ ],
+ CRM_Core_Action::BROWSE => [
'name' => ts('Update Contact Information'),
'url' => 'civicrm/pcp/info',
'qs' => 'action=browse&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Update Contact Information'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'url' => 'civicrm/pcp',
'qs' => 'action=enable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Enable'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'url' => 'civicrm/pcp',
'qs' => 'action=disable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Disable'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/pcp',
'qs' => 'action=delete&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
'title' => ts('Delete'),
- ),
- );
+ ],
+ ];
}
return self::$_pcpLinks;
}
@@ -360,20 +377,20 @@ public static function deleteById($id) {
* Form object.
*/
public static function buildPCPForm($form) {
- $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"));
+ $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"]);
$form->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
- $profile = array();
+ $profile = [];
$isUserRequired = NULL;
$config = CRM_Core_Config::singleton();
if ($config->userFramework != 'Standalone') {
$isUserRequired = 2;
}
- CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array(
+ CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, [
'title',
'is_active',
- ));
+ ]);
if (!empty($profiles)) {
foreach ($profiles as $key => $value) {
if ($value['is_active']) {
@@ -383,15 +400,15 @@ public static function buildPCPForm($form) {
$form->assign('profile', $profile);
}
- $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), array('' => ts('- select -')) + $profile, TRUE);
+ $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), ['' => ts('- select -')] + $profile, TRUE);
//CRM-15821 - To add new option for PCP "Owner" notification
$ownerNotifications = CRM_Core_OptionGroup::values('pcp_owner_notify');
$form->addRadio('owner_notify_id', ts('Owner Email Notification'), $ownerNotifications, NULL, '
', TRUE);
- $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, array('onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"));
+ $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, ['onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"]);
- $form->add('text',
+ $form->add('number',
'tellfriend_limit',
ts("'Tell a friend' maximum recipients limit"),
CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'tellfriend_limit')
@@ -407,28 +424,27 @@ public static function buildPCPForm($form) {
$form->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'notify_email'));
}
-
/**
* Add PCP form elements to a form.
*
* @param int $pcpId
- * @param CRM_Core_Page $page
+ * @param CRM_Core_Form $page
* @param null $elements
*/
public static function buildPcp($pcpId, &$page, &$elements = NULL) {
- $prms = array('id' => $pcpId);
+ $prms = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($pcpId)) {
if ($pcpInfo['page_type'] == 'event') {
- $pcp_supporter_text = ts('This event registration is being made thanks to the efforts of %1, who supports our campaign. ', array(1 => $pcpSupporter));
+ $pcp_supporter_text = ts('This event registration is being made thanks to the efforts of %1, who supports our campaign. ', [1 => $pcpSupporter]);
$text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'event');
if (!empty($text)) {
$pcp_supporter_text .= "You can support it as well - once you complete the registration, you will be able to create your own Personal Campaign Page!";
}
}
else {
- $pcp_supporter_text = ts('This contribution is being made thanks to the efforts of %1, who supports our campaign. ', array(1 => $pcpSupporter));
+ $pcp_supporter_text = ts('This contribution is being made thanks to the efforts of %1, who supports our campaign. ', [1 => $pcpSupporter]);
$text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'contribute');
if (!empty($text)) {
$pcp_supporter_text .= "You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!";
@@ -443,17 +459,17 @@ public static function buildPcp($pcpId, &$page, &$elements = NULL) {
if ($pcpInfo['is_honor_roll']) {
$page->assign('is_honor_roll', TRUE);
$page->add('checkbox', 'pcp_display_in_roll', ts('Show my support in the public honor roll'), NULL, NULL,
- array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
+ ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
);
- $extraOption = array('onclick' => "return pcpAnonymous( );");
- $elements = array();
+ $extraOption = ['onclick' => "return pcpAnonymous( );"];
+ $elements = [];
$elements[] = &$page->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
$elements[] = &$page->createElement('radio', NULL, '', ts('List my support anonymously'), 1, $extraOption);
$page->addGroup($elements, 'pcp_is_anonymous', NULL, ' ');
$page->_defaults['pcp_is_anonymous'] = 0;
- $page->add('text', 'pcp_roll_nickname', ts('Name'), array('maxlength' => 30));
- $page->add('textarea', "pcp_personal_note", ts('Personal Note'), array('style' => 'height: 3em; width: 40em;'));
+ $page->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
+ $page->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
}
else {
$page->assign('is_honor_roll', FALSE);
@@ -477,17 +493,16 @@ public static function handlePcp($pcpId, $component, $entity) {
return FALSE;
}
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
-
- $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
+ $pcpStatus = CRM_Core_PseudoConstant::get('CRM_PCP_BAO_PCP', 'status_id');
+ $approvedId = array_search('Approved', $pcpStatus);
- $params = array('id' => $pcpId);
+ $params = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
- $params = array('id' => $pcpInfo['pcp_block_id']);
+ $params = ['id' => $pcpInfo['pcp_block_id']];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlock);
- $params = array('id' => $pcpInfo['page_id']);
+ $params = ['id' => $pcpInfo['page_id']];
$now = time();
if ($component == 'event') {
@@ -507,13 +522,14 @@ public static function handlePcp($pcpId, $component, $entity) {
// define redirect url back to contrib page or event if needed
$url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE);
+ $currentPCPStatus = CRM_Core_PseudoConstant::getName('CRM_PCP_BAO_PCP', 'status_id', $pcpInfo['status_id']);
if ($pcpBlock['target_entity_id'] != $entity['id']) {
$statusMessage = ts('This page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.');
CRM_Core_Error::statusBounce($statusMessage, $url);
}
- elseif ($pcpInfo['status_id'] != $approvedId) {
- $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', array(1 => $pcpStatus[$pcpInfo['status_id']]));
+ elseif ($currentPCPStatus !== 'Approved') {
+ $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', [1 => $pcpStatus[$pcpInfo['status_id']]]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif (empty($pcpBlock['is_active'])) {
@@ -530,12 +546,12 @@ public static function handlePcp($pcpId, $component, $entity) {
$customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $entity));
if ($startDate && $endDate) {
$statusMessage = ts('The Personal Campaign Page you have just visited is only active from %1 to %2. However you can still support the campaign here.',
- array(1 => $customStartDate, 2 => $customEndDate)
+ [1 => $customStartDate, 2 => $customEndDate]
);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif ($startDate) {
- $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', array(1 => $customStartDate));
+ $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', [1 => $customStartDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif ($endDate) {
@@ -545,21 +561,21 @@ public static function handlePcp($pcpId, $component, $entity) {
"reset=1&id={$pcpBlock['entity_id']}",
FALSE, NULL, FALSE, TRUE
);
- $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', array(1 => $customEndDate));
+ $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', [1 => $customEndDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
else {
- $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', array(1 => $customEndDate));
+ $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', [1 => $customEndDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
}
}
- return array(
+ return [
'pcpId' => $pcpId,
'pcpBlock' => $pcpBlock,
'pcpInfo' => $pcpInfo,
- );
+ ];
}
/**
@@ -589,10 +605,10 @@ public static function setIsActive($id, $is_active) {
$pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
$pcpStatus = $pcpStatus[$is_active];
- CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", array(
+ CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", [
1 => $pcpTitle,
2 => $pcpStatus,
- )), 'Status Updated', 'success');
+ ]), 'Status Updated', 'success');
// send status change mail
$result = self::sendStatusUpdate($id, $is_active, FALSE, $pcpPageType);
@@ -636,30 +652,30 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
// used in subject templates
$contribPageTitle = self::getPcpPageTitle($pcpId, $component);
- $tplParams = array(
+ $tplParams = [
'loginUrl' => $loginURL,
'contribPageTitle' => $contribPageTitle,
'pcpId' => $pcpId,
- );
+ ];
//get the default domain email address.
list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') {
$fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1');
- CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
+ CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', [1 => $fixUrl]));
}
$receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
// get recipient (supporter) name and email
- $params = array('id' => $pcpId);
+ $params = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']);
// get pcp block info
list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component);
- $params = array('id' => $blockId);
+ $params = ['id' => $blockId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo);
// assign urls required in email template
@@ -689,7 +705,7 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
$tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change';
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => $tplName,
'contactId' => $pcpInfo['contact_id'],
@@ -697,7 +713,7 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
'from' => $receiptFrom,
'toName' => $name,
'toEmail' => $address,
- )
+ ]
);
return $sent;
}
@@ -709,7 +725,9 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
* Campaign page id.
*
* @param bool $is_active
- * @return null
+ *
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setDisable($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'is_active', $is_active);
@@ -733,7 +751,7 @@ public static function getStatus($pcpId, $component) {
$entity_table = self::getPcpEntityTable($component);
- $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -755,7 +773,7 @@ public static function getPcpBlockStatus($pageId, $component) {
$entity_table = self::getPcpEntityTable($component);
- $params = array(1 => array($pageId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pageId, 'Integer'], 2 => [$entity_table, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -773,7 +791,7 @@ public static function getPcpBlockInUse($id) {
FROM civicrm_pcp pcp
WHERE pcp.pcp_block_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$result = CRM_Core_DAO::singleValueQuery($query, $params);
return $result > 0;
}
@@ -792,7 +810,7 @@ public static function checkEmailProfile($profileId) {
FROM civicrm_uf_field
WHERE field_name like 'email%' And is_active = 1 And uf_group_id = %1";
- $params = array(1 => array($profileId, 'Integer'));
+ $params = [1 => [$profileId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if (!$dao->fetch()) {
return TRUE;
@@ -824,7 +842,7 @@ public static function getPcpPageTitle($pcpId, $component) {
WHERE pcp.id = %1";
}
- $params = array(1 => array($pcpId, 'Integer'));
+ $params = [1 => [$pcpId, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -845,13 +863,13 @@ public static function getPcpBlockEntityId($pcpId, $component) {
LEFT JOIN civicrm_pcp_block pb ON ( pb.entity_id = pcp.page_id AND pb.entity_table = %2 )
WHERE pcp.id = %1";
- $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
- return array($dao->pcpBlockId, $dao->entity_id);
+ return [$dao->pcpBlockId, $dao->entity_id];
}
- return array();
+ return [];
}
/**
@@ -862,12 +880,12 @@ public static function getPcpBlockEntityId($pcpId, $component) {
* @return string
*/
public static function getPcpEntityTable($component) {
- $entity_table_map = array(
+ $entity_table_map = [
'event' => 'civicrm_event',
'civicrm_event' => 'civicrm_event',
'contribute' => 'civicrm_contribution_page',
'civicrm_contribution_page' => 'civicrm_contribution_page',
- );
+ ];
return isset($entity_table_map[$component]) ? $entity_table_map[$component] : FALSE;
}
@@ -891,7 +909,7 @@ public static function getSupporterProfileId($component_id, $component = 'contri
AND pcp.entity_table = %2
AND ufgroup.is_active = 1";
- $params = array(1 => array($component_id, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
if (!$supporterProfileId = CRM_Core_DAO::singleValueQuery($query, $params)) {
CRM_Core_Error::fatal(ts('Supporter profile is not set for this Personal Campaign Page or the profile is disabled. Please contact the site administrator if you need assistance.'));
}
@@ -914,7 +932,7 @@ public static function getOwnerNotificationId($component_id, $component = 'contr
SELECT pb.owner_notify_id
FROM civicrm_pcp_block pb
WHERE pb.entity_id = %1 AND pb.entity_table = %2";
- $params = array(1 => array($component_id, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
if (!$ownerNotificationId = CRM_Core_DAO::singleValueQuery($query, $params)) {
CRM_Core_Error::fatal(ts('Owner Notification is not set for this Personal Campaign Page. Please contact the site administrator if you need assistance.'));
}
diff --git a/CRM/PCP/BAO/PCPBlock.php b/CRM/PCP/BAO/PCPBlock.php
index c30976e8b907..653d01005b55 100644
--- a/CRM/PCP/BAO/PCPBlock.php
+++ b/CRM/PCP/BAO/PCPBlock.php
@@ -1,9 +1,9 @@
__table = 'civicrm_pcp';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pcp_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pcp_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Personal Campaign Page ID') ,
- 'description' => 'Personal Campaign Page ID',
- 'required' => true,
+ 'title' => ts('Personal Campaign Page ID'),
+ 'description' => ts('Personal Campaign Page ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'pcp_contact_id' => array(
+ ],
+ 'pcp_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.contact_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'status_id' => array(
+ ],
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Personal Campaign Page Status') ,
- 'required' => true,
+ 'title' => ts('Personal Campaign Page Status'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.status_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'pcp_status',
'optionEditPath' => 'civicrm/admin/options/pcp_status',
- )
- ) ,
- 'title' => array(
+ ],
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Personal Campaign Page Title') ,
+ 'title' => ts('Personal Campaign Page Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp.title',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'intro_text' => array(
+ ],
+ ],
+ 'intro_text' => [
'name' => 'intro_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Intro Text') ,
+ 'title' => ts('Intro Text'),
+ 'where' => 'civicrm_pcp.intro_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'page_text' => array(
+ ],
+ ],
+ 'page_text' => [
'name' => 'page_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Page Text') ,
+ 'title' => ts('Page Text'),
+ 'where' => 'civicrm_pcp.page_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'donate_link_text' => array(
+ ],
+ ],
+ 'donate_link_text' => [
'name' => 'donate_link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Donate Link Text') ,
+ 'title' => ts('Donate Link Text'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp.donate_link_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'page_id' => array(
+ ],
+ ],
+ 'page_id' => [
'name' => 'page_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution Page') ,
- 'description' => 'The Contribution or Event Page which triggered this pcp',
- 'required' => true,
+ 'title' => ts('Contribution Page'),
+ 'description' => ts('The Contribution or Event Page which triggered this pcp'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.page_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'page_type' => array(
+ ],
+ 'page_type' => [
'name' => 'page_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('PCP Page Type') ,
- 'description' => 'The type of PCP this is: contribute or event',
+ 'title' => ts('PCP Page Type'),
+ 'description' => ts('The type of PCP this is: contribute or event'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pcp.page_type',
'default' => 'contribute',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'pcp_block_id' => array(
+ ],
+ ],
+ 'pcp_block_id' => [
'name' => 'pcp_block_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('PCP Block') ,
- 'description' => 'The pcp block that this pcp page was created from',
- 'required' => true,
+ 'title' => ts('PCP Block'),
+ 'description' => ts('The pcp block that this pcp page was created from'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.pcp_block_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'is_thermometer' => array(
+ ],
+ 'is_thermometer' => [
'name' => 'is_thermometer',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Use Thermometer?') ,
+ 'title' => ts('Use Thermometer?'),
+ 'where' => 'civicrm_pcp.is_thermometer',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_honor_roll' => array(
+ ],
+ ],
+ 'is_honor_roll' => [
'name' => 'is_honor_roll',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Show Honor Roll?') ,
+ 'title' => ts('Show Honor Roll?'),
+ 'where' => 'civicrm_pcp.is_honor_roll',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'goal_amount' => array(
+ ],
+ ],
+ 'goal_amount' => [
'name' => 'goal_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Goal Amount') ,
- 'description' => 'Goal amount of this Personal Campaign Page.',
- 'precision' => array(
+ 'title' => ts('Goal Amount'),
+ 'description' => ts('Goal amount of this Personal Campaign Page.'),
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_pcp.goal_amount',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pcp.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_active' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'description' => 'Is Personal Campaign Page enabled/active?',
+ 'title' => ts('Enabled?'),
+ 'description' => ts('Is Personal Campaign Page enabled/active?'),
+ 'where' => 'civicrm_pcp.is_active',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_notify' => array(
+ ],
+ ],
+ 'is_notify' => [
'name' => 'is_notify',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Notify Owner?') ,
- 'description' => 'Notify owner via email when someone donates to page?',
+ 'title' => ts('Notify Owner?'),
+ 'description' => ts('Notify owner via email when someone donates to page?'),
+ 'where' => 'civicrm_pcp.is_notify',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -434,10 +448,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -445,15 +460,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/PCP/DAO/PCPBlock.php b/CRM/PCP/DAO/PCPBlock.php
index f3a4f7a7c24e..2fa66b91dd3d 100644
--- a/CRM/PCP/DAO/PCPBlock.php
+++ b/CRM/PCP/DAO/PCPBlock.php
@@ -1,353 +1,363 @@
__table = 'civicrm_pcp_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'supporter_profile_id', 'civicrm_uf_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'target_entity_id', NULL, 'id', 'target_entity_type');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'supporter_profile_id', 'civicrm_uf_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'target_entity_id', NULL, 'id', 'target_entity_type');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('PCP Block ID') ,
- 'description' => 'PCP block Id',
- 'required' => true,
+ 'title' => ts('PCP Block ID'),
+ 'description' => ts('PCP block Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
+ 'title' => ts('Entity Table'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pcp_block.entity_table',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity') ,
- 'description' => 'FK to civicrm_contribution_page.id OR civicrm_event.id',
- 'required' => true,
+ 'title' => ts('Entity'),
+ 'description' => ts('FK to civicrm_contribution_page.id OR civicrm_event.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.entity_id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'target_entity_type' => array(
+ ],
+ 'target_entity_type' => [
'name' => 'target_entity_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Target Entity') ,
- 'description' => 'The type of entity that this pcp targets',
- 'required' => true,
+ 'title' => ts('Target Entity'),
+ 'description' => ts('The type of entity that this pcp targets'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.target_entity_type',
'default' => 'contribute',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'target_entity_id' => array(
+ ],
+ 'target_entity_id' => [
'name' => 'target_entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Target Entity ID') ,
- 'description' => 'The entity that this pcp targets',
- 'required' => true,
+ 'title' => ts('Target Entity ID'),
+ 'description' => ts('The entity that this pcp targets'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.target_entity_id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'supporter_profile_id' => array(
+ ],
+ 'supporter_profile_id' => [
'name' => 'supporter_profile_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Supporter Profile') ,
- 'description' => 'FK to civicrm_uf_group.id. Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?',
+ 'title' => ts('Supporter Profile'),
+ 'description' => ts('FK to civicrm_uf_group.id. Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?'),
+ 'where' => 'civicrm_pcp_block.supporter_profile_id',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_UFGroup',
- ) ,
- 'owner_notify_id' => array(
+ ],
+ 'owner_notify_id' => [
'name' => 'owner_notify_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Owner Notification') ,
- 'description' => 'FK to civicrm_option_group with name = PCP owner notifications',
+ 'title' => ts('Owner Notification'),
+ 'description' => ts('FK to civicrm_option_group with name = PCP owner notifications'),
+ 'where' => 'civicrm_pcp_block.owner_notify_id',
+ 'default' => '0',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Radio',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'pcp_owner_notify',
'optionEditPath' => 'civicrm/admin/options/pcp_owner_notify',
- )
- ) ,
- 'is_approval_needed' => array(
+ ],
+ ],
+ 'is_approval_needed' => [
'name' => 'is_approval_needed',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Approval Required?') ,
- 'description' => 'Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?',
+ 'title' => ts('Approval Required?'),
+ 'description' => ts('Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?'),
+ 'where' => 'civicrm_pcp_block.is_approval_needed',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'is_tellfriend_enabled' => array(
+ ],
+ 'is_tellfriend_enabled' => [
'name' => 'is_tellfriend_enabled',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Tell a Friend Enabled?') ,
- 'description' => 'Does Personal Campaign Page allow using tell a friend?',
+ 'title' => ts('Tell a Friend Enabled?'),
+ 'description' => ts('Does Personal Campaign Page allow using tell a friend?'),
+ 'where' => 'civicrm_pcp_block.is_tellfriend_enabled',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'tellfriend_limit' => array(
+ ],
+ 'tellfriend_limit' => [
'name' => 'tellfriend_limit',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Tell A Friend Limit') ,
- 'description' => 'Maximum recipient fields allowed in tell a friend',
+ 'title' => ts('Tell A Friend Limit'),
+ 'description' => ts('Maximum recipient fields allowed in tell a friend'),
+ 'where' => 'civicrm_pcp_block.tellfriend_limit',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'link_text' => array(
+ ],
+ 'link_text' => [
'name' => 'link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Link Text') ,
- 'description' => 'Link text for PCP.',
+ 'title' => ts('Link Text'),
+ 'description' => ts('Link text for PCP.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.link_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 1,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'description' => 'Is Personal Campaign Page Block enabled/active?',
+ 'title' => ts('Enabled?'),
+ 'description' => ts('Is Personal Campaign Page Block enabled/active?'),
+ 'where' => 'civicrm_pcp_block.is_active',
'default' => '1',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'notify_email' => array(
+ ],
+ 'notify_email' => [
'name' => 'notify_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Notification Email') ,
- 'description' => 'If set, notification is automatically emailed to this email-address on create/update Personal Campaign Page',
+ 'title' => ts('Notification Email'),
+ 'description' => ts('If set, notification is automatically emailed to this email-address on create/update Personal Campaign Page'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.notify_email',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -355,10 +365,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -366,15 +377,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/PCP/Form/Campaign.php b/CRM/PCP/Form/Campaign.php
index 8e5ea5fd9329..fe2bb9880fa9 100644
--- a/CRM/PCP/Form/Campaign.php
+++ b/CRM/PCP/Form/Campaign.php
@@ -1,9 +1,9 @@
_component = CRM_Utils_Request::retrieve('component', 'String', $this);
$this->assign('component', $this->_component);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $this->_context);
$this->_pageId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
@@ -71,7 +71,7 @@ public function preProcess() {
* Default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$dao = new CRM_PCP_DAO_PCP();
if ($this->_pageId) {
@@ -110,21 +110,21 @@ public function buildQuickForm() {
$this->add('text', 'goal_amount', ts('Your Goal'), NULL, TRUE);
$this->addRule('goal_amount', ts('Goal Amount should be a numeric value'), 'money');
- $attributes = array();
+ $attributes = [];
if ($this->_component == 'event') {
if ($this->get('action') & CRM_Core_Action::ADD) {
- $attributes = array('value' => ts('Join Us'), 'onClick' => 'select();');
+ $attributes = ['value' => ts('Join Us'), 'onClick' => 'select();'];
}
$this->add('text', 'donate_link_text', ts('Sign up Button'), $attributes);
}
else {
if ($this->get('action') & CRM_Core_Action::ADD) {
- $attributes = array('value' => ts('Donate Now'), 'onClick' => 'select();');
+ $attributes = ['value' => ts('Donate Now'), 'onClick' => 'select();'];
}
$this->add('text', 'donate_link_text', ts('Donation Button'), $attributes);
}
- $attrib = array('rows' => 8, 'cols' => 60);
+ $attrib = ['rows' => 8, 'cols' => 60];
$this->add('textarea', 'page_text', ts('Your Message'), NULL, FALSE);
$maxAttachments = 1;
@@ -133,14 +133,14 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_thermometer', ts('Progress Bar'));
$this->addElement('checkbox', 'is_honor_roll', ts('Honor Roll'), NULL);
if ($this->_pageId) {
- $params = array('id' => $this->_pageId);
+ $params = ['id' => $this->_pageId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
- $owner_notification_option = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
+ $owner_notification_option = CRM_Core_DAO::getFieldValue('CRM_PCP_BAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
}
else {
$owner_notification_option = CRM_PCP_BAO_PCP::getOwnerNotificationId($this->controller->get('component_page_id'), $this->_component ? $this->_component : 'contribute');
}
- if ($owner_notification_option == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name')) {
+ if ($owner_notification_option == CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCPBlock', 'owner_notify_id', 'owner_chooses')) {
$this->assign('owner_notification_option', TRUE);
$this->addElement('checkbox', 'is_notify', ts('Notify me via email when someone donates to my page'), NULL);
}
@@ -151,19 +151,19 @@ public function buildQuickForm() {
}
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
- $this->addFormRule(array('CRM_PCP_Form_Campaign', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Campaign', 'formRule'], $this);
}
/**
@@ -180,7 +180,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($fields['goal_amount'] <= 0) {
$errors['goal_amount'] = ts('Goal Amount should be a numeric value greater than zero.');
}
@@ -195,7 +195,7 @@ public static function formRule($fields, $files, $self) {
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
- $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active', 'is_notify');
+ $checkBoxes = ['is_thermometer', 'is_honor_roll', 'is_active', 'is_notify'];
foreach ($checkBoxes as $key) {
if (!isset($params[$key])) {
@@ -215,7 +215,7 @@ public function postProcess() {
// since we are allowing html input from the user
// we also need to purify it, so lets clean it up
- $htmlFields = array('intro_text', 'page_text', 'title');
+ $htmlFields = ['intro_text', 'page_text', 'title'];
foreach ($htmlFields as $field) {
if (!empty($params[$field])) {
$params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
@@ -256,10 +256,10 @@ public function postProcess() {
$statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id');
//send notification of PCP create/update.
- $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id);
- $notifyParams = array();
+ $pcpParams = ['entity_table' => $entity_table, 'entity_id' => $pcp->page_id];
+ $notifyParams = [];
$notifyStatus = "";
- CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
+ CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, ['notify_email']);
if ($emails = $pcpBlock->notify_email) {
$this->assign('pcpTitle', $pcp->title);
@@ -270,7 +270,7 @@ public function postProcess() {
else {
$this->assign('mode', 'Add');
}
- $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId);
+ $pcpStatus = CRM_Core_PseudoConstant::getLabel('CRM_PCP_DAO_PCP', 'status_id', $statusId);
$this->assign('pcpStatus', $pcpStatus);
$this->assign('pcpId', $pcp->id);
@@ -307,7 +307,7 @@ public function postProcess() {
$managePCPUrl = CRM_Utils_System::url('civicrm/admin/pcp',
"reset=1",
TRUE, NULL, FALSE,
- FALSE
+ FALSE, TRUE
);
$this->assign('managePCPUrl', $managePCPUrl);
@@ -316,7 +316,7 @@ public function postProcess() {
if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') {
$fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1');
- CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl)));
+ CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', [1 => $fixUrl]));
}
//if more than one email present for PCP notification ,
@@ -329,14 +329,14 @@ public function postProcess() {
$cc = implode(',', $emailArray);
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'pcp_notify',
'contactId' => $contactID,
'from' => "$domainEmailName <$domainEmailAddress>",
'toEmail' => $to,
'cc' => $cc,
- )
+ ]
);
if ($sent) {
@@ -361,7 +361,7 @@ public function postProcess() {
}
CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3",
- array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)
+ [1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus]
), '', 'info');
if (!$this->_pageId) {
$session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
diff --git a/CRM/PCP/Form/Contribute.php b/CRM/PCP/Form/Contribute.php
index 4a5dd93ddf62..4a09ff4cda2e 100644
--- a/CRM/PCP/Form/Contribute.php
+++ b/CRM/PCP/Form/Contribute.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_contribution_page');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_contribution_page'];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $defaults);
$defaults['pcp_active'] = CRM_Utils_Array::value('is_active', $defaults);
// Assign contribution page ID to pageId for referencing in PCP.hlp - since $id is overwritten there. dgg
@@ -92,10 +92,10 @@ public function buildQuickForm() {
$this->_last = TRUE;
CRM_PCP_BAO_PCP::buildPCPForm($this);
- $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this contribution page)'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"));
+ $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this contribution page)'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"]);
parent::buildQuickForm();
- $this->addFormRule(array('CRM_PCP_Form_Contribute', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Contribute', 'formRule'], $this);
}
/**
@@ -111,7 +111,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($params['is_active'])) {
if (!empty($params['is_tellfriend_enabled']) &&
diff --git a/CRM/PCP/Form/Event.php b/CRM/PCP/Form/Event.php
index 2059006add5a..f242036b3e04 100644
--- a/CRM/PCP/Form/Event.php
+++ b/CRM/PCP/Form/Event.php
@@ -1,9 +1,9 @@
setSelectedChild('pcp');
}
/**
* Set default values for the form.
*
- *
- * @return void
+ * @return array
*/
public function setDefaultValues() {
- $defaults = array();
-
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
$title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'title');
- CRM_Utils_System::setTitle(ts('Personal Campaign Page Settings (%1)', array(1 => $title)));
+ CRM_Utils_System::setTitle(ts('Personal Campaign Page Settings (%1)', [1 => $title]));
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_event'];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $defaults);
$defaults['pcp_active'] = CRM_Utils_Array::value('is_active', $defaults);
// Assign contribution page ID to pageId for referencing in PCP.hlp - since $id is overwritten there. dgg
@@ -97,18 +94,18 @@ public function setDefaultValues() {
public function buildQuickForm() {
CRM_PCP_BAO_PCP::buildPCPForm($this);
- $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this event)'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"));
+ $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this event)'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"]);
$this->add('select', 'target_entity_type', ts('Campaign Type'),
- array('' => ts('- select -'), 'event' => ts('Event'), 'contribute' => ts('Contribution')),
- NULL, array('onchange' => "return showHideByValue('target_entity_type','contribute','pcpDetailFields','block','select',false);")
+ ['' => ts('- select -'), 'event' => ts('Event'), 'contribute' => ts('Contribution')],
+ NULL, ['onchange' => "return showHideByValue('target_entity_type','contribute','pcpDetailFields','block','select',false);"]
);
$this->add('select', 'target_entity_id',
ts('Online Contribution Page'),
- array(
+ [
'' => ts('- select -'),
- ) +
+ ] +
CRM_Contribute_PseudoConstant::contributionPage()
);
@@ -121,15 +118,15 @@ public function buildQuickForm() {
$pcpBlock->find(TRUE);
if (!empty($pcpBlock->id) && CRM_PCP_BAO_PCP::getPcpBlockInUse($pcpBlock->id)) {
- foreach (array(
- 'target_entity_type',
- 'target_entity_id',
- ) as $element_name) {
+ foreach ([
+ 'target_entity_type',
+ 'target_entity_id',
+ ] as $element_name) {
$element = $this->getElement($element_name);
$element->freeze();
}
}
- $this->addFormRule(array('CRM_PCP_Form_Event', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Event', 'formRule'], $this);
}
/**
@@ -145,7 +142,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($params['is_active'])) {
if (!empty($params['is_tellfriend_enabled']) &&
@@ -177,7 +174,6 @@ public static function formRule($params, $files, $self) {
/**
* Process the form submission.
*
- *
* @return void
*/
public function postProcess() {
diff --git a/CRM/PCP/Form/PCP.php b/CRM/PCP/Form/PCP.php
index 89a0caaecb53..ff39071278fb 100644
--- a/CRM/PCP/Form/PCP.php
+++ b/CRM/PCP/Form/PCP.php
@@ -1,9 +1,9 @@
_context)) {
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
}
$this->assign('context', $this->_context);
@@ -92,19 +92,19 @@ public function preProcess() {
case CRM_Core_Action::DELETE:
case 'delete':
CRM_PCP_BAO_PCP::deleteById($this->_id);
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", array(1 => $this->_title)), ts('Page Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", [1 => $this->_title]), ts('Page Deleted'), 'success');
break;
case CRM_Core_Action::DISABLE:
case 'disable':
CRM_PCP_BAO_PCP::setDisable($this->_id, '0');
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been disabled.", array(1 => $this->_title)), ts('Page Disabled'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been disabled.", [1 => $this->_title]), ts('Page Disabled'), 'success');
break;
case CRM_Core_Action::ENABLE:
case 'enable':
CRM_PCP_BAO_PCP::setDisable($this->_id, '1');
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been enabled.", array(1 => $this->_title)), ts('Page Enabled'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been enabled.", [1 => $this->_title]), ts('Page Enabled'), 'success');
break;
}
@@ -122,7 +122,7 @@ public function preProcess() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$pageType = CRM_Utils_Request::retrieve('page_type', 'String', $this);
$defaults['page_type'] = !empty($pageType) ? $pageType : '';
@@ -135,43 +135,41 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Campaign'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
else {
- $status = array('' => ts('- select -')) + CRM_Core_OptionGroup::values("pcp_status");
- $types = array(
+ $status = ['' => ts('- select -')] + CRM_Core_OptionGroup::values("pcp_status");
+ $types = [
'' => ts('- select -'),
'contribute' => ts('Contribution'),
'event' => ts('Event'),
- );
- $contribPages = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage();
- $eventPages = array('' => ts('- select -')) + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
+ ];
+ $contribPages = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::contributionPage();
+ $eventPages = ['' => ts('- select -')] + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$this->addElement('select', 'status_id', ts('Status'), $status);
$this->addElement('select', 'page_type', ts('Source Type'), $types);
$this->addElement('select', 'page_id', ts('Contribution Page'), $contribPages);
$this->addElement('select', 'event_id', ts('Event Page'), $eventPages);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
parent::buildQuickForm();
}
}
@@ -197,14 +195,14 @@ public static function formRule($fields, $files, $form) {
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_PCP_BAO_PCP::deleteById($this->_id);
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", array(1 => $this->_title)), ts('Page Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", [1 => $this->_title]), ts('Page Deleted'), 'success');
}
else {
$params = $this->controller->exportValues($this->_name);
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array('status_id', 'page_id');
+ $fields = ['status_id', 'page_id'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
diff --git a/CRM/PCP/Form/PCPAccount.php b/CRM/PCP/Form/PCPAccount.php
index d62abf8640f0..624b873b4ce5 100644
--- a/CRM/PCP/Form/PCPAccount.php
+++ b/CRM/PCP/Form/PCPAccount.php
@@ -1,9 +1,9 @@
_defaults = array();
+ $this->_defaults = [];
if ($this->_contactID) {
foreach ($this->_fields as $name => $dontcare) {
$fields[$name] = 1;
@@ -143,7 +144,7 @@ public function buildQuickForm() {
if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $this->_contactID)) {
$fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
}
- $this->addFormRule(array('CRM_PCP_Form_PCPAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_PCPAccount', 'formRule'], $this);
}
else {
CRM_Core_BAO_CMSUser::buildForm($this, $id, TRUE);
@@ -183,28 +184,28 @@ public function buildQuickForm() {
}
if ($this->_single) {
- $button = array(
- array(
+ $button = [
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
}
else {
- $button[] = array(
+ $button[] = [
'type' => 'next',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- );
+ ];
}
- $this->addFormRule(array('CRM_PCP_Form_PCPAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_PCPAccount', 'formRule'], $this);
$this->addButtons($button);
}
@@ -222,7 +223,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
foreach ($fields as $key => $value) {
if (strpos($key, 'email-') !== FALSE && !empty($value)) {
$ufContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFMatch', $value, 'contact_id', 'uf_name');
@@ -257,7 +258,7 @@ public function postProcess() {
$isPrimary = 1;
}
- $params['email'] = array();
+ $params['email'] = [];
$params['email'][1]['email'] = $value;
$params['email'][1]['location_type_id'] = $locTypeId;
$params['email'][1]['is_primary'] = $isPrimary;
@@ -265,7 +266,7 @@ public function postProcess() {
}
}
- $this->_contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', array(), FALSE);
+ $this->_contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', [], FALSE);
$contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID);
$this->set('contactID', $contactID);
diff --git a/CRM/PCP/Page/PCP.php b/CRM/PCP/Page/PCP.php
index e090829e0e06..58768df2e0ad 100644
--- a/CRM/PCP/Page/PCP.php
+++ b/CRM/PCP/Page/PCP.php
@@ -1,9 +1,9 @@
getIdAndAction();
+
+ if ($this->_action & CRM_Core_Action::REVERT) {
CRM_PCP_BAO_PCP::setIsActive($id, 0);
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
}
- elseif ($action & CRM_Core_Action::RENEW) {
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
+ elseif ($this->_action & CRM_Core_Action::RENEW) {
CRM_PCP_BAO_PCP::setIsActive($id, 1);
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
}
- elseif ($action & CRM_Core_Action::DELETE) {
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
+ elseif ($this->_action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1&action=browse'));
$controller = new CRM_Core_Controller_Simple('CRM_PCP_Form_PCP',
@@ -156,7 +150,7 @@ public function run() {
$this->browse();
// parent run
- parent::run();
+ CRM_Core_Page::run();
}
/**
@@ -220,7 +214,7 @@ public function browse($action = NULL) {
}
}
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
+ $approvedId = CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCP', 'status_id', 'Approved');
//check for delete CRM-4418
$allowToDelete = CRM_Core_Permission::check('delete in CiviContribute');
diff --git a/CRM/PCP/Page/PCPInfo.php b/CRM/PCP/Page/PCPInfo.php
index 3a0cd2800737..1327de5a63a6 100644
--- a/CRM/PCP/Page/PCPInfo.php
+++ b/CRM/PCP/Page/PCPInfo.php
@@ -1,9 +1,9 @@
$this->_id);
+ $prms = ['id' => $this->_id];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
$this->_component = $pcpInfo['page_type'];
@@ -77,13 +77,13 @@ public function run() {
$this->assign('pcp', $pcpInfo);
$pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
+ $approvedId = CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCP', 'status_id', 'Approved');
// check if PCP is created by anonymous user
$anonymousPCP = CRM_Utils_Request::retrieve('ap', 'Boolean', $this);
if ($anonymousPCP) {
$loginURL = $config->userSystem->getLoginURL();
- $anonMessage = ts('Once you\'ve received your new account welcome email, you can click here to login and promote your campaign page.', array(1 => $loginURL));
+ $anonMessage = ts('Once you\'ve received your new account welcome email, you can click here to login and promote your campaign page.', [1 => $loginURL]);
CRM_Core_Session::setStatus($anonMessage, ts('Success'), 'success');
}
else {
@@ -122,7 +122,7 @@ public function run() {
}
}
- $default = array();
+ $default = [];
if ($pcpBlock->target_entity_type == 'contribute') {
$urlBase = 'civicrm/contribute/transact';
@@ -135,19 +135,19 @@ public function run() {
$page_class = 'CRM_Event_DAO_Event';
$this->assign('pageName', CRM_Event_PseudoConstant::event($pcpInfo['page_id']));
CRM_Core_DAO::commonRetrieveAll($page_class, 'id',
- $pcpInfo['page_id'], $default, array(
+ $pcpInfo['page_id'], $default, [
'start_date',
'end_date',
'registration_start_date',
'registration_end_date',
- )
+ ]
);
}
elseif ($pcpBlock->entity_table == 'civicrm_contribution_page') {
$page_class = 'CRM_Contribute_DAO_ContributionPage';
$this->assign('pageName', CRM_Contribute_PseudoConstant::contributionPage($pcpInfo['page_id'], TRUE));
CRM_Core_DAO::commonRetrieveAll($page_class, 'id',
- $pcpInfo['page_id'], $default, array('start_date', 'end_date')
+ $pcpInfo['page_id'], $default, ['start_date', 'end_date']
);
}
@@ -161,7 +161,7 @@ public function run() {
$link = CRM_PCP_BAO_PCP::pcpLinks();
- $hints = array(
+ $hints = [
CRM_Core_Action::UPDATE => ts('Change the content and appearance of your page'),
CRM_Core_Action::DETACH => ts('Send emails inviting your friends to support your campaign!'),
CRM_Core_Action::VIEW => ts('Copy this link to share directly with your network!'),
@@ -169,13 +169,13 @@ public function run() {
CRM_Core_Action::DISABLE => ts('De-activate the page (you can re-activate it later)'),
CRM_Core_Action::ENABLE => ts('Activate the page (you can de-activate it later)'),
CRM_Core_Action::DELETE => ts('Remove the page (this cannot be undone!)'),
- );
+ ];
- $replace = array(
+ $replace = [
'id' => $this->_id,
'block' => $pcpBlock->id,
'pageComponent' => $this->_component,
- );
+ ];
if (!$pcpBlock->is_tellfriend_enabled || CRM_Utils_Array::value('status_id', $pcpInfo) != $approvedId) {
unset($link['all'][CRM_Core_Action::DETACH]);
@@ -202,8 +202,9 @@ public function run() {
if (!empty($entityFile)) {
$fileInfo = reset($entityFile);
$fileId = $fileInfo['fileID'];
+ $fileHash = CRM_Core_BAO_File::generateFileHash($this->_id, $fileId);
$image = '_id}"
+ "reset=1&id=$fileId&eid={$this->_id}&fcs={$fileHash}"
) . '" />';
$this->assign('image', $image);
}
diff --git a/CRM/PCP/StateMachine/PCP.php b/CRM/PCP/StateMachine/PCP.php
index 34f81e92c27a..a1040ffe45a8 100644
--- a/CRM/PCP/StateMachine/PCP.php
+++ b/CRM/PCP/StateMachine/PCP.php
@@ -1,9 +1,9 @@
set('singleForm', FALSE);
- $this->_pages = array(
+ $this->_pages = [
'CRM_PCP_Form_PCPAccount' => NULL,
'CRM_PCP_Form_Campaign' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Pledge/BAO/Pledge.php b/CRM/Pledge/BAO/Pledge.php
index f368882facfd..e5feb625b599 100644
--- a/CRM/Pledge/BAO/Pledge.php
+++ b/CRM/Pledge/BAO/Pledge.php
@@ -1,9 +1,9 @@
CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id),
'honorId' => $pledgeDAO->contact_id,
'amount' => $pledgeDAO->amount,
- 'status' => CRM_Contribute_PseudoConstant::contributionStatus($pledgeDAO->status_id),
+ 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id),
'create_date' => $pledgeDAO->create_date,
'acknowledge_date' => $pledgeDAO->acknowledge_date,
'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
@@ -613,7 +613,7 @@ public static function sendAcknowledgment(&$form, $params) {
// handle custom data.
if (!empty($params['hidden_custom'])) {
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', CRM_Core_DAO::$_nullObject, $params['id']);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']);
$pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
$customGroup = array();
// retrieve custom data
@@ -678,9 +678,9 @@ public static function sendAcknowledgment(&$form, $params) {
$activityType = 'Pledge Acknowledgment';
$activity = new CRM_Activity_DAO_Activity();
$activity->source_record_id = $params['id'];
- $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
- $activityType,
- 'name'
+ $activity->activity_type_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
+ 'activity_type_id',
+ $activityType
);
// FIXME: Translate
@@ -691,9 +691,9 @@ public static function sendAcknowledgment(&$form, $params) {
'subject' => $subject,
'source_contact_id' => $params['contact_id'],
'source_record_id' => $params['id'],
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- $activityType,
- 'name'
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
+ 'activity_type_id',
+ $activityType
),
'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']),
'is_test' => $params['is_test'],
@@ -790,16 +790,18 @@ public static function exportableFields($checkPermission = TRUE) {
*/
public static function getContactPledges($contactID) {
$pledgeDetails = array();
- $pledgeStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
+ FALSE, FALSE, FALSE, NULL, 'name'
+ );
$status = array();
// get pending and in progress status
foreach (array(
- 'Pending',
- 'In Progress',
- 'Overdue',
- ) as $name) {
+ 'Pending',
+ 'In Progress',
+ 'Overdue',
+ ) as $name) {
if ($statusId = array_search($name, $pledgeStatuses)) {
$status[] = $statusId;
}
@@ -851,20 +853,15 @@ public static function updatePledgeStatus($params) {
$sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
- $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
-
- // unset statues that we never use for pledges
- foreach (array(
- 'Completed',
- 'Cancelled',
- 'Failed',
- ) as $statusKey) {
- if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
- unset($allStatus[$key]);
- }
- }
+ $allStatus = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
+ $allPledgeStatus = CRM_Core_OptionGroup::values('pledge_status',
+ TRUE, FALSE, FALSE, NULL, 'name', TRUE
+ );
+ unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
+ unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
- $statusIds = implode(',', array_keys($allStatus));
+ $statusIds = implode(',', $allStatus);
+ $pledgeStatusIds = implode(',', $allPledgeStatus);
$updateCnt = 0;
$query = "
@@ -893,7 +890,7 @@ public static function updatePledgeStatus($params) {
) as amount_paid
FROM civicrm_pledge pledge, civicrm_pledge_payment payment
WHERE pledge.id = payment.pledge_id
- AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
+ AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
GROUP By payment.id
";
@@ -931,23 +928,23 @@ public static function updatePledgeStatus($params) {
if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
$now
- ) && $dao->payment_status != array_search('Overdue', $allStatus)
+ ) && $dao->payment_status != $allStatus['Overdue']
) {
$pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
}
}
+ $allPledgeStatus = array_flip($allPledgeStatus);
// process the updating script...
-
foreach ($pledgePayments as $pledgeId => $paymentIds) {
// 1. update the pledge /pledge payment status. returns new status when an update happens
- $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
+ $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
$newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
- array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
+ $allStatus['Overdue'], NULL, 0, FALSE, TRUE
);
if ($newStatus != $pledgeStatus[$pledgeId]) {
- $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
+ $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
$updateCnt += 1;
}
}
@@ -1058,9 +1055,9 @@ public static function updatePledgeStatus($params) {
'source_contact_id' => $contactId,
'source_record_id' => $paymentId,
'assignee_contact_id' => $contactId,
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- $activityType,
- 'name'
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
+ 'activity_type_id',
+ $activityType
),
'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
'is_test' => $details['is_test'],
@@ -1109,7 +1106,7 @@ public static function cancel($pledgeID) {
* Array of int (civicrm_pledge_payment.id)
*/
public static function findCancelablePayments($pledgeID) {
- $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
+ $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'));
$paymentDAO = new CRM_Pledge_DAO_PledgePayment();
$paymentDAO->pledge_id = $pledgeID;
@@ -1148,7 +1145,7 @@ public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID
return civicrm_api3('pledge_payment', 'getcount', array(
'pledge_id' => $pledgeID,
- 'contribution_id' => array('NOT NULL' => TRUE),
+ 'contribution_id' => array('IS NOT NULL' => TRUE),
));
}
@@ -1177,7 +1174,6 @@ protected static function getNonTransactionalStatus() {
return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
}
-
/**
* Create array for recur record for pledge.
* @return array
@@ -1203,32 +1199,33 @@ public static function buildRecurParams($params) {
*/
public static function getPledgeStartDate($date, $pledgeBlock) {
$startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
- list($field, $value) = each($startDate);
- if (!empty($date) && !CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
- return $date;
- }
- if (empty($date)) {
- $date = $value;
- }
- switch ($field) {
- case 'contribution_date':
- if (empty($date)) {
- $date = date('Ymd');
- }
- break;
+ foreach ($startDate as $field => $value) {
+ if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
+ return $date;
+ }
+ if (empty($date)) {
+ $date = $value;
+ }
+ switch ($field) {
+ case 'contribution_date':
+ if (empty($date)) {
+ $date = date('Ymd');
+ }
+ break;
- case 'calendar_date':
- $date = date('Ymd', strtotime($date));
- break;
+ case 'calendar_date':
+ $date = date('Ymd', strtotime($date));
+ break;
- case 'calendar_month':
- $date = self::getPaymentDate($date);
- $date = date('Ymd', strtotime($date));
- break;
+ case 'calendar_month':
+ $date = self::getPaymentDate($date);
+ $date = date('Ymd', strtotime($date));
+ break;
- default:
- break;
+ default:
+ break;
+ }
}
return $date;
}
diff --git a/CRM/Pledge/BAO/PledgeBlock.php b/CRM/Pledge/BAO/PledgeBlock.php
index 4ca50a57e1b9..9d63fd5db409 100644
--- a/CRM/Pledge/BAO/PledgeBlock.php
+++ b/CRM/Pledge/BAO/PledgeBlock.php
@@ -1,9 +1,9 @@
_values['pledge_id'], $allPayments, $returnProperties
@@ -282,11 +281,11 @@ public static function buildPledgeBlock($form) {
$form->addRadio('is_pledge', ts('Pledge Frequency Interval'), $pledgeOptions,
NULL, array('
')
);
- $form->addElement('text', 'pledge_installments', ts('Installments'), array('size' => 3));
+ $form->addElement('text', 'pledge_installments', ts('Installments'), ['size' => 3, 'aria-label' => ts('Installments')]);
if (!empty($pledgeBlock['is_pledge_interval'])) {
$form->assign('is_pledge_interval', CRM_Utils_Array::value('is_pledge_interval', $pledgeBlock));
- $form->addElement('text', 'pledge_frequency_interval', NULL, array('size' => 3));
+ $form->addElement('text', 'pledge_frequency_interval', NULL, ['size' => 3, 'aria-label' => ts('Frequency Intervals')]);
}
else {
$form->add('hidden', 'pledge_frequency_interval', 1);
@@ -300,47 +299,48 @@ public static function buildPledgeBlock($form) {
$freqUnits[$val] = !empty($pledgeBlock['is_pledge_interval']) ? "{$frequencyUnits[$val]}(s)" : $frequencyUnits[$val];
}
}
- $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits);
+ $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits, ['aria-label' => ts('Frequency Units')]);
// CRM-18854
- if (CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) {
- if (CRM_Utils_Array::value('pledge_start_date', $pledgeBlock)) {
+ if (!empty($pledgeBlock['is_pledge_start_date_visible'])) {
+ if (!empty($pledgeBlock['pledge_start_date'])) {
$defaults = array();
$date = (array) json_decode($pledgeBlock['pledge_start_date']);
- list($field, $value) = each($date);
- switch ($field) {
- case 'contribution_date':
- $form->addDate('start_date', ts('First installment payment'));
- $paymentDate = $value = date('m/d/Y');
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(NULL);
- $form->assign('is_date', TRUE);
- break;
-
- case 'calendar_date':
- $form->addDate('start_date', ts('First installment payment'));
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
- $form->assign('is_date', TRUE);
- $paymentDate = $value;
- break;
-
- case 'calendar_month':
- $month = CRM_Utils_Date::getCalendarDayOfMonth();
- $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
- $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($paymentDate);
- break;
-
- default:
- break;
+ foreach ($date as $field => $value) {
+ switch ($field) {
+ case 'contribution_date':
+ $form->add('datepicker', 'start_date', ts('First installment payment'), [], FALSE, ['time' => FALSE]);
+ $paymentDate = $value = date('Y-m-d');
+ $defaults['start_date'] = $value;
+ $form->assign('is_date', TRUE);
+ break;
+
+ case 'calendar_date':
+ $form->add('datepicker', 'start_date', ts('First installment payment'), [], FALSE, ['time' => FALSE]);
+ $defaults['start_date'] = $value;
+ $form->assign('is_date', TRUE);
+ $paymentDate = $value;
+ break;
+
+ case 'calendar_month':
+ $month = CRM_Utils_Date::getCalendarDayOfMonth();
+ $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
+ $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
+ $defaults['start_date'] = $paymentDate;
+ break;
+
+ default:
+ break;
- }
- $form->setDefaults($defaults);
- $form->assign('start_date_display', $paymentDate);
- $form->assign('start_date_editable', FALSE);
- if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
- $form->assign('start_date_editable', TRUE);
- if ($field == 'calendar_month') {
- $form->assign('is_date', FALSE);
- $form->setDefaults(array('start_date' => $value));
+ }
+ $form->setDefaults($defaults);
+ $form->assign('start_date_display', $paymentDate);
+ $form->assign('start_date_editable', FALSE);
+ if (!empty($pledgeBlock['is_pledge_start_date_editable'])) {
+ $form->assign('start_date_editable', TRUE);
+ if ($field == 'calendar_month') {
+ $form->assign('is_date', FALSE);
+ $form->setDefaults(array('start_date' => $value));
+ }
}
}
}
diff --git a/CRM/Pledge/BAO/PledgePayment.php b/CRM/Pledge/BAO/PledgePayment.php
index 484f2296a5a0..7de77302e0a6 100644
--- a/CRM/Pledge/BAO/PledgePayment.php
+++ b/CRM/Pledge/BAO/PledgePayment.php
@@ -1,9 +1,9 @@
fetch()) {
$paymentDetails[$payment->id]['scheduled_amount'] = $payment->scheduled_amount;
$paymentDetails[$payment->id]['scheduled_date'] = $payment->scheduled_date;
@@ -98,27 +98,28 @@ public static function getPledgePayments($pledgeId) {
*/
public static function create($params) {
$transaction = new CRM_Core_Transaction();
- $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $overdueStatusID = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Overdue');
+ $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Pending');
//calculate the scheduled date for every installment
$now = date('Ymd') . '000000';
- $statues = $prevScheduledDate = array();
+ $statues = $prevScheduledDate = [];
$prevScheduledDate[1] = CRM_Utils_Date::processDate($params['scheduled_date']);
if (CRM_Utils_Date::overdue($prevScheduledDate[1], $now)) {
- $statues[1] = array_search('Overdue', $contributionStatus);
+ $statues[1] = $overdueStatusID;
}
else {
- $statues[1] = array_search('Pending', $contributionStatus);
+ $statues[1] = $pendingStatusId;
}
for ($i = 1; $i < $params['installments']; $i++) {
$prevScheduledDate[$i + 1] = self::calculateNextScheduledDate($params, $i);
if (CRM_Utils_Date::overdue($prevScheduledDate[$i + 1], $now)) {
- $statues[$i + 1] = array_search('Overdue', $contributionStatus);
+ $statues[$i + 1] = $overdueStatusID;
}
else {
- $statues[$i + 1] = array_search('Pending', $contributionStatus);
+ $statues[$i + 1] = $pendingStatusId;
}
}
@@ -287,16 +288,13 @@ public static function deletePayments($id) {
* @return bool
*/
public static function resetPledgePayment($contributionID) {
- // get all status
- $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
-
$transaction = new CRM_Core_Transaction();
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->contribution_id = $contributionID;
if ($payment->find(TRUE)) {
$payment->contribution_id = 'null';
- $payment->status_id = array_search('Pending', $allStatus);
+ $payment->status_id = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
$payment->scheduled_date = NULL;
$payment->reminder_date = NULL;
$payment->scheduled_amount = $payment->actual_amount;
@@ -308,7 +306,6 @@ public static function resetPledgePayment($contributionID) {
$pledgeStatusID = self::calculatePledgeStatus($pledgeID);
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'status_id', $pledgeStatusID);
- $payment->free();
}
$transaction->commit();
@@ -319,18 +316,18 @@ public static function resetPledgePayment($contributionID) {
* Update Pledge Payment Status.
*
* @param int $pledgeID
- * , id of pledge.
+ * Id of pledge.
* @param array $paymentIDs
- * , ids of pledge payment(s) to update.
+ * Ids of pledge payment(s) to update.
* @param int $paymentStatusID
- * , payment status to set.
+ * Payment status to set.
* @param int $pledgeStatusID
* Pledge status to change (if needed).
* @param float|int $actualAmount , actual amount being paid
* @param bool $adjustTotalAmount
- * , is amount being paid different from scheduled amount?.
+ * Is amount being paid different from scheduled amount?.
* @param bool $isScriptUpdate
- * , is function being called from bin script?.
+ * Is function being called from bin script?.
*
* @return int
* $newStatus, updated status id (or 0)
@@ -349,7 +346,9 @@ public static function updatePledgePaymentStatus(
$editScheduled = FALSE;
// get all statuses
- $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $allStatus = CRM_Core_OptionGroup::values('pledge_status',
+ FALSE, FALSE, FALSE, NULL, 'name', TRUE
+ );
// if we get do not get contribution id means we are editing the scheduled payment.
if (!empty($paymentIDs)) {
@@ -367,8 +366,9 @@ public static function updatePledgePaymentStatus(
}
// if payment ids are passed, we update payment table first, since payments statuses are not dependent on pledge status
- if ((!empty($paymentIDs) || $pledgeStatusID == array_search('Cancelled', $allStatus)) && (!$editScheduled || $isScriptUpdate)) {
- if ($pledgeStatusID == array_search('Cancelled', $allStatus)) {
+ $pledgeStatusName = CRM_Core_PseudoConstant::getName('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeStatusID);
+ if ((!empty($paymentIDs) || $pledgeStatusName == 'Cancelled') && (!$editScheduled || $isScriptUpdate)) {
+ if ($pledgeStatusName == 'Cancelled') {
$paymentStatusID = $pledgeStatusID;
}
@@ -417,12 +417,12 @@ public static function updatePledgePaymentStatus(
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit,
$pledgeFrequencyInterval, $newDate
));
- $pledgeParams = array(
+ $pledgeParams = [
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => ($pledgeScheduledAmount - $actualAmount),
'scheduled_date' => $ScheduledDate,
- );
+ ];
$payment = self::add($pledgeParams);
// while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
if (!$paymentContributionId) {
@@ -450,7 +450,7 @@ public static function updatePledgePaymentStatus(
WHERE civicrm_pledge_payment.pledge_id = %1
AND civicrm_pledge_payment.status_id = 1
";
- $totalPaidParams = array(1 => array($pledgeID, 'Integer'));
+ $totalPaidParams = [1 => [$pledgeID, 'Integer']];
$totalPaidAmount = CRM_Core_DAO::singleValueQuery($balanceQuery, $totalPaidParams);
$remainingTotalAmount = ($actualPledgeAmount - $totalPaidAmount);
if (($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus)) && (($actualAmount > $remainingTotalAmount) || ($actualAmount >= $actualPledgeAmount))) {
@@ -489,12 +489,12 @@ public static function updatePledgePaymentStatus(
WHERE civicrm_pledge.id = %2
";
- $params = array(
- 1 => array($pledgeStatusID, 'Integer'),
- 2 => array($pledgeID, 'Integer'),
- );
+ $params = [
+ 1 => [$pledgeStatusID, 'Integer'],
+ 2 => [$pledgeID, 'Integer'],
+ ];
- $dao = CRM_Core_DAO::executeQuery($query, $params);
+ CRM_Core_DAO::executeQuery($query, $params);
return $pledgeStatusID;
}
@@ -511,7 +511,7 @@ public static function updatePledgePaymentStatus(
* Next scheduled date as an array
*/
public static function calculateBaseScheduleDate(&$params) {
- $date = array();
+ $date = [];
$scheduled_date = CRM_Utils_Date::processDate($params['scheduled_date']);
$date['year'] = (int) substr($scheduled_date, 0, 4);
$date['month'] = (int) substr($scheduled_date, 4, 2);
@@ -567,20 +567,20 @@ public static function calculateNextScheduledDate(&$params, $paymentNo, $basePay
}
//CRM-18316 - change $basePaymentDate for the end dates of the month eg: 29, 30 or 31.
- if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], array(29, 30, 31))) {
+ if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], [29, 30, 31])) {
$frequency = $params['frequency_day'];
extract(date_parse($basePaymentDate));
$lastDayOfMonth = date('t', mktime($hour, $minute, $second, $month + $interval, 1, $year));
// Take the last day in case the current month is Feb or frequency_day is set to 31.
- if (in_array($lastDayOfMonth, array(28, 29)) || $frequency == 31) {
+ if (in_array($lastDayOfMonth, [28, 29]) || $frequency == 31) {
$frequency = 0;
$interval++;
}
- $basePaymentDate = array(
+ $basePaymentDate = [
'M' => $month,
'd' => $frequency,
'Y' => $year,
- );
+ ];
}
return CRM_Utils_Date::format(
@@ -603,10 +603,17 @@ public static function calculateNextScheduledDate(&$params, $paymentNo, $basePay
*/
public static function calculatePledgeStatus($pledgeId) {
$paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $pledgeStatusTypes = CRM_Pledge_BAO_Pledge::buildOptions('status_id', 'validate');
+
+ //return if the pledge is cancelled.
+ $currentPledgeStatusId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'status_id', 'id', TRUE);
+ if ($currentPledgeStatusId == array_search('Cancelled', $pledgeStatusTypes)) {
+ return $currentPledgeStatusId;
+ }
// retrieve all pledge payments for this particular pledge
- $allPledgePayments = $allStatus = array();
- $returnProperties = array('status_id');
+ $allPledgePayments = $allStatus = [];
+ $returnProperties = ['status_id'];
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $pledgeId, $allPledgePayments, $returnProperties);
// build pledge payment statuses
@@ -615,18 +622,18 @@ public static function calculatePledgeStatus($pledgeId) {
}
if (array_search('Overdue', $allStatus)) {
- $statusId = array_search('Overdue', $paymentStatusTypes);
+ $statusId = array_search('Overdue', $pledgeStatusTypes);
}
elseif (array_search('Completed', $allStatus)) {
if (count(array_count_values($allStatus)) == 1) {
- $statusId = array_search('Completed', $paymentStatusTypes);
+ $statusId = array_search('Completed', $pledgeStatusTypes);
}
else {
- $statusId = array_search('In Progress', $paymentStatusTypes);
+ $statusId = array_search('In Progress', $pledgeStatusTypes);
}
}
else {
- $statusId = array_search('Pending', $paymentStatusTypes);
+ $statusId = array_search('Pending', $pledgeStatusTypes);
}
return $statusId;
@@ -662,6 +669,10 @@ public static function updatePledgePayments(
$payments = implode(',', $paymentIds);
$paymentClause = " AND civicrm_pledge_payment.id IN ( {$payments} )";
}
+ elseif ($paymentStatusId == array_search('Cancelled', $allStatus)) {
+ $completedStatus = array_search('Completed', $allStatus);
+ $paymentClause = " AND civicrm_pledge_payment.status_id != {$completedStatus}";
+ }
$actualAmountClause = NULL;
$contributionIdClause = NULL;
if (isset($contributionId) && !$isScriptUpdate) {
@@ -677,10 +688,7 @@ public static function updatePledgePayments(
{$paymentClause}
";
- // get all status
- $params = array(1 => array($pledgeId, 'Integer'));
-
- $dao = CRM_Core_DAO::executeQuery($query, $params);
+ CRM_Core_DAO::executeQuery($query, [1 => [$pledgeId, 'Integer']]);
}
/**
@@ -712,7 +720,9 @@ public static function updateReminderDetails($paymentId) {
*/
public static function getOldestPledgePayment($pledgeID, $limit = 1) {
// get pending / overdue statuses
- $pledgeStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
+ FALSE, FALSE, FALSE, NULL, 'name'
+ );
// get pending and overdue payments
$status[] = array_search('Pending', $pledgeStatuses);
@@ -730,20 +740,20 @@ public static function getOldestPledgePayment($pledgeID, $limit = 1) {
LIMIT 0, %2
";
- $params[1] = array($pledgeID, 'Integer');
- $params[2] = array($limit, 'Integer');
+ $params[1] = [$pledgeID, 'Integer'];
+ $params[2] = [$limit, 'Integer'];
$payment = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
- $paymentDetails = array();
+ $paymentDetails = [];
while ($payment->fetch()) {
- $paymentDetails[] = array(
+ $paymentDetails[] = [
'id' => $payment->id,
'amount' => $payment->amount,
'currency' => $payment->currency,
'schedule_date' => $payment->scheduled_date,
'financial_type_id' => $payment->financial_type_id,
'count' => $count,
- );
+ ];
$count++;
}
return end($paymentDetails);
@@ -759,14 +769,15 @@ public static function getOldestPledgePayment($pledgeID, $limit = 1) {
*/
public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId = NULL, $pPaymentId = NULL, $paymentStatusID = NULL) {
$allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
- if ($paymentStatusID == array_search('Cancelled', $allStatus) || $paymentStatusID == array_search('Refunded', $allStatus)) {
+ $paymentStatusName = CRM_Core_PseudoConstant::getName('CRM_Pledge_BAO_PledgePayment', 'status_id', $paymentStatusID);
+ if ($paymentStatusName == 'Cancelled'|| $paymentStatusName == 'Refunded') {
$query = "
SELECT civicrm_pledge_payment.id id
FROM civicrm_pledge_payment
WHERE civicrm_pledge_payment.contribution_id = {$paymentContributionId}
";
$paymentsAffected = CRM_Core_DAO::executeQuery($query);
- $paymentIDs = array();
+ $paymentIDs = [];
while ($paymentsAffected->fetch()) {
$paymentIDs[] = $paymentsAffected->id;
}
@@ -802,56 +813,55 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
$date['day'] = (int) substr($scheduled_date, 6, 2);
$newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit, $pledgeFrequencyInterval, $newDate));
- $pledgeParams = array(
+ $pledgeParams = [
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => $pledgeScheduledAmount,
'scheduled_date' => $ScheduledDate,
- );
+ ];
$payment = self::add($pledgeParams);
}
else {
- $oldestPayment = self::getOldestPledgePayment($pledgeID);
+ $nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID);
if (!$paymentContributionId) {
// means we are editing payment scheduled payment, so get the second pending to update.
- $oldestPayment = self::getOldestPledgePayment($pledgeID, 2);
- if (($oldestPayment['count'] != 1) && ($oldestPayment['id'] == $pPaymentId)) {
- $oldestPayment = self::getOldestPledgePayment($pledgeID);
+ $nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID, 2);
+ if (($nextPledgeInstallmentDue['count'] != 1) && ($nextPledgeInstallmentDue['id'] == $pPaymentId)) {
+ $nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID);
}
}
- if ($oldestPayment) {
+ if ($nextPledgeInstallmentDue) {
// not the last scheduled payment and the actual amount is less than the expected , add it to oldest pending.
- if (($actualAmount != $pledgeScheduledAmount) && (($actualAmount < $pledgeScheduledAmount) || (($actualAmount - $pledgeScheduledAmount) < $oldestPayment['amount']))) {
- $oldScheduledAmount = $oldestPayment['amount'];
+ if (($actualAmount != $pledgeScheduledAmount) && (($actualAmount < $pledgeScheduledAmount) || (($actualAmount - $pledgeScheduledAmount) < $nextPledgeInstallmentDue['amount']))) {
+ $oldScheduledAmount = $nextPledgeInstallmentDue['amount'];
$newScheduledAmount = $oldScheduledAmount + ($pledgeScheduledAmount - $actualAmount);
// store new amount in oldest pending payment record.
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment',
- $oldestPayment['id'],
+ $nextPledgeInstallmentDue['id'],
'scheduled_amount',
$newScheduledAmount
);
- if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'contribution_id', 'id')) {
+ if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $nextPledgeInstallmentDue['id'], 'contribution_id', 'id')) {
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment',
- $oldestPayment['id'],
+ $nextPledgeInstallmentDue['id'],
'contribution_id',
$paymentContributionId
);
}
}
- elseif (($actualAmount > $pledgeScheduledAmount) && (($actualAmount - $pledgeScheduledAmount) >= $oldestPayment['amount'])) {
+ elseif (($actualAmount > $pledgeScheduledAmount) && (($actualAmount - $pledgeScheduledAmount) >= $nextPledgeInstallmentDue['amount'])) {
// here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
// set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
- $paymentId = array($oldestPayment['id']);
+ $paymentId = [$nextPledgeInstallmentDue['id']];
self::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
- CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'scheduled_amount', 0, 'id');
- $oldestPayment = self::getOldestPledgePayment($pledgeID);
+ CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $nextPledgeInstallmentDue['id'], 'scheduled_amount', 0, 'id');
if (!$paymentContributionId) {
// means we are editing payment scheduled payment.
$oldestPaymentAmount = self::getOldestPledgePayment($pledgeID, 2);
}
- $newActualAmount = ($actualAmount - $pledgeScheduledAmount);
- $newPledgeScheduledAmount = $oldestPayment['amount'];
+ $newActualAmount = round(($actualAmount - $pledgeScheduledAmount), CRM_Utils_Money::getCurrencyPrecision());
+ $newPledgeScheduledAmount = $nextPledgeInstallmentDue['amount'];
if (!$paymentContributionId) {
$newActualAmount = ($actualAmount - $pledgeScheduledAmount);
$newPledgeScheduledAmount = $oldestPaymentAmount['amount'];
@@ -881,10 +891,11 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
$result = parent::buildOptions($fieldName, $context, $props);
if ($fieldName == 'status_id') {
- $result = array_diff($result, array('Failed', 'In Progress'));
+ $result = CRM_Pledge_BAO_Pledge::buildOptions($fieldName, $context, $props);
+ $result = array_diff($result, ['Failed', 'In Progress']);
}
return $result;
}
diff --git a/CRM/Pledge/BAO/Query.php b/CRM/Pledge/BAO/Query.php
index 5b9f344b9013..1859eb7e06f3 100644
--- a/CRM/Pledge/BAO/Query.php
+++ b/CRM/Pledge/BAO/Query.php
@@ -1,9 +1,9 @@
_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
+ if (!empty($query->_returnProperties['pledge_original_installment_amount'])) {
+ $query->_select['pledge_original_installment_amount'] = 'civicrm_pledge.original_installment_amount as pledge_original_installment_amount';
+ $query->_element['pledge_original_installment_amount'] = 1;
+ $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
+ }
+
+ if (!empty($query->_returnProperties['installments'])) {
+ $query->_select['installments'] = 'civicrm_pledge.installments as installments';
+ $query->_element['installments'] = 1;
+ $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
+ }
+
if (!empty($query->_returnProperties['pledge_create_date'])) {
$query->_select['pledge_create_date'] = 'civicrm_pledge.create_date as pledge_create_date';
$query->_element['pledge_create_date'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
+ if (!empty($query->_returnProperties['pledge_end_date'])) {
+ $query->_select['pledge_end_date'] = 'civicrm_pledge.end_date as pledge_end_date';
+ $query->_element['pledge_end_date'] = 1;
+ $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
+ }
+
if (!empty($query->_returnProperties['pledge_start_date'])) {
$query->_select['pledge_start_date'] = 'civicrm_pledge.start_date as pledge_start_date';
$query->_element['pledge_start_date'] = 1;
@@ -216,7 +235,7 @@ public static function where(&$query) {
continue;
}
if (substr($query->_params[$id][0], 0, 7) == 'pledge_') {
- if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
+ if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$grouping = $query->_params[$id][3];
@@ -226,43 +245,24 @@ public static function where(&$query) {
}
/**
- * @param $values
- * @param $query
+ * Get where clause for field.
+ *
+ * @todo most of this could be replaced by using metadata.
+ *
+ * @param array $values
+ * @param \CRM_Contact_BAO_Query $query
+ *
+ * @throws \CRM_Core_Exception
*/
public static function whereClauseSingle(&$values, &$query) {
+ if ($query->buildDateRangeQuery($values)) {
+ // @todo - move this to Contact_Query in or near the call to
+ // $this->buildRelativeDateQuery($values);
+ return;
+ }
list($name, $op, $value, $grouping, $wildcard) = $values;
switch ($name) {
- case 'pledge_create_date_low':
- case 'pledge_create_date_high':
- // process to / from date
- $query->dateQueryBuilder($values,
- 'civicrm_pledge', 'pledge_create_date', 'create_date', 'Pledge Made'
- );
- case 'pledge_start_date_low':
- case 'pledge_start_date_high':
- // process to / from date
- $query->dateQueryBuilder($values,
- 'civicrm_pledge', 'pledge_start_date', 'start_date', 'Pledge Start Date'
- );
- return;
-
- case 'pledge_end_date_low':
- case 'pledge_end_date_high':
- // process to / from date
- $query->dateQueryBuilder($values,
- 'civicrm_pledge', 'pledge_end_date', 'end_date', 'Pledge End Date'
- );
- return;
-
- case 'pledge_payment_date_low':
- case 'pledge_payment_date_high':
- // process to / from date
- $query->dateQueryBuilder($values,
- 'civicrm_pledge_payment', 'pledge_payment_date', 'scheduled_date', 'Payment Scheduled'
- );
- return;
-
case 'pledge_amount':
case 'pledge_amount_low':
case 'pledge_amount_high':
@@ -298,15 +298,19 @@ public static function whereClauseSingle(&$values, &$query) {
$tableName = 'civicrm_pledge';
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
$label = "Pledge Status";
+ $qillDAO = 'CRM_Pledge_DAO_Pledge';
+ $qillField = 'status_id';
}
else {
$tableName = 'civicrm_pledge_payment';
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
$label = "Pledge Payment Status";
+ $qillDAO = 'CRM_Contribute_DAO_Contribution';
+ $qillField = 'contribution_status_id';
}
$name = 'status_id';
if (!empty($value) && is_array($value) && !in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
- $value = array('IN' => $value);
+ $value = ['IN' => $value];
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name",
@@ -314,8 +318,8 @@ public static function whereClauseSingle(&$values, &$query) {
$value,
'Integer'
);
- list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contribute_DAO_Contribution', 'contribution_status_id', $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $qillop, 3 => $qillVal));
+ list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($qillDAO, $qillField, $value, $op);
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $label, 2 => $qillop, 3 => $qillVal]);
return;
case 'pledge_test':
@@ -341,7 +345,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value,
'Integer'
);
- $query->_qill[$grouping][] = ts('Financial Type - %1', array(1 => $type));
+ $query->_qill[$grouping][] = ts('Financial Type - %1', [1 => $type]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
@@ -352,7 +356,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value,
'Integer'
);
- $query->_qill[$grouping][] = ts('Financial Page - %1', array(1 => $page));
+ $query->_qill[$grouping][] = ts('Financial Page - %1', [1 => $page]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
@@ -381,7 +385,7 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_pledge.$name", $op, $value, 'Integer');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Pledge_DAO_Pledge', $name, $value, $op);
$label = ($name == 'campaign_id') ? 'Campaign' : 'Contact ID';
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
}
@@ -405,7 +409,7 @@ public static function from($name, $mode, $side) {
break;
case 'pledge_status':
- $from .= " $side JOIN civicrm_option_group option_group_pledge_status ON (option_group_pledge_status.name = 'contribution_status')";
+ $from .= " $side JOIN civicrm_option_group option_group_pledge_status ON (option_group_pledge_status.name = 'pledge_status')";
$from .= " $side JOIN civicrm_option_value pledge_status ON (civicrm_pledge.status_id = pledge_status.value AND option_group_pledge_status.id = pledge_status.option_group_id ) ";
break;
@@ -445,7 +449,7 @@ public static function defaultReturnProperties(
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -466,7 +470,7 @@ public static function defaultReturnProperties(
'pledge_frequency_unit' => 1,
'pledge_currency' => 1,
'pledge_campaign_id' => 1,
- );
+ ];
}
return $properties;
}
@@ -482,7 +486,7 @@ public static function extraReturnProperties($mode) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
- $properties = array(
+ $properties = [
'pledge_balance_amount' => 1,
'pledge_payment_id' => 1,
'pledge_payment_scheduled_amount' => 1,
@@ -493,7 +497,7 @@ public static function extraReturnProperties($mode) {
'pledge_payment_reminder_count' => 1,
'pledge_payment_status_id' => 1,
'pledge_payment_status' => 1,
- );
+ ];
// also get all the custom pledge properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Pledge');
@@ -507,73 +511,99 @@ public static function extraReturnProperties($mode) {
}
/**
- * @param CRM_Core_Form $form
+ * Get the metadata for fields to be included on the grant search form.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getSearchFieldMetadata() {
+ $fields = [
+ 'pledge_status_id',
+ 'pledge_start_date',
+ 'pledge_end_date',
+ 'pledge_create_date',
+ ];
+ $metadata = civicrm_api3('Pledge', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
+ /**
+ * Get the metadata for fields to be included on the grant search form.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getPledgePaymentSearchFieldMetadata() {
+ $fields = [
+ 'pledge_payment_scheduled_date',
+ ];
+ $metadata = civicrm_api3('PledgePayment', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
+ /**
+ * Build the search for for pledges.
+ *
+ * @param CRM_Pledge_Form_Search|\CRM_Contact_Form_Search_Advanced $form
+ *
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public static function buildSearchForm(&$form) {
// pledge related dates
- CRM_Core_Form_Date::buildDateRange($form, 'pledge_start_date', 1, '_low', '_high', ts('From'), FALSE);
- CRM_Core_Form_Date::buildDateRange($form, 'pledge_end_date', 1, '_low', '_high', ts('From'), FALSE);
- CRM_Core_Form_Date::buildDateRange($form, 'pledge_create_date', 1, '_low', '_high', ts('From'), FALSE);
-
- // pledge payment related dates
- CRM_Core_Form_Date::buildDateRange($form, 'pledge_payment_date', 1, '_low', '_high', ts('From'), FALSE);
+ $form->addSearchFieldMetadata(['Pledge' => self::getSearchFieldMetadata()]);
+ $form->addSearchFieldMetadata(['PledgePayment' => self::getPledgePaymentSearchFieldMetadata()]);
+ $form->addFormFieldsFromMetadata();
$form->addYesNo('pledge_test', ts('Pledge is a Test?'), TRUE);
- $form->add('text', 'pledge_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+ $form->add('text', 'pledge_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
- $form->add('text', 'pledge_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
-
- $form->add('select', 'pledge_status_id',
- ts('Pledge Status'), CRM_Pledge_BAO_Pledge::buildOptions('status_id'),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')
- );
+ $form->add('text', 'pledge_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
$form->addYesNo('pledge_acknowledge_date_is_not_null', ts('Acknowledgement sent?'), TRUE);
- $form->add('text', 'pledge_installments_low', ts('From'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_installments_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_installments_low', ts('Please enter a number'), 'integer');
- $form->add('text', 'pledge_installments_high', ts('To'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_installments_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_installments_high', ts('Please enter number.'), 'integer');
$form->add('select', 'pledge_payment_status_id',
ts('Pledge Payment Status'), CRM_Pledge_BAO_PledgePayment::buildOptions('status_id'),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
);
$form->add('select', 'pledge_financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
- FALSE, array('class' => 'crm-select2')
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType(),
+ FALSE, ['class' => 'crm-select2']
);
$form->add('select', 'pledge_contribution_page_id',
ts('Contribution Page'),
- array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::contributionPage(),
- FALSE, array('class' => 'crm-select2')
+ ['' => ts('- any -')] + CRM_Contribute_PseudoConstant::contributionPage(),
+ FALSE, ['class' => 'crm-select2']
);
// add fields for pledge frequency
- $form->add('text', 'pledge_frequency_interval', ts('Every'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_frequency_interval', ts('Every'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_frequency_interval', ts('Please enter valid Pledge Frequency Interval'), 'integer');
$frequencies = CRM_Core_OptionGroup::values('recur_frequency_units');
foreach ($frequencies as $val => $label) {
- $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', array(1 => $label));
+ $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', [1 => $label]);
}
$form->add('select', 'pledge_frequency_unit',
ts('Pledge Frequency'),
- array('' => ts('- any -')) + $freqUnitsDisplay
+ ['' => ts('- any -')] + $freqUnitsDisplay
);
- self::addCustomFormFields($form, array('Pledge'));
+ self::addCustomFormFields($form, ['Pledge']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id');
$form->assign('validCiviPledge', TRUE);
- $form->setDefaults(array('pledge_test' => 0));
+ $form->setDefaults(['pledge_test' => 0]);
}
/**
@@ -582,7 +612,7 @@ public static function buildSearchForm(&$form) {
public static function tableNames(&$tables) {
// add status table
if (!empty($tables['pledge_status']) || !empty($tables['civicrm_pledge_payment'])) {
- $tables = array_merge(array('civicrm_pledge' => 1), $tables);
+ $tables = array_merge(['civicrm_pledge' => 1], $tables);
}
}
diff --git a/CRM/Pledge/Controller/Search.php b/CRM/Pledge/Controller/Search.php
index c7c6a582a190..f95d94db590c 100644
--- a/CRM/Pledge/Controller/Search.php
+++ b/CRM/Pledge/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_pledge';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_page_id', 'civicrm_contribution_page', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_page_id', 'civicrm_contribution_page', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pledge_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pledge_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge ID') ,
- 'description' => 'Pledge ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Pledge ID'),
+ 'description' => ts('Pledge ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- ) ,
- 'pledge_contact_id' => array(
+ ],
+ 'pledge_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Foreign key to civicrm_contact.id .',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Foreign key to civicrm_contact.id .'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'pledge_financial_type_id' => array(
+ ],
+ ],
+ 'pledge_financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Type') ,
- 'description' => 'FK to Financial Type',
+ 'title' => ts('Type'),
+ 'description' => ts('FK to Financial Type'),
+ 'where' => 'civicrm_pledge.financial_type_id',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'pledge_contribution_page_id' => array(
+ ],
+ ],
+ 'pledge_contribution_page_id' => [
'name' => 'contribution_page_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Contribution Page') ,
- 'description' => 'The Contribution Page which triggered this contribution',
+ 'title' => ts('Pledge Contribution Page'),
+ 'description' => ts('The Contribution Page which triggered this contribution'),
+ 'where' => 'civicrm_pledge.contribution_page_id',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
- ) ,
- 'pledge_amount' => array(
+ ],
+ 'pledge_amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Total Pledged') ,
- 'description' => 'Total pledged amount.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Total Pledged'),
+ 'description' => ts('Total pledged amount.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge.amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pledge_original_installment_amount' => array(
+ ],
+ ],
+ 'pledge_original_installment_amount' => [
'name' => 'original_installment_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Original Installment Amount') ,
- 'description' => 'Original amount for each of the installments.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Original Installment Amount'),
+ 'description' => ts('Original amount for each of the installments.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_pledge.original_installment_amount',
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Pledge Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pledge.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_frequency_unit' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'pledge_frequency_unit' => [
'name' => 'frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Frequency Unit') ,
- 'description' => 'Time units for recurrence of pledge payments.',
+ 'title' => ts('Pledge Frequency Unit'),
+ 'description' => ts('Time units for recurrence of pledge payments.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_pledge.frequency_unit',
'default' => 'month',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'recur_frequency_units',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/recur_frequency_units',
- )
- ) ,
- 'pledge_frequency_interval' => array(
+ ],
+ ],
+ 'pledge_frequency_interval' => [
'name' => 'frequency_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Frequency Interval') ,
- 'description' => 'Number of time units for recurrence of pledge payments.',
- 'required' => true,
+ 'title' => ts('Pledge Frequency Interval'),
+ 'description' => ts('Number of time units for recurrence of pledge payments.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.frequency_interval',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'frequency_day' => array(
+ ],
+ ],
+ 'frequency_day' => [
'name' => 'frequency_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge day') ,
- 'description' => 'Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.',
- 'required' => true,
+ 'title' => ts('Pledge day'),
+ 'description' => ts('Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.frequency_day',
'default' => '3',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'installments' => array(
+ ],
+ ],
+ 'installments' => [
'name' => 'installments',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Number of Installments') ,
- 'description' => 'Total number of payments to be made.',
+ 'title' => ts('Pledge Number of Installments'),
+ 'description' => ts('Total number of payments to be made.'),
+ 'where' => 'civicrm_pledge.installments',
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'start_date' => array(
+ ],
+ ],
+ 'pledge_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Start Date') ,
- 'description' => 'The date the first scheduled pledge occurs.',
- 'required' => true,
+ 'title' => ts('Pledge Start Date'),
+ 'description' => ts('The date the first scheduled pledge occurs.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.start_date',
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'unique_title' => ts('Payments Start Date'),
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'pledge_create_date' => array(
+ ],
+ ],
+ 'pledge_create_date' => [
'name' => 'create_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Made') ,
- 'description' => 'When this pledge record was created.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Pledge Made'),
+ 'description' => ts('When this pledge record was created.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.create_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'acknowledge_date' => array(
+ ],
+ ],
+ 'acknowledge_date' => [
'name' => 'acknowledge_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Acknowledged') ,
- 'description' => 'When a pledge acknowledgement message was sent to the contributor.',
+ 'title' => ts('Pledge Acknowledged'),
+ 'description' => ts('When a pledge acknowledgement message was sent to the contributor.'),
+ 'where' => 'civicrm_pledge.acknowledge_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'modified_date' => array(
+ ],
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Modified Date') ,
- 'description' => 'Last updated date for this pledge record.',
+ 'title' => ts('Pledge Modified Date'),
+ 'description' => ts('Last updated date for this pledge record.'),
+ 'where' => 'civicrm_pledge.modified_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- ) ,
- 'cancel_date' => array(
+ ],
+ 'cancel_date' => [
'name' => 'cancel_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Cancelled Date') ,
- 'description' => 'Date this pledge was cancelled by contributor.',
+ 'title' => ts('Pledge Cancelled Date'),
+ 'description' => ts('Date this pledge was cancelled by contributor.'),
+ 'where' => 'civicrm_pledge.cancel_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'end_date' => array(
+ ],
+ ],
+ 'pledge_end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge End Date') ,
- 'description' => 'Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).',
+ 'title' => ts('Pledge End Date'),
+ 'description' => ts('Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).'),
+ 'where' => 'civicrm_pledge.end_date',
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'unique_title' => ts('Payments Ended Date'),
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'max_reminders' => array(
+ ],
+ ],
+ 'max_reminders' => [
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Number of Reminders') ,
- 'description' => 'The maximum number of payment reminders to send for any given payment.',
+ 'title' => ts('Maximum Number of Reminders'),
+ 'description' => ts('The maximum number of payment reminders to send for any given payment.'),
+ 'where' => 'civicrm_pledge.max_reminders',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'initial_reminder_day' => array(
+ ],
+ ],
+ 'initial_reminder_day' => [
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Initial Reminder Day') ,
- 'description' => 'Send initial reminder this many days prior to the payment due date.',
+ 'title' => ts('Initial Reminder Day'),
+ 'description' => ts('Send initial reminder this many days prior to the payment due date.'),
+ 'where' => 'civicrm_pledge.initial_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'additional_reminder_day' => array(
+ ],
+ ],
+ 'additional_reminder_day' => [
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Additional Reminder Days') ,
- 'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
+ 'title' => ts('Additional Reminder Days'),
+ 'description' => ts('Send additional reminder this many days after last one sent, up to maximum number of reminders.'),
+ 'where' => 'civicrm_pledge.additional_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pledge_status_id' => array(
+ ],
+ ],
+ 'pledge_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Status Id') ,
- 'description' => 'Implicit foreign key to civicrm_option_values in the contribution_status option group.',
- 'import' => true,
+ 'title' => ts('Pledge Status Id'),
+ 'description' => ts('Implicit foreign key to civicrm_option_values in the pledge_status option group.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'pseudoconstant' => array(
- 'optionGroupName' => 'contribution_status',
- 'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- 'pledge_is_test' => array(
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
+ 'optionGroupName' => 'pledge_status',
+ 'optionEditPath' => 'civicrm/admin/options/pledge_status',
+ ],
+ ],
+ 'pledge_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.is_test',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'pledge_campaign_id' => array(
+ ],
+ ],
+ 'pledge_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this pledge has been initiated.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this pledge has been initiated.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -637,10 +656,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -648,24 +668,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_status' => array(
+ $indices = [
+ 'index_status' => [
'name' => 'index_status',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/DAO/PledgeBlock.php b/CRM/Pledge/DAO/PledgeBlock.php
index a8b3fa840587..d261ba53dc97 100644
--- a/CRM/Pledge/DAO/PledgeBlock.php
+++ b/CRM/Pledge/DAO/PledgeBlock.php
@@ -1,306 +1,316 @@
__table = 'civicrm_pledge_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Block ID') ,
- 'description' => 'Pledge ID',
- 'required' => true,
+ 'title' => ts('Pledge Block ID'),
+ 'description' => ts('Pledge ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.id',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'physical tablename for entity being joined to pledge, e.g. civicrm_contact',
+ 'title' => ts('Entity Table'),
+ 'description' => ts('physical tablename for entity being joined to pledge, e.g. civicrm_contact'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pledge_block.entity_table',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Id') ,
- 'description' => 'FK to entity table specified in entity_table column.',
- 'required' => true,
+ 'title' => ts('Entity Id'),
+ 'description' => ts('FK to entity table specified in entity_table column.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.entity_id',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'pledge_frequency_unit' => array(
+ ],
+ 'pledge_frequency_unit' => [
'name' => 'pledge_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Frequency Unit') ,
- 'description' => 'Delimited list of supported frequency units',
+ 'title' => ts('Pledge Frequency Unit'),
+ 'description' => ts('Delimited list of supported frequency units'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pledge_block.pledge_frequency_unit',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_interval' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ ],
+ 'is_pledge_interval' => [
'name' => 'is_pledge_interval',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Expose Frequency Interval?') ,
- 'description' => 'Is frequency interval exposed on the contribution form.',
+ 'title' => ts('Expose Frequency Interval?'),
+ 'description' => ts('Is frequency interval exposed on the contribution form.'),
+ 'where' => 'civicrm_pledge_block.is_pledge_interval',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'max_reminders' => array(
+ ],
+ 'max_reminders' => [
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Number of Reminders') ,
- 'description' => 'The maximum number of payment reminders to send for any given payment.',
+ 'title' => ts('Maximum Number of Reminders'),
+ 'description' => ts('The maximum number of payment reminders to send for any given payment.'),
+ 'where' => 'civicrm_pledge_block.max_reminders',
'default' => '1',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'initial_reminder_day' => array(
+ ],
+ 'initial_reminder_day' => [
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Initial Reminder Day') ,
- 'description' => 'Send initial reminder this many days prior to the payment due date.',
+ 'title' => ts('Initial Reminder Day'),
+ 'description' => ts('Send initial reminder this many days prior to the payment due date.'),
+ 'where' => 'civicrm_pledge_block.initial_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'additional_reminder_day' => array(
+ ],
+ 'additional_reminder_day' => [
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Additional Reminder Days') ,
- 'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
+ 'title' => ts('Additional Reminder Days'),
+ 'description' => ts('Send additional reminder this many days after last one sent, up to maximum number of reminders.'),
+ 'where' => 'civicrm_pledge_block.additional_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'pledge_start_date' => array(
+ ],
+ 'pledge_start_date' => [
'name' => 'pledge_start_date',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Start Date') ,
- 'description' => 'The date the first scheduled pledge occurs.',
+ 'title' => ts('Pledge Start Date'),
+ 'description' => ts('The date the first scheduled pledge occurs.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pledge_block.pledge_start_date',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_start_date_visible' => array(
+ ],
+ 'is_pledge_start_date_visible' => [
'name' => 'is_pledge_start_date_visible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Show Recurring Donation Start Date?') ,
- 'description' => 'If true - recurring start date is shown.',
- 'required' => true,
+ 'title' => ts('Show Recurring Donation Start Date?'),
+ 'description' => ts('If true - recurring start date is shown.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.is_pledge_start_date_visible',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_start_date_editable' => array(
+ ],
+ 'is_pledge_start_date_editable' => [
'name' => 'is_pledge_start_date_editable',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Edits to Recurring Donation Start Date?') ,
- 'description' => 'If true - recurring start date is editable.',
- 'required' => true,
+ 'title' => ts('Allow Edits to Recurring Donation Start Date?'),
+ 'description' => ts('If true - recurring start date is editable.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.is_pledge_start_date_editable',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -308,10 +318,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -319,25 +330,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity' => array(
+ $indices = [
+ 'index_entity' => [
'name' => 'index_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_block::0::entity_table::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/DAO/PledgePayment.php b/CRM/Pledge/DAO/PledgePayment.php
index c51fc033dfe7..879a6fa973d2 100644
--- a/CRM/Pledge/DAO/PledgePayment.php
+++ b/CRM/Pledge/DAO/PledgePayment.php
@@ -1,339 +1,327 @@
__table = 'civicrm_pledge_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'pledge_id', 'civicrm_pledge', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'pledge_id', 'civicrm_pledge', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pledge_payment_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pledge_payment_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment ID') ,
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Payment ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_id' => array(
+ ],
+ 'pledge_id' => [
'name' => 'pledge_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge') ,
- 'description' => 'FK to Pledge table',
- 'required' => true,
+ 'title' => ts('Pledge'),
+ 'description' => ts('FK to Pledge table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_payment.pledge_id',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Pledge_DAO_Pledge',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'where' => 'civicrm_pledge_payment.contribution_id',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- 'pledge_payment_scheduled_amount' => array(
+ ],
+ 'pledge_payment_scheduled_amount' => [
'name' => 'scheduled_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Scheduled Amount') ,
- 'description' => 'Pledged amount for this payment (the actual contribution amount might be different).',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Scheduled Amount'),
+ 'description' => ts('Pledged amount for this payment (the actual contribution amount might be different).'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.scheduled_amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_actual_amount' => array(
+ ],
+ 'pledge_payment_actual_amount' => [
'name' => 'actual_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Actual Amount') ,
- 'description' => 'Actual amount that is paid as the Pledged installment amount.',
- 'precision' => array(
+ 'title' => ts('Actual Amount'),
+ 'description' => ts('Actual amount that is paid as the Pledged installment amount.'),
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.actual_amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pledge_payment.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_payment_scheduled_date' => array(
+ 'abbrColumn' => 'symbol',
+ ],
+ ],
+ 'pledge_payment_scheduled_date' => [
'name' => 'scheduled_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Scheduled Date') ,
- 'description' => 'The date the pledge payment is supposed to happen.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Scheduled Date'),
+ 'description' => ts('The date the pledge payment is supposed to happen.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.scheduled_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_reminder_date' => array(
+ 'unique_title' => ts('Payment Scheduled'),
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'pledge_payment_reminder_date' => [
'name' => 'reminder_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Last Reminder') ,
- 'description' => 'The date that the most recent payment reminder was sent.',
- 'import' => true,
+ 'title' => ts('Last Reminder'),
+ 'description' => ts('The date that the most recent payment reminder was sent.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.reminder_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_reminder_count' => array(
+ ],
+ 'pledge_payment_reminder_count' => [
'name' => 'reminder_count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Reminders Sent') ,
- 'description' => 'The number of payment reminders sent.',
- 'import' => true,
+ 'title' => ts('Reminders Sent'),
+ 'description' => ts('The number of payment reminders sent.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.reminder_count',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_status_id' => array(
+ ],
+ 'pledge_payment_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Status') ,
- 'import' => true,
+ 'title' => ts('Payment Status'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -341,10 +329,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -352,33 +341,39 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_contribution_pledge' => array(
+ $indices = [
+ 'index_contribution_pledge' => [
'name' => 'index_contribution_pledge',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'pledge_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_payment::0::contribution_id::pledge_id',
- ) ,
- 'index_status' => array(
+ ],
+ 'index_status' => [
'name' => 'index_status',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_payment::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/Form/Payment.php b/CRM/Pledge/Form/Payment.php
index 71038395ec57..ea24635c075b 100644
--- a/CRM/Pledge/Form/Payment.php
+++ b/CRM/Pledge/Form/Payment.php
@@ -1,9 +1,9 @@
_id) {
$params['id'] = $this->_id;
CRM_Pledge_BAO_PledgePayment::retrieve($params, $defaults);
- list($defaults['scheduled_date']) = CRM_Utils_Date::setDateDefaults($defaults['scheduled_date']);
if (isset($defaults['contribution_id'])) {
$this->assign('pledgePayment', TRUE);
}
@@ -82,69 +95,63 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
// add various dates
- $this->addDate('scheduled_date', ts('Scheduled Date'), TRUE);
+ $this->addField('scheduled_date', [], TRUE, FALSE);
$this->addMoney('scheduled_amount',
ts('Scheduled Amount'), TRUE,
- array('readonly' => TRUE),
+ ['readonly' => TRUE],
TRUE,
'currency',
NULL,
TRUE
);
- $optionTypes = array(
+ $optionTypes = [
'1' => ts('Adjust Pledge Payment Schedule?'),
'2' => ts('Adjust Total Pledge Amount?'),
- );
+ ];
$element = $this->addRadio('option_type',
NULL,
$optionTypes,
- array(), '
'
+ [], '
'
);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
/**
* Process the form submission.
*/
public function postProcess() {
- // get the submitted form values.
$formValues = $this->controller->exportValues($this->_name);
- $params = array();
- $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
- $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
- $params['currency'] = CRM_Utils_Array::value('currency', $formValues);
- $now = date('Ymd');
+ $params = [
+ 'id' => $this->_id,
+ 'scheduled_date' => $formValues['scheduled_date'],
+ 'currency' => $formValues['currency'],
+ ];
- if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
+ if (CRM_Utils_Date::overdue($params['scheduled_date'])) {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Overdue');
}
else {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
}
- $params['id'] = $this->_id;
$pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id');
CRM_Pledge_BAO_PledgePayment::add($params);
- $adjustTotalAmount = FALSE;
- if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
- $adjustTotalAmount = TRUE;
- }
+ $adjustTotalAmount = (CRM_Utils_Array::value('option_type', $formValues) == 2);
$pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$params['id'],
@@ -161,7 +168,7 @@ public function postProcess() {
}
// update pledge status
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
- array($params['id']),
+ [$params['id']],
$params['status_id'],
NULL,
$formValues['scheduled_amount'],
diff --git a/CRM/Pledge/Form/Pledge.php b/CRM/Pledge/Form/Pledge.php
index dad93c060d89..3e80eb7615da 100644
--- a/CRM/Pledge/Form/Pledge.php
+++ b/CRM/Pledge/Form/Pledge.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
// check for action permissions.
if (!CRM_Core_Permission::checkActionPermission('CiviPledge', $this->_action)) {
@@ -93,21 +96,20 @@ public function preProcess() {
list($this->userDisplayName,
$this->userEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
- $this->assign('displayName', $this->userDisplayName);
}
$this->setPageTitle(ts('Pledge'));
// build custom data
CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id);
- $this->_values = array();
+ $this->_values = [];
// current pledge id
if ($this->_id) {
// get the contribution id
$this->_contributionID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$this->_id, 'contribution_id', 'pledge_id'
);
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Pledge_BAO_Pledge::getValues($params, $this->_values);
$this->_isPending = (CRM_Pledge_BAO_Pledge::pledgeHasFinancialTransactions($this->_id, CRM_Utils_Array::value('status_id', $this->_values))) ? FALSE : TRUE;
@@ -119,7 +121,6 @@ public function preProcess() {
$this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
}
-
/**
* Set default values for the form.
* The default values are retrieved from the database.
@@ -127,7 +128,6 @@ public function preProcess() {
public function setDefaultValues() {
$defaults = $this->_values;
- $fields = array();
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
@@ -137,25 +137,13 @@ public function setDefaultValues() {
}
if ($this->_id) {
- $startDate = CRM_Utils_Array::value('start_date', $this->_values);
- $createDate = CRM_Utils_Array::value('create_date', $this->_values);
- list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($startDate);
- list($defaults['create_date']) = CRM_Utils_Date::setDateDefaults($createDate);
-
- if ($ackDate = CRM_Utils_Array::value('acknowledge_date', $this->_values)) {
- list($defaults['acknowledge_date']) = CRM_Utils_Date::setDateDefaults($ackDate);
- }
-
// check is this pledge pending.
// fix the display of the monetary value, CRM-4038.
if ($this->_isPending) {
$defaults['eachPaymentAmount'] = $this->_values['amount'] / $this->_values['installments'];
$defaults['eachPaymentAmount'] = CRM_Utils_Money::format($defaults['eachPaymentAmount'], NULL, '%a');
}
- else {
- $this->assign('start_date', $startDate);
- $this->assign('create_date', $createDate);
- }
+
// fix the display of the monetary value, CRM-4038
if (isset($this->_values['amount'])) {
$defaults['amount'] = CRM_Utils_Money::format($this->_values['amount'], NULL, '%a');
@@ -164,10 +152,12 @@ public function setDefaultValues() {
$this->assign('installments', $defaults['installments']);
}
else {
+ if ($this->_contactID) {
+ $defaults['contact_id'] = $this->_contactID;
+ }
// default values.
- list($now) = CRM_Utils_Date::setDateDefaults();
- $defaults['create_date'] = $now;
- $defaults['start_date'] = $now;
+ $defaults['create_date'] = date('Y-m-d');
+ $defaults['start_date'] = date('Y-m-d');
$defaults['installments'] = 12;
$defaults['frequency_interval'] = 1;
$defaults['frequency_day'] = 1;
@@ -179,7 +169,7 @@ public function setDefaultValues() {
}
$pledgeStatus = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
- $pledgeStatusNames = CRM_Core_OptionGroup::values('contribution_status',
+ $pledgeStatusNames = CRM_Core_OptionGroup::values('pledge_status',
FALSE, FALSE, FALSE, NULL, 'name', TRUE
);
// get default status label (pending)
@@ -208,44 +198,41 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
return;
}
- if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Contact'), array(
- 'create' => TRUE,
- 'api' => array('extra' => array('email')),
- ), TRUE);
+ $contactField = $this->addEntityRef('contact_id', ts('Contact'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
+ if ($this->_context != 'standalone') {
+ $contactField->freeze();
}
$showAdditionalInfo = FALSE;
$this->_formType = CRM_Utils_Array::value('formType', $_GET);
- $defaults = array();
+ $defaults = [];
- $paneNames = array(
+ $paneNames = [
'Payment Reminders' => 'PaymentReminders',
- );
+ ];
foreach ($paneNames as $name => $type) {
$urlParams = "snippet=4&formType={$type}";
- $allPanes[$name] = array(
+ $allPanes[$name] = [
'url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams),
'open' => 'false',
'id' => $type,
- );
+ ];
// see if we need to include this paneName in the current form
if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
CRM_Utils_Array::value("hidden_{$type}", $defaults)
@@ -272,85 +259,50 @@ public function buildQuickForm() {
$this->assign('isPending', $this->_isPending);
- $js = array(
+ $js = [
'onblur' => "calculatedPaymentAmount( );",
'onkeyup' => "calculatedPaymentAmount( );",
- );
+ ];
- $currencyFreeze = FALSE;
- if ($this->_id &&
- !$this->_isPending
- ) {
- $currencyFreeze = TRUE;
- }
-
- $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
+ $amount = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
array_merge($attributes['pledge_amount'], $js), TRUE,
- 'currency', NULL, $currencyFreeze
+ 'currency', NULL, $this->_id && !$this->_isPending
);
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
-
- $element = &$this->add('text', 'installments', ts('To be paid in'),
+ $installments = &$this->add('text', 'installments', ts('To be paid in'),
array_merge($attributes['installments'], $js), TRUE
);
$this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
- $element = &$this->add('text', 'frequency_interval', ts('every'),
+ $frequencyInterval = $this->add('number', 'frequency_interval', ts('every'),
$attributes['pledge_frequency_interval'], TRUE
);
$this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
// Fix frequency unit display for use with frequency_interval
- $freqUnitsDisplay = array();
+ $freqUnitsDisplay = [];
foreach ($this->_freqUnits as $val => $label) {
- $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
+ $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
}
- $element = &$this->add('select', 'frequency_unit',
+ $frequencyUnit = $this->add('select', 'frequency_unit',
ts('Frequency'),
- array('' => ts('- select -')) + $freqUnitsDisplay,
+ ['' => ts('- select -')] + $freqUnitsDisplay,
TRUE
);
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
-
- $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
+ $frequencyDay = $this->add('number', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
$this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
- $this->add('text', 'eachPaymentAmount', ts('each'), array(
- 'size' => 10,
- 'style' => "background-color:#EBECE4",
- 0 => 'READONLY', // WTF, preserved because its inexplicable
- ));
+ $this->add('text', 'eachPaymentAmount', ts('each'), [
+ 'size' => 10,
+ 'style' => "background-color:#EBECE4",
+ // WTF, preserved because its inexplicable
+ 0 => 'READONLY',
+ ]);
// add various dates
- if (!$this->_id || $this->_isPending) {
- $this->addDate('create_date', ts('Pledge Made'), TRUE);
- $this->addDate('start_date', ts('Payments Start'), TRUE);
- }
+ $createDate = $this->add('datepicker', 'create_date', ts('Pledge Made'), [], TRUE, ['time' => FALSE]);
+ $startDate = $this->add('datepicker', 'start_date', ts('Payments Start'), [], TRUE, ['time' => FALSE]);
if (!empty($this->_values['currency'])) {
$this->assign('currency', $this->_values['currency']);
@@ -359,12 +311,16 @@ public function buildQuickForm() {
$this->assign('currency', $this->_submitValues['currency']);
}
- if ($this->_id &&
- !$this->_isPending
- ) {
+ if ($this->_id && !$this->_isPending) {
+ $amount->freeze();
+ $installments->freeze();
+ $createDate->freeze();
+ $startDate->freeze();
+ $frequencyInterval->freeze();
+ $frequencyUnit->freeze();
+ $frequencyDay->freeze();
$eachPaymentAmount = $this->_values['original_installment_amount'];
$this->assign('eachPaymentAmount', $eachPaymentAmount);
- $this->assign('hideCalender', TRUE);
}
if (CRM_Utils_Array::value('status_id', $this->_values) !=
@@ -372,34 +328,34 @@ public function buildQuickForm() {
) {
$this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
- array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
+ ['onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
}
- $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
+ $this->add('datepicker', 'acknowledge_date', ts('Acknowledgment Date'), [], FALSE, ['time' => FALSE]);
$this->add('select', 'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType(),
TRUE
);
// CRM-7362 --add campaigns.
CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
- $pageIds = array();
+ $pageIds = [];
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
- 'civicrm_contribution_page', $pageIds, array('entity_id')
+ 'civicrm_contribution_page', $pageIds, ['entity_id']
);
$pages = CRM_Contribute_PseudoConstant::contributionPage();
- $pledgePages = array();
+ $pledgePages = [];
foreach ($pageIds as $key => $value) {
$pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
}
- $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
- array('' => ts('- select -')) + $pledgePages
+ $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
+ ['' => ts('- select -')] + $pledgePages
);
$mailingInfo = Civi::settings()->get('mailing_backend');
@@ -410,27 +366,26 @@ public function buildQuickForm() {
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc $uploadNames = $this->get( 'uploadNames' );
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
- 'js' => array('onclick' => "return verify( );"),
+ 'js' => ['onclick' => "return verify( );"],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
- 'js' => array('onclick' => "return verify( );"),
+ 'js' => ['onclick' => "return verify( );"],
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
- $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
+ $this->addFormRule(['CRM_Pledge_Form_Pledge', 'formRule'], $this);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
@@ -451,7 +406,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($fields['amount'] <= 0) {
$errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
@@ -492,7 +447,7 @@ public function postProcess() {
$session = CRM_Core_Session::singleton();
- $fields = array(
+ $fields = [
'frequency_unit',
'frequency_interval',
'frequency_day',
@@ -503,7 +458,7 @@ public function postProcess() {
'additional_reminder_day',
'contribution_page_id',
'campaign_id',
- );
+ ];
foreach ($fields as $f) {
$params[$f] = CRM_Utils_Array::value($f, $formValues);
}
@@ -513,7 +468,7 @@ public function postProcess() {
$params['currency'] = CRM_Utils_Array::value('currency', $formValues);
$params['original_installment_amount'] = ($params['amount'] / $params['installments']);
- $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
+ $dates = ['create_date', 'start_date', 'acknowledge_date', 'cancel_date'];
foreach ($dates as $d) {
if ($this->_id && (!$this->_isPending) && !empty($this->_values[$d])) {
if ($d == 'start_date') {
@@ -590,13 +545,7 @@ public function postProcess() {
// send Acknowledgment mail.
CRM_Pledge_BAO_Pledge::sendAcknowledgment($this, $params);
- if (!isset($this->userEmail)) {
- list($this->userDisplayName,
- $this->userEmail
- ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
- }
-
- $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.
", array(1 => $this->userEmail));
+ $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.
", [1 => $this->userEmail]);
// build the payment urls.
if ($this->paymentId) {
@@ -610,13 +559,13 @@ public function postProcess() {
"billing_mode IN ( 1, 3 )"
);
if (count($processors) > 0) {
- $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge OR submit a credit card payment.", array(
- 1 => $contribURL,
- 2 => $creditURL,
- ));
+ $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge OR submit a credit card payment.", [
+ 1 => $contribURL,
+ 2 => $creditURL,
+ ]);
}
else {
- $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge.", array(1 => $contribURL));
+ $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge.", [1 => $contribURL]);
}
}
}
diff --git a/CRM/Pledge/Form/PledgeView.php b/CRM/Pledge/Form/PledgeView.php
index c9540c89ad0a..0509c6bd407b 100644
--- a/CRM/Pledge/Form/PledgeView.php
+++ b/CRM/Pledge/Form/PledgeView.php
@@ -1,9 +1,9 @@
$this->get('id'));
+ $values = $ids = [];
+ $params = ['id' => $this->get('id')];
CRM_Pledge_BAO_Pledge::getValues($params,
$values,
$ids
);
- $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));
+ $values['frequencyUnit'] = ts('%1(s)', [1 => $values['frequency_unit']]);
if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
$sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
@@ -63,7 +63,7 @@ public function preProcess() {
}
// handle custom data.
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']);
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $params['id']);
if (!empty($values['contribution_page_id'])) {
@@ -80,7 +80,7 @@ public function preProcess() {
"action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -129,15 +129,14 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Search.php b/CRM/Pledge/Form/Search.php
index e0e23cfa0618..1f735e48af4f 100644
--- a/CRM/Pledge/Form/Search.php
+++ b/CRM/Pledge/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
-
- // we allow the controller to set force/reset externally, useful when we are being
- // driven by the wizard framework
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -99,6 +98,10 @@ public function preProcess() {
}
if ($this->_force) {
+ // pledge related dates
+ $this->addSearchFieldMetadata(['Pledge' => CRM_Pledge_BAO_Query::getSearchFieldMetadata()]);
+ $this->addSearchFieldMetadata(['PledgePayment' => CRM_Pledge_BAO_Query::getPledgePaymentSearchFieldMetadata()]);
+ $this->addFormFieldsFromMetadata();
$this->postProcess();
$this->set('force', 0);
}
@@ -145,7 +148,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Pledge_BAO_Query::buildSearchForm($this);
@@ -155,9 +158,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Pledge_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Pledge_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -184,6 +185,36 @@ protected function getSortNameLabelWithOutEmail() {
return ts('Pledger Name');
}
+ /**
+ * Get the label for the tag field.
+ *
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
+ *
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Pledger Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getGroupLabel() {
+ return ts('Pledger Group(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Pledger Contact Type');
+ }
+
/**
* The post processing of the form gets done here.
*
@@ -203,7 +234,7 @@ public function postProcess() {
$this->_done = TRUE;
- $this->_formValues = $this->controller->exportValues($this->_name);
+ $this->setFormValues();
$this->fixFormValues();
@@ -212,7 +243,7 @@ public function postProcess() {
$this->_formValues["pledge_test"] = 0;
}
- foreach (array('pledge_amount_low', 'pledge_amount_high') as $f) {
+ foreach (['pledge_amount_low', 'pledge_amount_high'] as $f) {
if (isset($this->_formValues[$f])) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
@@ -291,38 +322,7 @@ public function postProcess() {
* @see valid_date
*/
public function addRules() {
- $this->addFormRule(array('CRM_Pledge_Form_Search', 'formRule'));
- }
-
- /**
- * Global validation rules for the form.
- *
- * @param array $fields
- * Posted values of the form.
- *
- * @return array|bool
- */
- public static function formRule($fields) {
- $errors = array();
-
- if (!empty($errors)) {
- return $errors;
- }
-
- return TRUE;
- }
-
- /**
- * Set the default form values.
- *
- *
- * @return array
- * the default array reference
- */
- public function setDefaultValues() {
- $defaults = array();
- $defaults = $this->_formValues;
- return $defaults;
+ $this->addFormRule(['CRM_Pledge_Form_Search', 'formRule']);
}
public function fixFormValues() {
@@ -333,8 +333,8 @@ public function fixFormValues() {
// set pledge payment related fields
$status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
- $this->_formValues['pledge_payment_status_id'] = array($status => 1);
- $this->_defaults['pledge_payment_status_id'] = array($status => 1);
+ $this->_formValues['pledge_payment_status_id'] = [$status => 1];
+ $this->_defaults['pledge_payment_status_id'] = [$status => 1];
}
$fromDate = CRM_Utils_Request::retrieve('start', 'Date');
@@ -360,7 +360,7 @@ public function fixFormValues() {
// we need set all statuses except Cancelled
unset($statusValues[$pledgeStatus]);
- $statuses = array();
+ $statuses = [];
foreach ($statusValues as $statusId => $value) {
$statuses[$statusId] = 1;
}
diff --git a/CRM/Pledge/Form/Task.php b/CRM/Pledge/Form/Task.php
index 218da6c3a8e3..ede0eb0caaf8 100644
--- a/CRM/Pledge/Form/Task.php
+++ b/CRM/Pledge/Form/Task.php
@@ -1,9 +1,9 @@
_pledgeIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_pledgeIds = [];
$values = $form->controller->exportValues('Search');
@@ -86,7 +65,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$pledgeTasks = CRM_Pledge_Task::tasks();
$form->assign('taskName', $pledgeTasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -135,7 +114,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_pledgeIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_pledgeIds,
'civicrm_pledge'
);
}
@@ -151,18 +130,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => $backType,
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Task/Delete.php b/CRM/Pledge/Form/Task/Delete.php
index 2c924ff17c96..ace7d9471736 100644
--- a/CRM/Pledge/Form/Task/Delete.php
+++ b/CRM/Pledge/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count pledges deleted.', 'count' => $deleted));
+ $msg = ts('%count pledge deleted.', ['plural' => '%count pledges deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Pledge/Form/Task/Print.php b/CRM/Pledge/Form/Task/Print.php
index 5dee67b7536f..5af5df8d0b6a 100644
--- a/CRM/Pledge/Form/Task/Print.php
+++ b/CRM/Pledge/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Print Pledge List'),
- 'js' => array('onclick' => 'window.print()'),
+ 'js' => ['onclick' => 'window.print()'],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'back',
'name' => ts('Done'),
- ),
- )
- );
+ ],
+ ]);
}
/**
diff --git a/CRM/Pledge/Form/Task/Result.php b/CRM/Pledge/Form/Task/Result.php
index 5e838317a6a2..385a151fa001 100644
--- a/CRM/Pledge/Form/Task/Result.php
+++ b/CRM/Pledge/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Task/SearchTaskHookSample.php b/CRM/Pledge/Form/Task/SearchTaskHookSample.php
index 9cc917aa5057..0c8576ece9ea 100644
--- a/CRM/Pledge/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Pledge/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_pledgeIds);
@@ -56,11 +56,11 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'create_date' => CRM_Utils_Date::customFormat($dao->create_date),
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -69,14 +69,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Info.php b/CRM/Pledge/Info.php
index 56f445a4edc7..3bbac1648b0d 100644
--- a/CRM/Pledge/Info.php
+++ b/CRM/Pledge/Info.php
@@ -1,9 +1,9 @@
'CiviPledge',
'translatedName' => ts('CiviPledge'),
'title' => ts('CiviCRM Pledge Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* Provides permissions that are used by component.
@@ -76,20 +76,20 @@ public function getInfo() {
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviPledge' => array(
+ $permissions = [
+ 'access CiviPledge' => [
ts('access CiviPledge'),
ts('View pledges'),
- ),
- 'edit pledges' => array(
+ ],
+ 'edit pledges' => [
ts('edit pledges'),
ts('Create and update pledges'),
- ),
- 'delete in CiviPledge' => array(
+ ],
+ 'delete in CiviPledge' => [
ts('delete in CiviPledge'),
ts('Delete pledges'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -110,13 +110,13 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* null if no element offered
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Pledges'),
'title' => ts('Your Pledge(s)'),
// we need to check this permission since you can click on contribution page link for making payment
- 'perm' => array('make online contributions'),
+ 'perm' => ['make online contributions'],
'weight' => 15,
- );
+ ];
}
/**
@@ -129,11 +129,19 @@ public function getUserDashboardElement() {
* null if no element offered
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Pledges'),
'url' => 'pledge',
'weight' => 25,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-paper-plane';
}
/**
@@ -146,10 +154,10 @@ public function registerTab() {
* null if no element offered
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Pledges'),
'weight' => 25,
- );
+ ];
}
/**
@@ -174,14 +182,14 @@ public function creatNewShortcut(&$shortCuts) {
if (CRM_Core_Permission::check('access CiviPledge') &&
CRM_Core_Permission::check('edit pledges')
) {
- $shortCuts = array_merge($shortCuts, array(
- array(
+ $shortCuts = array_merge($shortCuts, [
+ [
'path' => 'civicrm/pledge/add',
'query' => 'reset=1&action=add&context=standalone',
'ref' => 'new-pledge',
'title' => ts('Pledge'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Page/AJAX.php b/CRM/Pledge/Page/AJAX.php
index 6a68cf132e01..fc3532cc57a6 100644
--- a/CRM/Pledge/Page/AJAX.php
+++ b/CRM/Pledge/Page/AJAX.php
@@ -1,9 +1,9 @@
get('fiscalYearStart');
- $year = array('Y' => date('Y'));
+ $year = ['Y' => date('Y')];
$this->assign('curYear', $year['Y']);
$yearDate = array_merge($year, $yearDate);
$yearDate = CRM_Utils_Date::format($yearDate);
diff --git a/CRM/Pledge/Page/Payment.php b/CRM/Pledge/Page/Payment.php
index 16f352b34955..4de246d4ea91 100644
--- a/CRM/Pledge/Page/Payment.php
+++ b/CRM/Pledge/Page/Payment.php
@@ -1,9 +1,9 @@
_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
diff --git a/CRM/Pledge/Page/Tab.php b/CRM/Pledge/Page/Tab.php
index 601f61ec6b03..3c44c2344bcf 100644
--- a/CRM/Pledge/Page/Tab.php
+++ b/CRM/Pledge/Page/Tab.php
@@ -1,9 +1,9 @@
assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('pledge', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
- );
+ ];
}
}
@@ -94,7 +94,7 @@ public function edit() {
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -156,7 +156,7 @@ public function run() {
* @param $form
*/
public static function setContext(&$form) {
- $context = CRM_Utils_Request::retrieve('context', 'String', $form, FALSE, 'search');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'search');
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $form);
// validate the qfKey
diff --git a/CRM/Pledge/Page/UserDashboard.php b/CRM/Pledge/Page/UserDashboard.php
index 447286349dca..82a091391d66 100644
--- a/CRM/Pledge/Page/UserDashboard.php
+++ b/CRM/Pledge/Page/UserDashboard.php
@@ -1,9 +1,9 @@
run();
// add honor block.
- $honorParams = array();
+ $honorParams = [];
$honorParams = CRM_Pledge_BAO_Pledge::getHonorContacts($this->_contactId);
if (!empty($honorParams)) {
// assign vars to templates
diff --git a/CRM/Pledge/Selector/Search.php b/CRM/Pledge/Selector/Search.php
index e5f253180cac..b2d39ad3b71b 100644
--- a/CRM/Pledge/Selector/Search.php
+++ b/CRM/Pledge/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=pledge' . $extraParams,
'title' => ts('View Pledge'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Pledge'),
- ),
- CRM_Core_Action::DETACH => array(
+ ],
+ CRM_Core_Action::DETACH => [
'name' => ts('Cancel'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=detach&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'extra' => 'onclick = "return confirm(\'' . $cancelExtra . '\');"',
'title' => ts('Cancel Pledge'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Pledge'),
- ),
- );
+ ],
+ ];
if (in_array('Cancel', $hideOption)) {
unset(self::$_links[CRM_Core_Action::DETACH]);
@@ -287,7 +287,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
// get all pledge status
$pledgeStatuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
@@ -296,7 +296,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// CRM-4418 check for view, edit and delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit pledges')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -306,7 +306,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -319,15 +319,17 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['campaign_id'] = $result->pledge_campaign_id;
// add pledge status name
- $row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
- $pledgeStatuses
- );
+ if (!empty($row['pledge_status_id'])) {
+ $row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
+ $pledgeStatuses
+ );
+ }
// append (test) to status label
if (!empty($row['pledge_is_test'])) {
- $row['pledge_status'] .= ' (test)';
+ $row['pledge_status'] = CRM_Core_TestEntity::appendTestText($row['pledge_status']);
}
- $hideOption = array();
+ $hideOption = [];
if (CRM_Utils_Array::key('Cancelled', $row) ||
CRM_Utils_Array::key('Completed', $row)
) {
@@ -338,11 +340,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['action'] = CRM_Core_Action::formLink(self::links($hideOption, $this->_key),
$mask,
- array(
+ [
'id' => $result->pledge_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'pledge.selector.row',
@@ -381,57 +383,57 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Pledged'),
'sort' => 'pledge_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Total Paid'),
'sort' => 'pledge_total_paid',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Balance'),
- ),
- array(
+ ],
+ [
'name' => ts('Pledged For'),
'sort' => 'pledge_financial_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Pledge Made'),
'sort' => 'pledge_create_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Next Pay Date'),
'sort' => 'pledge_next_pay_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Next Amount'),
'sort' => 'pledge_next_pay_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'pledge_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact ID')),
- array(
+ $pre = [
+ ['desc' => ts('Contact ID')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
diff --git a/CRM/Pledge/StateMachine/Search.php b/CRM/Pledge/StateMachine/Search.php
index a809e91fd2e8..1bf31c5c09b4 100644
--- a/CRM/Pledge/StateMachine/Search.php
+++ b/CRM/Pledge/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Pledge_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -80,7 +80,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Pledge/Task.php b/CRM/Pledge/Task.php
index feeaf1073449..39309019b676 100644
--- a/CRM/Pledge/Task.php
+++ b/CRM/Pledge/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete pledges'),
'class' => 'CRM_Pledge_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Pledge_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export pledges'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- );
+ ],
+ ];
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviPledge')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
- CRM_Utils_Hook::searchTasks('pledge', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles.
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
- /**
- * These tasks get added based on the context the user is in.
- *
- * @return array
- * the set of optional tasks for a group of contacts
- */
- public static function &optionalTaskTitle() {
- $tasks = array();
- return $tasks;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit pledges')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviPledge')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -158,14 +120,12 @@ public static function &permissionedTaskTitles($permission) {
*/
public static function getTask($value) {
self::tasks();
- if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+
+ if (!CRM_Utils_Array::value($value, self::$_tasks)) {
+ // make it the print task by default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Price/BAO/LineItem.php b/CRM/Price/BAO/LineItem.php
index e1b629c4a721..cd9145d6ccf3 100644
--- a/CRM/Price/BAO/LineItem.php
+++ b/CRM/Price/BAO/LineItem.php
@@ -1,9 +1,9 @@
- * $Id$
+ * @copyright CiviCRM LLC (c) 2004-2019
*/
/**
@@ -70,6 +61,8 @@ public static function create(&$params) {
// unset entity table and entity id in $params
// we never update the entity table and entity id during update mode
if ($id) {
+ $entity_id = CRM_Utils_Array::value('entity_id', $params);
+ $entity_table = CRM_Utils_Array::value('entity_table', $params);
unset($params['entity_id'], $params['entity_table']);
}
else {
@@ -77,7 +70,7 @@ public static function create(&$params) {
$params['unit_price'] = 0;
}
}
- if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
+ if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !empty($params['check_permissions'])) {
if (empty($params['financial_type_id'])) {
throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
}
@@ -92,16 +85,22 @@ public static function create(&$params) {
$return = $lineItemBAO->save();
if ($lineItemBAO->entity_table == 'civicrm_membership' && $lineItemBAO->contribution_id && $lineItemBAO->entity_id) {
- $membershipPaymentParams = array(
+ $membershipPaymentParams = [
'membership_id' => $lineItemBAO->entity_id,
'contribution_id' => $lineItemBAO->contribution_id,
- );
+ ];
if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
+ // If we are creating the membership payment row from the line item then we
+ // should have correct line item & membership payment should not need to fix.
+ $membershipPaymentParams['isSkipLineItem'] = TRUE;
civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
}
}
if ($id) {
+ // CRM-21281: Restore entity reference in case the post hook needs it
+ $lineItemBAO->entity_id = $entity_id;
+ $lineItemBAO->entity_table = $entity_table;
CRM_Utils_Hook::post('edit', 'LineItem', $id, $lineItemBAO);
}
else {
@@ -123,7 +122,7 @@ public static function create(&$params) {
*
* @return CRM_Price_BAO_LineItem
*/
- public static function retrieve(&$params, &$defaults) {
+ public static function retrieve(&$params = [], &$defaults = []) {
$lineItem = new CRM_Price_BAO_LineItem();
$lineItem->copyValues($params);
if ($lineItem->find(TRUE)) {
@@ -143,7 +142,7 @@ public static function retrieve(&$params, &$defaults) {
public static function getAPILineItemParams(&$params) {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types);
if ($types && empty($params['financial_type_id'])) {
- $params['financial_type_id'] = array('IN' => array_keys($types));
+ $params['financial_type_id'] = ['IN' => array_keys($types)];
}
elseif ($types) {
if (is_array($params['financial_type_id'])) {
@@ -153,7 +152,7 @@ public static function getAPILineItemParams(&$params) {
$invalidFts = $params['financial_type_id'];
}
if ($invalidFts) {
- $params['financial_type_id'] = array('NOT IN' => $invalidFts);
+ $params['financial_type_id'] = ['NOT IN' => $invalidFts];
}
}
else {
@@ -170,7 +169,7 @@ public static function getLineTotal($contributionId) {
$sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
FROM civicrm_line_item li
WHERE li.contribution_id = %1";
- $params = array(1 => array($contributionId, 'Integer'));
+ $params = [1 => [$contributionId, 'Integer']];
$lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
return $lineItemTotal;
}
@@ -182,7 +181,7 @@ public static function getLineTotal($contributionId) {
* @return array
*/
public static function getLineItemsByContributionID($contributionID) {
- return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
+ return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
}
/**
@@ -257,16 +256,16 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
$whereClause .= " and li.qty != 0";
}
- $lineItems = array();
+ $lineItems = [];
if (!$entityId || !$entity || !$fromClause) {
return $lineItems;
}
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entity, 'Text'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entity, 'Text'],
+ ];
$getTaxDetails = FALSE;
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
@@ -277,7 +276,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
if (!$dao->id) {
continue;
}
- $lineItems[$dao->id] = array(
+ $lineItems[$dao->id] = [
'qty' => (float) $dao->qty,
'label' => $dao->label,
'unit_price' => $dao->unit_price,
@@ -297,11 +296,11 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
'membership_num_terms' => $dao->membership_num_terms,
'tax_amount' => $dao->tax_amount,
'price_set_id' => $dao->price_set_id,
- );
+ ];
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
if (isset($lineItems[$dao->id]['financial_type_id']) && array_key_exists($lineItems[$dao->id]['financial_type_id'], $taxRates)) {
- // We are close to output/display here - so apply some rounding at output/display level - to not show Tax Rate in all 8 decimals
- $lineItems[$dao->id]['tax_rate'] = round($taxRates[$lineItems[$dao->id]['financial_type_id']], 3);
+ // Cast to float so trailing zero decimals are removed for display.
+ $lineItems[$dao->id]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id]['financial_type_id']];
}
else {
// There is no Tax Rate associated with this Financial Type
@@ -313,6 +312,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
}
}
if ($invoicing) {
+ // @todo - this is an inappropriate place to be doing form level assignments.
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('taxTerm', $taxTerm);
@@ -336,6 +336,11 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
* this is
* lineItem array)
* @param string $amount_override
+ * Amount override must be in format 1000.00 - ie no thousand separator & if
+ * a decimal point is used it should be a decimal
+ *
+ * @todo - this parameter is only used for partial payments. It's unclear why a partial
+ * payment would change the line item price.
*/
public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
if (empty($params["price_{$fid}"])) {
@@ -344,7 +349,7 @@ public static function format($fid, $params, $fields, &$values, $amount_override
//lets first check in fun parameter,
//since user might modified w/ hooks.
- $options = array();
+ $options = [];
if (array_key_exists('options', $fields)) {
$options = $fields['options'];
}
@@ -359,13 +364,9 @@ public static function format($fid, $params, $fields, &$values, $amount_override
foreach ($params["price_{$fid}"] as $oid => $qty) {
$price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
- // lets clean the price in case it is not yet cleant
- // CRM-10974
- $price = CRM_Utils_Rule::cleanMoney($price);
-
$participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
- $values[$oid] = array(
+ $values[$oid] = [
'price_field_id' => $fid,
'price_field_value_id' => $oid,
'label' => CRM_Utils_Array::value('label', $options[$oid]),
@@ -383,7 +384,7 @@ public static function format($fid, $params, $fields, &$values, $amount_override
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
- );
+ ];
if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
$values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
@@ -405,7 +406,7 @@ public static function deleteLineItems($entityId, $entityTable) {
}
if ($entityId && !is_array($entityId)) {
- $entityId = array($entityId);
+ $entityId = [$entityId];
}
$query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
@@ -429,7 +430,7 @@ public static function deleteLineItems($entityId, $entityTable) {
*/
public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
if (!$entityId || !is_array($lineItem)
- || CRM_Utils_system::isNull($lineItem)
+ || CRM_Utils_System::isNull($lineItem)
) {
return;
}
@@ -457,8 +458,11 @@ public static function processPriceSet($entityId, $lineItem, $contributionDetail
// CRM-19094: entity_table is set to civicrm_membership then ensure
// the entityId is set to membership ID not contribution by default
elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
- $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
- $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
+ $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $contributionDetails->id, 'membership_id', 'contribution_id');
+ if ($membershipId && (int) $membershipId !== (int) $line['entity_id']) {
+ $line['entity_id'] = $membershipId;
+ Civi::log()->warning('Per https://lab.civicrm.org/dev/core/issues/15 this data fix should not be required. Please log a ticket at https://lab.civicrm.org/dev/core with steps to get this.', ['civi.tag' => 'deprecated']);
+ }
}
}
@@ -503,16 +507,16 @@ public static function syncLineItems($entityId, $entityTable = 'civicrm_contribu
$where = " li.entity_id = %1 AND
li.entity_table = %2 ";
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entityTable, 'String'),
- 3 => array($amount, 'Float'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entityTable, 'String'],
+ 3 => [$amount, 'Float'],
+ ];
if ($entityTable == 'civicrm_contribution') {
$entityName = 'default_contribution_amount';
$where .= " AND ps.name = %4 ";
- $params[4] = array($entityName, 'String');
+ $params[4] = [$entityName, 'String'];
}
elseif ($entityTable == 'civicrm_participant') {
$from .= "
@@ -522,10 +526,10 @@ public static function syncLineItems($entityId, $entityTable = 'civicrm_contribu
li.price_field_value_id = cpfv.id ";
$where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
$amount = empty($amount) ? 0 : $amount;
- $params += array(
- 4 => array($otherParams['fee_label'], 'String'),
- 5 => array($otherParams['event_id'], 'String'),
- );
+ $params += [
+ 4 => [$otherParams['fee_label'], 'String'],
+ 5 => [$otherParams['event_id'], 'String'],
+ ];
}
$query = "
@@ -552,7 +556,6 @@ public static function syncLineItems($entityId, $entityTable = 'civicrm_contribu
* @param bool $isRelatedID
*/
public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
-
if (!$entityId) {
$priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
$totalAmount = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
@@ -567,7 +570,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
}
$financialType = $values['financial_type_id'];
}
- $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
+ $params['line_item'][$values['setID']][$values['priceFieldID']] = [
'price_field_id' => $values['priceFieldID'],
'price_field_value_id' => $values['priceFieldValueID'],
'label' => $values['label'],
@@ -576,7 +579,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
'line_total' => $totalAmount,
'financial_type_id' => $financialType,
'membership_type_id' => $values['membership_type_id'],
- );
+ ];
break;
}
}
@@ -605,4 +608,734 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
}
}
+ /**
+ * Build the line items for the submitted price field.
+ *
+ * This is when first building them - not an update where an entityId is already present
+ * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
+ * (resolving to the same format regardless of what type of price set is being used first).
+ *
+ * @param array $priceParams
+ * These are per the way the form processes them - ie
+ * ['price_1' => 1, 'price_2' => 8]
+ * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
+ * @param float|NULL $overrideAmount
+ * Optional override of the amount.
+ *
+ * @param int|null $financialTypeID
+ * Financial type ID is the type should be overridden.
+ *
+ * @return array
+ * Line items formatted for processing. These will look like
+ * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
+ * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
+ *
+ */
+ public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
+ $lineItems = [];
+ foreach ($priceParams as $key => $value) {
+ $priceField = self::getPriceFieldMetaData($key);
+
+ if ($priceField['html_type'] === 'Text') {
+ $valueSpec = reset($priceField['values']);
+ }
+ else {
+ $valueSpec = $priceField['values'][$value];
+ }
+ $qty = $priceField['is_enter_qty'] ? $value : 1;
+ $lineItems[$priceField['id']] = [
+ 'price_field_id' => $priceField['id'],
+ 'price_field_value_id' => $valueSpec['id'],
+ 'label' => $valueSpec['label'],
+ 'qty' => $qty,
+ 'unit_price' => $overrideAmount ?: $valueSpec['amount'],
+ 'line_total' => $qty * ($overrideAmount ?: $valueSpec['amount']),
+ 'financial_type_id' => $financialTypeID ?: $valueSpec['financial_type_id'],
+ 'membership_type_id' => $valueSpec['membership_type_id'],
+ 'price_set_id' => $priceField['price_set_id'],
+ ];
+ }
+ return $lineItems;
+ }
+
+ /**
+ * Function to update related contribution of a entity and
+ * add/update/cancel financial records
+ *
+ * @param array $params
+ * @param int $entityID
+ * @param int $entity
+ * @param int $contributionId
+ * @param $feeBlock
+ * @param array $lineItems
+ *
+ */
+ public static function changeFeeSelections(
+ $params,
+ $entityID,
+ $entity,
+ $contributionId,
+ $feeBlock,
+ $lineItems
+ ) {
+ $entityTable = "civicrm_" . $entity;
+ CRM_Price_BAO_PriceSet::processAmount($feeBlock,
+ $params, $lineItems
+ );
+ // initialize empty Lineitem instance to call protected helper functions
+ $lineItemObj = new CRM_Price_BAO_LineItem();
+
+ // fetch submitted LineItems from input params and feeBlock information
+ $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
+
+ $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
+
+ // get financial information that need to be recorded on basis on submitted price field value IDs
+ if (!empty($requiredChanges['line_items_to_cancel']) || !empty($requiredChanges['line_items_to_update'])) {
+ // @todo - this IF is to get this through PR merge but I suspect that it should not
+ // be necessary & is masking something else.
+ $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
+ $entityID,
+ $entityTable,
+ $contributionId,
+ array_keys($requiredChanges['line_items_to_cancel']),
+ $requiredChanges['line_items_to_update']
+ );
+ }
+
+ // update line item with changed line total and other information
+ $totalParticipant = $participantCount = 0;
+ $amountLevel = [];
+ if (!empty($requiredChanges['line_items_to_update'])) {
+ foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
+ $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
+ if ($entity == 'participant' && isset($value['participant_count'])) {
+ $totalParticipant += $value['participant_count'];
+ }
+ }
+ }
+
+ foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
+ // Must use BAO rather than api because a bad line it in the api which we want to avoid.
+ CRM_Price_BAO_LineItem::create($lineItemToAlter);
+ }
+
+ $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
+
+ $count = 0;
+ if ($entity == 'participant') {
+ $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
+ }
+ else {
+ $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
+ }
+ if ($count > 1) {
+ $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
+ }
+ else {
+ $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
+ }
+ if (strlen($params['tax_amount']) != 0) {
+ $taxAmount = $params['tax_amount'];
+ }
+ else {
+ $taxAmount = "NULL";
+ }
+ $displayParticipantCount = '';
+ if ($totalParticipant > 0) {
+ $displayParticipantCount = ' Participant Count -' . $totalParticipant;
+ }
+ $updateAmountLevel = NULL;
+ if (!empty($amountLevel)) {
+ $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
+ }
+ $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
+ $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
+
+ if (!empty($financialItemsArray)) {
+ foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
+ $newFinancialItem = CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
+ // record reverse transaction only if Contribution is Completed because for pending refund or
+ // partially paid we are already recording the surplus owed or refund amount
+ if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
+ $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
+ 'entity_id' => $newFinancialItem->id,
+ 'entity_table' => 'civicrm_financial_item',
+ ]);
+ $reverseTrxn = CRM_Core_BAO_FinancialTrxn::create($updateFinancialItemInfoValues);
+ // record reverse entity financial trxn linked to membership's related contribution
+ civicrm_api3('EntityFinancialTrxn', 'create', [
+ 'entity_table' => "civicrm_contribution",
+ 'entity_id' => $contributionId,
+ 'financial_trxn_id' => $reverseTrxn->id,
+ 'amount' => $reverseTrxn->total_amount,
+ ]);
+ unset($updateFinancialItemInfoValues['financialTrxn']);
+ }
+ elseif ($trxn && $newFinancialItem->amount != 0) {
+ civicrm_api3('EntityFinancialTrxn', 'create', [
+ 'entity_id' => $newFinancialItem->id,
+ 'entity_table' => 'civicrm_financial_item',
+ 'financial_trxn_id' => $trxn->id,
+ 'amount' => $newFinancialItem->amount,
+ ]);
+ }
+ }
+ }
+
+ $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ?? NULL);
+
+ // update participant fee_amount column
+ $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
+ }
+
+ /**
+ * Function to retrieve financial items that need to be recorded as result of changed fee
+ *
+ * @param int $entityID
+ * @param string $entityTable
+ * @param int $contributionID
+ * @param array $priceFieldValueIDsToCancel
+ * @param array $lineItemsToUpdate
+ *
+ * @return array
+ * List of formatted reverse Financial Items to be recorded
+ */
+ protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
+ $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
+
+ $financialItemsArray = [];
+ $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
+ foreach ($financialItemResult as $updateFinancialItemInfoValues) {
+ $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
+
+ // the below params are not needed as we are creating new financial item
+ $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
+ $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
+ unset($updateFinancialItemInfoValues['id']);
+ unset($updateFinancialItemInfoValues['created_date']);
+
+ // if not submitted and difference is not 0 make it negative
+ if ((empty($lineItemsToUpdate) || (in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
+ $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
+ ) && $updateFinancialItemInfoValues['amount'] > 0
+ ) {
+ // INSERT negative financial_items
+ $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
+ // reverse the related financial trxn too
+ $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
+ if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
+ $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
+ $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
+ }
+ // INSERT negative financial_items for tax amount
+ $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
+ }
+ // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
+ elseif (
+ !empty($lineItemsToUpdate)
+ && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
+ && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
+ && $updateFinancialItemInfoValues['amount'] > 0
+ ) {
+ $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
+ if ($amountChangeOnTextLineItem !== (float) 0) {
+ // calculate the amount difference, considered as financial item amount
+ $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
+ if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
+ $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'];
+ $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
+ }
+ $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
+ }
+ }
+ }
+
+ return $financialItemsArray;
+ }
+
+ /**
+ * Helper function to return sum of financial item's amount related to a line-item
+ * @param array $lineItemID
+ *
+ * @return float $financialItem
+ */
+ protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
+ return CRM_Core_DAO::singleValueQuery("
+ SELECT SUM(amount)
+ FROM civicrm_financial_item
+ WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
+ ");
+ }
+
+ /**
+ * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
+ *
+ * @param array $inputParams
+ * @param array $feeBlock
+ *
+ * @return array
+ * List of submitted line items
+ */
+ protected function getSubmittedLineItems($inputParams, $feeBlock) {
+ $submittedLineItems = [];
+ foreach ($feeBlock as $id => $values) {
+ CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
+ }
+
+ return $submittedLineItems;
+ }
+
+ /**
+ * Helper function to retrieve line items that need to be altered.
+ *
+ * We iterate through the previous line items for the given entity to determine
+ * what alterations to line items need to be made to reflect the new line items.
+ *
+ * There are 4 possible changes required - per the keys in the return array.
+ *
+ * @param array $submittedLineItems
+ * @param int $entityID
+ * @param string $entity
+ *
+ * @return array
+ * Array of line items to alter with the following keys
+ * - line_items_to_add. If the line items required are new radio options that
+ * have not previously been set then we should add line items for them
+ * - line_items_to_update. If we have already been an active option and a change has
+ * happened then it should be in this array.
+ * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
+ * These need to be zero'd out.
+ * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
+ * re-enabled rather than a new one added.
+ */
+ protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
+ $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
+
+ $lineItemsToAdd = $submittedLineItems;
+ $lineItemsToUpdate = [];
+ $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
+ $lineItemsToCancel = $lineItemsToResurrect = [];
+
+ foreach ($previousLineItems as $id => $previousLineItem) {
+ if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
+ $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
+ if (CRM_Utils_Array::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
+ // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
+ // because unlike other kind of price-field, it's related price-field-value-id isn't changed and thats why we need to make an
+ // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
+ unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
+ }
+ else {
+ $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
+ // for updating the line items i.e. use-case - once deselect-option selecting again
+ if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
+ || (
+ // This would be a $0 line item - but why it should be catered to
+ // other than when the above condition is unclear.
+ $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
+ )
+ || (
+ $previousLineItem['qty'] != $submittedLineItem['qty']
+ )
+ ) {
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
+ // Format is actually '0.00'
+ if ($previousLineItem['line_total'] == 0) {
+ $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
+ $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
+ }
+ }
+ // If there was previously a submitted line item for the same option value then there is
+ // either no change or a qty adjustment. In either case we are not doing an add + reversal.
+ unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
+ unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
+ }
+ }
+ else {
+ if (!$this->isCancelled($previousLineItem)) {
+ $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
+ $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
+
+ }
+ }
+ }
+
+ return [
+ 'line_items_to_add' => $lineItemsToAdd,
+ 'line_items_to_update' => $lineItemsToUpdate,
+ 'line_items_to_cancel' => $lineItemsToCancel,
+ 'line_items_to_resurrect' => $lineItemsToResurrect,
+ ];
+ }
+
+ /**
+ * Check if a line item has already been cancelled.
+ *
+ * @param array $lineItem
+ *
+ * @return bool
+ */
+ protected function isCancelled($lineItem) {
+ if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
+ return TRUE;
+ }
+ }
+
+ /**
+ * Add line Items as result of fee change.
+ *
+ * @param array $lineItemsToAdd
+ * @param int $entityID
+ * @param string $entityTable
+ * @param int $contributionID
+ */
+ protected function addLineItemOnChangeFeeSelection(
+ $lineItemsToAdd,
+ $entityID,
+ $entityTable,
+ $contributionID
+ ) {
+ // if there is no line item to add, do not proceed
+ if (empty($lineItemsToAdd)) {
+ return;
+ }
+
+ $changedFinancialTypeID = NULL;
+ $updatedContribution = new CRM_Contribute_BAO_Contribution();
+ $updatedContribution->id = (int) $contributionID;
+ // insert financial items
+ foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
+ $lineParams = array_merge($lineParams, [
+ 'entity_table' => $entityTable,
+ 'entity_id' => $entityID,
+ 'contribution_id' => $contributionID,
+ ]);
+ if (!array_key_exists('skip', $lineParams)) {
+ self::create($lineParams);
+ }
+ }
+
+ if ($changedFinancialTypeID) {
+ $updatedContribution->financial_type_id = $changedFinancialTypeID;
+ $updatedContribution->save();
+ }
+ }
+
+ /**
+ * Add financial transactions when an array of line items is changed.
+ *
+ * @param array $lineItemsToAdd
+ * @param int $entityID
+ * @param string $entityTable
+ * @param int $contributionID
+ * @param bool $trxnID
+ * Is there a change to the total balance requiring additional transactions to be created.
+ */
+ protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
+ $updatedContribution = new CRM_Contribute_BAO_Contribution();
+ $updatedContribution->id = $contributionID;
+ $updatedContribution->find(TRUE);
+ $trxnArray = $trxnID ? ['id' => $trxnID] : NULL;
+
+ foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
+ $lineParams = array_merge($lineParams, [
+ 'entity_table' => $entityTable,
+ 'entity_id' => $entityID,
+ 'contribution_id' => $contributionID,
+ ]);
+ $financialTypeChangeTrxnID = $this->addFinancialItemsOnLineItemChange($trxnID, $lineParams, $updatedContribution);
+ $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams);
+ // insert financial items
+ // ensure entity_financial_trxn table has a linking of it.
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnArray);
+ if (isset($lineObj->tax_amount)) {
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnArray);
+ }
+ }
+ }
+
+ /**
+ * Helper function to update entity record on change fee selection
+ *
+ * @param array $inputParams
+ * @param int $entityID
+ * @param string $entity
+ *
+ */
+ protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
+ $entityTable = "civicrm_{$entity}";
+
+ if ($entity == 'participant') {
+ $partUpdateFeeAmt = ['id' => $entityID];
+ $getUpdatedLineItems = "SELECT *
+ FROM civicrm_line_item
+ WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
+ $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
+ $line = [];
+ while ($getUpdatedLineItemsDAO->fetch()) {
+ $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
+ }
+
+ $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
+ $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
+ CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
+
+ //activity creation
+ CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
+ }
+ }
+
+ /**
+ * Get the metadata for a price field.
+ *
+ * @param string|int $key
+ * Price field id. Either as an integer or as 'price_4' where 4 is the id
+ *
+ * @return array
+ * Metadata for the price field with a values key for option values.
+ */
+ protected static function getPriceFieldMetaData($key) {
+ $priceFieldID = str_replace('price_', '', $key);
+ if (!isset(Civi::$statics[__CLASS__]['price_fields'][$priceFieldID])) {
+ $values = civicrm_api3('PriceFieldValue', 'get', [
+ 'price_field_id' => $priceFieldID,
+ 'return' => [
+ 'id',
+ 'amount',
+ 'financial_type_id',
+ 'membership_type_id',
+ 'label',
+ 'price_field_id',
+ 'price_field_id.price_set_id',
+ 'price_field_id.html_type',
+ 'is_enter_qty',
+ ],
+ ]);
+ $firstValue = reset($values['values']);
+ $values = $values['values'];
+ foreach ($values as $index => $value) {
+ // Let's be nice to calling functions & ensure membership_type_id is set
+ // so they don't have to handle notices on it. Handle one place not many.
+ if (!isset($value['membership_type_id'])) {
+ $values[$index]['membership_type_id'] = NULL;
+ }
+ }
+
+ Civi::$statics[__CLASS__]['price_fields'][$priceFieldID] = [
+ 'price_set_id' => $firstValue['price_field_id.price_set_id'],
+ 'id' => $firstValue['price_field_id'],
+ 'html_type' => $firstValue['price_field_id.html_type'],
+ 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
+ 'values' => $values,
+ ];
+ }
+ return Civi::$statics[__CLASS__]['price_fields'][$priceFieldID];
+ }
+
+ /**
+ * Helper function to retrieve financial trxn parameters to reverse
+ * for given financial item identified by $financialItemID
+ *
+ * @param int $financialItemID
+ *
+ * @return array $financialTrxn
+ *
+ */
+ protected function _getRelatedCancelFinancialTrxn($financialItemID) {
+ try {
+ $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
+ 'entity_table' => 'civicrm_financial_item',
+ 'entity_id' => $financialItemID,
+ 'options' => [
+ 'sort' => 'id DESC',
+ 'limit' => 1,
+ ],
+ 'api.FinancialTrxn.getsingle' => [
+ 'id' => "\$value.financial_trxn_id",
+ ],
+ ]);
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ return [];
+ }
+
+ $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
+ 'trxn_date' => date('YmdHis'),
+ 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
+ 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
+ 'entity_table' => 'civicrm_financial_item',
+ 'entity_id' => $financialItemID,
+ ]);
+ unset($financialTrxn['id']);
+
+ return $financialTrxn;
+ }
+
+ /**
+ * Record adjusted amount.
+ *
+ * @param int $updatedAmount
+ * @param int $contributionId
+ * @param int $taxAmount
+ * @param bool $updateAmountLevel
+ *
+ * @return bool|\CRM_Core_BAO_FinancialTrxn
+ */
+ protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
+ $paidAmount = CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId);
+ $balanceAmt = $updatedAmount - $paidAmount;
+
+ $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+ $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
+ $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
+ $completedStatusId = array_search('Completed', $contributionStatuses);
+
+ $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
+ $adjustedTrxn = $skip = FALSE;
+ if ($balanceAmt) {
+ if ($balanceAmt > 0 && $paidAmount != 0) {
+ $contributionStatusVal = $partiallyPaidStatusId;
+ }
+ elseif ($balanceAmt < 0 && $paidAmount != 0) {
+ $contributionStatusVal = $pendingRefundStatusId;
+ }
+ elseif ($paidAmount == 0) {
+ //skip updating the contribution status if no payment is made
+ $skip = TRUE;
+ $updatedContributionDAO->cancel_date = 'null';
+ $updatedContributionDAO->cancel_reason = NULL;
+ }
+ // update contribution status and total amount without trigger financial code
+ // as this is handled in current BAO function used for change selection
+ $updatedContributionDAO->id = $contributionId;
+ if (!$skip) {
+ $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
+ }
+ $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
+ $updatedContributionDAO->fee_amount = 0;
+ $updatedContributionDAO->tax_amount = $taxAmount;
+ if (!empty($updateAmountLevel)) {
+ $updatedContributionDAO->amount_level = $updateAmountLevel;
+ }
+ $updatedContributionDAO->save();
+ // adjusted amount financial_trxn creation
+ $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
+ ['id' => $contributionId]
+ );
+ $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
+ $adjustedTrxnValues = [
+ 'from_financial_account_id' => NULL,
+ 'to_financial_account_id' => $toFinancialAccount,
+ 'total_amount' => $balanceAmt,
+ 'net_amount' => $balanceAmt,
+ 'status_id' => $completedStatusId,
+ 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
+ 'contribution_id' => $updatedContribution->id,
+ 'trxn_date' => date('YmdHis'),
+ 'currency' => $updatedContribution->currency,
+ ];
+ $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
+ }
+ // CRM-17151: Update the contribution status to completed if balance is zero,
+ // because due to sucessive fee change will leave the related contribution status incorrect
+ else {
+ CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
+ }
+
+ return $adjustedTrxn;
+ }
+
+ /**
+ * Add financial items to reflect line item change.
+ *
+ * @param bool $isCreateAdditionalFinancialTrxn
+ * @param array $lineParams
+ * @param \CRM_Contribute_BAO_Contribution $updatedContribution
+ */
+ protected function addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution) {
+ $tempFinancialTrxnID = NULL;
+ // don't add financial item for cancelled line item
+ if ($lineParams['qty'] == 0) {
+ return NULL;
+ }
+ elseif ($isCreateAdditionalFinancialTrxn) {
+ // This routine & the return below is super uncomfortable.
+ // I have refactored to here and it is hit from
+ // testSubmitUnpaidPriceChangeWhileStillPending
+ // but I'm still skeptical it's not covered elsewhere.
+ // original comment : add financial item if ONLY financial type is changed
+ if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id) {
+ $changedFinancialTypeID = (int) $lineParams['financial_type_id'];
+ $adjustedTrxnValues = [
+ 'from_financial_account_id' => NULL,
+ 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id),
+ 'total_amount' => $lineParams['line_total'],
+ 'net_amount' => $lineParams['line_total'],
+ 'status_id' => $updatedContribution->contribution_status_id,
+ 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
+ 'contribution_id' => $updatedContribution->id,
+ 'is_payment' => TRUE,
+ // since balance is 0, which means contribution is completed
+ 'trxn_date' => date('YmdHis'),
+ 'currency' => $updatedContribution->currency,
+ ];
+ $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
+ return $adjustedTrxn->id;
+ }
+ }
+ }
+
+ /**
+ * Get Financial items, culling out any that have already been reversed.
+ *
+ * @param int $entityID
+ * @param string $entityTable
+ *
+ * @return array
+ * Array of financial items that have not be reversed.
+ */
+ protected function getNonCancelledFinancialItems($entityID, $entityTable) {
+ // gathering necessary info to record negative (deselected) financial_item
+ $updateFinancialItem = "
+ SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
+ FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
+ WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
+ GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
+ ";
+ $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
+
+ $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
+ $items = [];
+ foreach ($financialItemResult as $index => $financialItem) {
+ $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
+
+ if (!empty($items[$financialItem['price_field_value_id']])) {
+ foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
+ if ($financialItem['amount'] + $existingAmount == 0) {
+ // Filter both rows as they cancel each other out.
+ unset($financialItemResult[$index]);
+ unset($financialItemResult[$existingItemID]);
+ unset($items['price_field_value_id'][$existingItemID]);
+ unset($items[$financialItem['price_field_value_id']][$index]);
+ }
+ }
+
+ }
+
+ }
+ return $financialItemResult;
+ }
+
+ /**
+ * Get the string used to describe the sales tax (eg. VAT, GST).
+ *
+ * @return string
+ */
+ protected function getSalesTaxTerm() {
+ return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
+ }
+
}
diff --git a/CRM/Price/BAO/PriceField.php b/CRM/Price/BAO/PriceField.php
index 6c6070d59e44..1020c6009a56 100644
--- a/CRM/Price/BAO/PriceField.php
+++ b/CRM/Price/BAO/PriceField.php
@@ -1,9 +1,9 @@
ID
+ *
+ * @var array
+ */
+ private static $visibilityOptionsKeys;
+
/**
* Takes an associative array and creates a price field object.
*
@@ -54,6 +61,9 @@ class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
* @return CRM_Price_BAO_PriceField
*/
public static function add(&$params) {
+ $hook = empty($params['id']) ? 'create' : 'edit';
+ CRM_Utils_Hook::pre($hook, 'PriceField', CRM_Utils_Array::value('id', $params), $params);
+
$priceFieldBAO = new CRM_Price_BAO_PriceField();
$priceFieldBAO->copyValues($params);
@@ -63,6 +73,7 @@ public static function add(&$params) {
}
$priceFieldBAO->save();
+ CRM_Utils_Hook::post($hook, 'PriceField', $priceFieldBAO->id, $priceFieldBAO);
return $priceFieldBAO;
}
@@ -75,6 +86,9 @@ public static function add(&$params) {
* (reference) an assoc array of name/value pairs.
*
* @return CRM_Price_DAO_PriceField
+ *
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public static function create(&$params) {
if (empty($params['id']) && empty($params['name'])) {
@@ -92,16 +106,17 @@ public static function create(&$params) {
if (!empty($params['id']) && empty($priceField->html_type)) {
$priceField->html_type = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
}
- $optionsIds = array();
+ $optionsIds = [];
$maxIndex = CRM_Price_Form_Field::NUM_OPTION;
if ($priceField->html_type == 'Text') {
$maxIndex = 1;
- $fieldOptions = civicrm_api3('price_field_value', 'get', array(
+ $fieldOptions = civicrm_api3('price_field_value', 'get', [
'price_field_id' => $priceField->id,
'sequential' => 1,
- ));
+ ]);
foreach ($fieldOptions['values'] as $option) {
$optionsIds['id'] = $option['id'];
+ $params['option_id'] = [1 => $option['id']];
// CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
if (!empty($params['id']) && $priceField->label != $option['label']) {
$fieldValue = new CRM_Price_DAO_PriceFieldValue();
@@ -111,7 +126,7 @@ public static function create(&$params) {
}
}
}
- $defaultArray = array();
+ $defaultArray = [];
//html type would be empty in update scenario not sure what would happen ...
if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
$tempArray = array_keys($params['default_checkbox_option']);
@@ -133,11 +148,11 @@ public static function create(&$params) {
(CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
!CRM_Utils_System::isNull($params['option_amount'][$index])
) {
- $options = array(
+ $options = [
'price_field_id' => $priceField->id,
'label' => trim($params['option_label'][$index]),
'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
- 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
+ 'amount' => trim($params['option_amount'][$index]),
'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
@@ -147,7 +162,8 @@ public static function create(&$params) {
'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
'membership_num_terms' => NULL,
'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $params),
- );
+ 'visibility_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_visibility_id', $params), self::getVisibilityOptionID('public')),
+ ];
if ($options['membership_type_id']) {
$options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
@@ -162,10 +178,10 @@ public static function create(&$params) {
}
if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
if ($opId = CRM_Utils_Array::value($index, $opIds)) {
- $optionsIds['id'] = $opId;
+ $options['id'] = $opId;
}
else {
- $optionsIds['id'] = NULL;
+ $options['id'] = NULL;
}
}
try {
@@ -176,8 +192,8 @@ public static function create(&$params) {
throw new CRM_Core_Exception($e->getMessage());
}
}
- elseif (!empty($optionsIds)) {
- $optionsLoad = civicrm_api3('price_field_value', 'get', array('id' => $optionsIds['id']));
+ elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
+ $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
$options = $optionsLoad['values'][$optionsIds['id']];
$options['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
try {
@@ -216,8 +232,8 @@ public static function retrieve(&$params, &$defaults) {
* @param bool $is_active
* Value we want to set the is_active field.
*
- * @return Object
- * DAO object on success, null otherwise.
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
@@ -279,7 +295,7 @@ public static function addQuickFormElement(
$useRequired = TRUE,
$label = NULL,
$fieldOptions = NULL,
- $freezeOptions = array()
+ $freezeOptions = []
) {
$field = new CRM_Price_DAO_PriceField();
@@ -339,13 +355,13 @@ public static function addQuickFormElement(
$qf->assign('taxTerm', $taxTerm);
$qf->assign('invoicing', $invoicing);
}
- $priceVal = implode($seperator, array(
+ $priceVal = implode($seperator, [
$customOption[$optionKey][$valueFieldName] + $taxAmount,
$count,
$max_value,
- ));
+ ]);
- $extra = array();
+ $extra = [];
if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
$useRequired = 0;
}
@@ -355,21 +371,21 @@ public static function addQuickFormElement(
if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
$label .= ' ' . $currencySymbol;
$qf->assign('priceset', $elementName);
- $extra = array('onclick' => 'useAmountOther();');
+ $extra = ['onclick' => 'useAmountOther();'];
}
}
$element = &$qf->add('text', $elementName, $label,
array_merge($extra,
- array(
- 'price' => json_encode(array($optionKey, $priceVal)),
+ [
+ 'price' => json_encode([$optionKey, $priceVal]),
'size' => '4',
- )
+ ]
),
$useRequired && $field->is_required
);
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
// CRM-6902 - Add "max" option for a price set field
@@ -385,7 +401,7 @@ public static function addQuickFormElement(
$type = 'money';
}
else {
- $message = ts('%1 must be a number (with or without decimal point).', array(1 => $label));
+ $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
$type = 'numeric';
}
// integers will have numeric rule applied to them.
@@ -393,7 +409,7 @@ public static function addQuickFormElement(
break;
case 'Radio':
- $choice = array();
+ $choice = [];
if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
$qf->assign('contriPriceset', $elementName);
@@ -404,10 +420,10 @@ public static function addQuickFormElement(
if ($field->is_display_amounts) {
$opt['label'] = !empty($opt['label']) ? $opt['label'] . ' - ' : '';
$preHelpText = $postHelpText = '';
- if (isset($opt['help_pre'])) {
+ if (!empty($opt['help_pre'])) {
$preHelpText = '' . $opt['help_pre'] . ': ';
}
- if (isset($opt['help_post'])) {
+ if (!empty($opt['help_post'])) {
$postHelpText = ': ' . $opt['help_post'] . '';
}
if (isset($taxAmount) && $invoicing) {
@@ -430,27 +446,34 @@ public static function addQuickFormElement(
}
$count = CRM_Utils_Array::value('count', $opt, '');
$max_value = CRM_Utils_Array::value('max_value', $opt, '');
- $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
- $extra = array(
- 'price' => json_encode(array($elementName, $priceVal)),
+ $priceVal = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
+ if (isset($opt['visibility_id'])) {
+ $visibility_id = $opt['visibility_id'];
+ }
+ else {
+ $visibility_id = self::getVisibilityOptionID('public');
+ }
+ $extra = [
+ 'price' => json_encode([$elementName, $priceVal]),
'data-amount' => $opt[$valueFieldName],
'data-currency' => $currencyName,
'data-price-field-values' => json_encode($customOption),
- );
+ 'visibility' => $visibility_id,
+ ];
if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
- $extra += array('onclick' => 'clearAmountOther();');
+ $extra += ['onclick' => 'clearAmountOther();'];
}
- elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
- $extra += array(
+ if ($field->name == 'membership_amount') {
+ $extra += [
'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
'membership-type' => $opt['membership_type_id'],
- );
+ ];
$qf->assign('membershipFieldID', $field->id);
}
$choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
// CRM-6902 - Add "max" option for a price set field
@@ -462,11 +485,11 @@ public static function addQuickFormElement(
}
if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
$choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
- array(
- 'price' => json_encode(array($elementName, '0|0')),
+ [
+ 'price' => json_encode([$elementName, '0|0']),
'data-currency' => $currencyName,
'onclick' => 'clearAmountOther();',
- )
+ ]
);
}
@@ -483,7 +506,7 @@ public static function addQuickFormElement(
}
$choice[] = $qf->createElement('radio', NULL, '', $none, '0',
- array('price' => json_encode(array($elementName, '0')))
+ ['price' => json_encode([$elementName, '0'])]
);
}
@@ -497,12 +520,12 @@ public static function addQuickFormElement(
}
if ($useRequired && $field->is_required) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
}
break;
case 'Select':
- $selectOption = $allowedOptions = $priceVal = array();
+ $selectOption = $allowedOptions = $priceVal = [];
foreach ($customOption as $opt) {
$taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
@@ -519,7 +542,7 @@ public static function addQuickFormElement(
}
}
- $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
+ $priceVal[$opt['id']] = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
if (!in_array($opt['id'], $freezeOptions)) {
$allowedOptions[] = $opt['id'];
@@ -533,16 +556,21 @@ public static function addQuickFormElement(
$selectOption[$opt['id']] = $opt['label'];
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
}
-
+ if (isset($opt['visibility_id'])) {
+ $visibility_id = $opt['visibility_id'];
+ }
+ else {
+ $visibility_id = self::getVisibilityOptionID('public');
+ }
$element = &$qf->add('select', $elementName, $label,
- array(
+ [
'' => ts('- select -'),
- ) + $selectOption,
+ ] + $selectOption,
$useRequired && $field->is_required,
- array('price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption))
+ ['price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption)]
);
// CRM-6902 - Add "max" option for a price set field
@@ -554,7 +582,7 @@ public static function addQuickFormElement(
case 'CheckBox':
- $check = array();
+ $check = [];
foreach ($customOption as $opId => $opt) {
$taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
$count = CRM_Utils_Array::value('count', $opt, '');
@@ -577,16 +605,17 @@ public static function addQuickFormElement(
}
$opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
}
- $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
+ $priceVal = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
$check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
- array(
- 'price' => json_encode(array($opt['id'], $priceVal)),
+ [
+ 'price' => json_encode([$opt['id'], $priceVal]),
'data-amount' => $opt[$valueFieldName],
'data-currency' => $currencyName,
- )
+ 'visibility' => $opt['visibility_id'],
+ ]
);
if ($is_pay_later) {
- $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], array('size' => '4'));
+ $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
$qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
}
// CRM-6902 - Add "max" option for a price set field
@@ -598,7 +627,7 @@ public static function addQuickFormElement(
}
$element = &$qf->addGroup($check, $elementName, $label);
if ($useRequired && $field->is_required) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
}
break;
}
@@ -623,17 +652,16 @@ public static function addQuickFormElement(
* array of options
*/
public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
- static $options = array();
- if ($reset) {
- $options = array();
+ if ($reset || !isset(Civi::$statics[__CLASS__]['priceOptions'])) {
+ Civi::$statics[__CLASS__]['priceOptions'] = [];
// This would happen if the function was only called to clear the cache.
if (empty($fieldId)) {
- return array();
+ return [];
}
}
- if (empty($options[$fieldId])) {
- $values = array();
+ if (empty(Civi::$statics[__CLASS__]['priceOptions'][$fieldId])) {
+ $values = $options = [];
CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
$options[$fieldId] = $values;
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
@@ -647,9 +675,10 @@ public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FA
$options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
}
}
+ Civi::$statics[__CLASS__]['priceOptions'][$fieldId] = $options[$fieldId];
}
- return $options[$fieldId];
+ return Civi::$statics[__CLASS__]['priceOptions'][$fieldId];
}
/**
@@ -676,10 +705,10 @@ public static function getOptionId($optionLabel, $fid) {
AND option_group.id = option_value.option_group_id
AND option_value.label = %2";
- $dao = CRM_Core_DAO::executeQuery($query, array(
- 1 => array($optionGroupName, 'String'),
- 2 => array($optionLabel, 'String'),
- ));
+ $dao = CRM_Core_DAO::executeQuery($query, [
+ 1 => [$optionGroupName, 'String'],
+ 2 => [$optionLabel, 'String'],
+ ]);
while ($dao->fetch()) {
return $dao->id;
@@ -704,7 +733,7 @@ public static function deleteField($id) {
CRM_Price_BAO_PriceFieldValue::deleteValues($id);
// reorder the weight before delete
- $fieldValues = array('price_set_id' => $field->price_set_id);
+ $fieldValues = ['price_set_id' => $field->price_set_id];
CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
@@ -721,12 +750,12 @@ public static function deleteField($id) {
public static function &htmlTypes() {
static $htmlTypes = NULL;
if (!$htmlTypes) {
- $htmlTypes = array(
+ $htmlTypes = [
'Text' => ts('Text / Numeric Quantity'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
'CheckBox' => ts('CheckBox'),
- );
+ ];
}
return $htmlTypes;
}
@@ -751,10 +780,10 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
$priceField->price_set_id = $priceSetId;
$priceField->find();
- $priceFields = array();
+ $priceFields = [];
if ($allowNoneSelection) {
- $noneSelectedPriceFields = array();
+ $noneSelectedPriceFields = [];
}
while ($priceField->fetch()) {
@@ -780,15 +809,15 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
FROM civicrm_price_field
WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
$fieldDAO = CRM_Core_DAO::executeQuery($sql);
- $htmlTypes = array();
+ $htmlTypes = [];
while ($fieldDAO->fetch()) {
$htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
}
- $selectedAmounts = array();
+ $selectedAmounts = [];
foreach ($htmlTypes as $fieldId => $type) {
- $options = array();
+ $options = [];
CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
if (empty($options)) {
@@ -814,8 +843,17 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
list($componentName) = explode(':', $fields['_qf_default']);
// now we have all selected amount in hand.
$totalAmount = array_sum($selectedAmounts);
+ // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
+ $totalPaymentAmountEnteredOnForm = CRM_Utils_Array::value('partial_payment_total', $fields, CRM_Utils_Array::value('total_amount', $fields));
if ($totalAmount < 0) {
- $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
+ $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
+ }
+ elseif ($totalAmount > 0 &&
+ // if total amount is equal to all selected amount in hand
+ $totalPaymentAmountEnteredOnForm >= $totalAmount &&
+ (CRM_Utils_Array::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
+ ) {
+ $error['total_amount'] = ts('You have specified the status Partially Paid but have entered an amount that equals or exceeds the amount due. Please adjust the status of the payment or the amount');
}
}
else {
@@ -860,4 +898,31 @@ public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm)
return $label;
}
+ /**
+ * Given the name of a visibility option, returns its ID.
+ *
+ * @param string $visibilityName
+ *
+ * @return int
+ */
+ public static function getVisibilityOptionID($visibilityName) {
+
+ if (!isset(self::$visibilityOptionsKeys)) {
+ self::$visibilityOptionsKeys = CRM_Price_BAO_PriceField::buildOptions(
+ 'visibility_id',
+ NULL,
+ [
+ 'labelColumn' => 'name',
+ 'flip' => TRUE,
+ ]
+ );
+ }
+
+ if (isset(self::$visibilityOptionsKeys[$visibilityName])) {
+ return self::$visibilityOptionsKeys[$visibilityName];
+ }
+
+ return 0;
+ }
+
}
diff --git a/CRM/Price/BAO/PriceFieldValue.php b/CRM/Price/BAO/PriceFieldValue.php
index 186c4326c895..57a78fc07119 100644
--- a/CRM/Price/BAO/PriceFieldValue.php
+++ b/CRM/Price/BAO/PriceFieldValue.php
@@ -1,9 +1,9 @@
copyValues($params);
- if ($id = CRM_Utils_Array::value('id', $ids)) {
- $fieldValueBAO->id = $id;
- $prevLabel = self::getOptionLabel($id);
- if (!empty($params['label']) && $prevLabel != $params['label']) {
- self::updateAmountAndFeeLevel($id, $prevLabel, $params['label']);
- }
- }
// CRM-16189
$priceFieldID = CRM_Utils_Array::value('price_field_id', $params);
+
+ $id = CRM_Utils_Array::value('id', $ids, CRM_Utils_Array::value('id', $params));
+
if (!$priceFieldID) {
$priceFieldID = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceFieldValue', $id, 'price_field_id');
}
if (!empty($params['is_default'])) {
$query = 'UPDATE civicrm_price_field_value SET is_default = 0 WHERE price_field_id = %1';
- $p = array(1 => array($params['price_field_id'], 'Integer'));
+ $p = [1 => [$params['price_field_id'], 'Integer']];
CRM_Core_DAO::executeQuery($query, $p);
}
$fieldValueBAO->save();
+ CRM_Utils_Hook::post($hook, 'PriceFieldValue', $fieldValueBAO->id, $fieldValueBAO);
+
// Reset the cached values in this function.
CRM_Price_BAO_PriceField::getOptions(CRM_Utils_Array::value('price_field_id', $params), FALSE, TRUE);
return $fieldValueBAO;
@@ -85,8 +85,10 @@ public static function add(&$params, $ids = array()) {
* @param $ids
*
* @return CRM_Price_DAO_PriceFieldValue
+ *
+ * @throws \CRM_Core_Exception
*/
- public static function create(&$params, $ids = array()) {
+ public static function create(&$params, $ids = []) {
$id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
if (!is_array($params) || empty($params)) {
return NULL;
@@ -104,7 +106,7 @@ public static function create(&$params, $ids = array()) {
if ($id) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'weight', 'id');
}
- $fieldValues = array('price_field_id' => CRM_Utils_Array::value('price_field_id', $params, 0));
+ $fieldValues = ['price_field_id' => CRM_Utils_Array::value('price_field_id', $params, 0)];
$params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceFieldValue', $oldWeight, $params['weight'], $fieldValues);
}
else {
@@ -132,10 +134,10 @@ public static function create(&$params, $ids = array()) {
* @return array
*/
public static function getDefaults() {
- return array(
+ return [
'is_active' => 1,
'weight' => 1,
- );
+ ];
}
@@ -223,9 +225,8 @@ public static function getOptionLabel($id) {
* @param bool $is_active
* Value we want to set the is_active field.
*
- * @return Object
- * DAO object on success, null otherwise
- *
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'is_active', $is_active);
@@ -284,11 +285,11 @@ public static function updateFinancialType($entityId, $entityTable, $financialTy
if (!$entityId || !$entityTable || !$financialTypeID) {
return;
}
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entityTable, 'String'),
- 3 => array($financialTypeID, 'Integer'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entityTable, 'String'],
+ 3 => [$financialTypeID, 'Integer'],
+ ];
// for event discount
$join = $where = '';
if ($entityTable == 'civicrm_event') {
@@ -311,39 +312,4 @@ public static function updateFinancialType($entityId, $entityTable, $financialTy
CRM_Core_DAO::executeQuery($sql, $params);
}
- /**
- * Update price option label in line_item, civicrm_contribution and civicrm_participant.
- *
- * @param int $id - id of the price_field_value
- * @param string $prevLabel
- * @param string $newLabel
- *
- */
- public static function updateAmountAndFeeLevel($id, $prevLabel, $newLabel) {
- // update price field label in line item.
- $lineItem = new CRM_Price_DAO_LineItem();
- $lineItem->price_field_value_id = $id;
- $lineItem->label = $prevLabel;
- $lineItem->find();
- while ($lineItem->fetch()) {
- $lineItemParams['id'] = $lineItem->id;
- $lineItemParams['label'] = $newLabel;
- CRM_Price_BAO_LineItem::create($lineItemParams);
-
- // update amount and fee level in civicrm_contribution and civicrm_participant
- $params = array(
- 1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'),
- 2 => array(CRM_Core_DAO::VALUE_SEPARATOR . $newLabel . ' -', 'String'),
- );
- // Update contribution
- if (!empty($lineItem->contribution_id)) {
- CRM_Core_DAO::executeQuery("UPDATE `civicrm_contribution` SET `amount_level` = REPLACE(amount_level, %1, %2) WHERE id = {$lineItem->contribution_id}", $params);
- }
- // Update participant
- if ($lineItem->entity_table == 'civicrm_participant') {
- CRM_Core_DAO::executeQuery("UPDATE `civicrm_participant` SET `fee_level` = REPLACE(fee_level, %1, %2) WHERE id = {$lineItem->entity_id}", $params);
- }
- }
- }
-
}
diff --git a/CRM/Price/BAO/PriceSet.php b/CRM/Price/BAO/PriceSet.php
index 3b1dfb35d8bb..c7d9ebe7079e 100644
--- a/CRM/Price/BAO/PriceSet.php
+++ b/CRM/Price/BAO/PriceSet.php
@@ -1,9 +1,9 @@
domain_id = CRM_Core_Config::domainID();
}
- return $priceSetBAO->save();
+ $priceSetBAO->save();
+
+ CRM_Utils_Hook::post($hook, 'PriceSet', $priceSetBAO->id, $priceSetBAO);
+ return $priceSetBAO;
}
/**
@@ -105,10 +111,8 @@ public static function retrieve(&$params, &$defaults) {
* Id of the database record.
* @param $isActive
*
- * @internal param bool $is_active value we want to set the is_active field
- *
- * @return Object
- * DAO object on success, null otherwise
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsActive($id, $isActive) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
@@ -142,9 +146,9 @@ public static function getDefaultPriceSet($entity = 'contribution') {
";
$dao = CRM_Core_DAO::executeQuery($sql);
- self::$_defaultPriceSet[$entity] = array();
+ self::$_defaultPriceSet[$entity] = [];
while ($dao->fetch()) {
- self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
+ self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = [
'setID' => $dao->setID,
'priceFieldID' => $dao->priceFieldID,
'name' => $dao->name,
@@ -153,7 +157,7 @@ public static function getDefaultPriceSet($entity = 'contribution') {
'membership_type_id' => $dao->membership_type_id,
'amount' => $dao->amount,
'financial_type_id' => $dao->financial_type_id,
- );
+ ];
}
return self::$_defaultPriceSet[$entity];
@@ -183,7 +187,7 @@ public static function getTitle($id) {
* @return array
*/
public static function getUsedBy($id, $simpleReturn = FALSE) {
- $usedBy = array();
+ $usedBy = [];
$forms = self::getFormsUsingPriceSet($id);
$tables = array_keys($forms);
// @todo - this is really clumsy overloading the signature like this. Instead
@@ -199,7 +203,7 @@ public static function getUsedBy($id, $simpleReturn = FALSE) {
FROM civicrm_line_item cli
LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
WHERE cpf.price_set_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
while ($crmFormDAO->fetch()) {
$forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
@@ -315,13 +319,13 @@ public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuick
if ($isQuickConfig) {
$sql .= ' AND ps.is_quick_config = 0 ';
}
- $params = array(
- 1 => array($entityTable, 'String'),
- 2 => array($entityId, 'Integer'),
- );
+ $params = [
+ 1 => [$entityTable, 'String'],
+ 2 => [$entityId, 'Integer'],
+ ];
if ($usedFor) {
$sql .= " AND ps.extends LIKE '%%3%' ";
- $params[3] = array($usedFor, 'Integer');
+ $params[3] = [$usedFor, 'Integer'];
}
$dao = CRM_Core_DAO::executeQuery($sql, $params);
@@ -338,7 +342,7 @@ public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuick
* array may contain either option id or
* price field id
*
- * @return int|NULL
+ * @return int|null
* price set id on success, null otherwise
*/
public static function getSetId(&$params) {
@@ -392,7 +396,7 @@ public static function getAssoc($withInactive = FALSE, $extendComponentName = FA
$query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
}
- $priceSets = array();
+ $priceSets = [];
if ($extendComponentName) {
$componentId = CRM_Core_Component::getComponentID($extendComponentName);
@@ -436,9 +440,9 @@ public static function getAssoc($withInactive = FALSE, $extendComponentName = FA
*/
public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
// create a new tree
- $setTree = array();
+ $setTree = [];
- $priceFields = array(
+ $priceFields = [
'id',
'name',
'label',
@@ -455,7 +459,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
'javascript',
'visibility_id',
'is_required',
- );
+ ];
if ($required == TRUE) {
$priceFields[] = 'is_required';
}
@@ -464,9 +468,9 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
$select = 'SELECT ' . implode(',', $priceFields);
$from = ' FROM civicrm_price_field';
- $params = array(
- 1 => array($setID, 'Integer'),
- );
+ $params = [
+ 1 => [$setID, 'Integer'],
+ ];
$currentTime = date('YmdHis');
$where = "
WHERE price_set_id = %1
@@ -495,7 +499,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
while ($dao->fetch()) {
$fieldID = $dao->id;
- $setTree[$setID]['fields'][$fieldID] = array();
+ $setTree[$setID]['fields'][$fieldID] = [];
$setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
foreach ($priceFields as $field) {
@@ -561,7 +565,6 @@ public static function getOnlyPriceFieldValueID(array $priceSet) {
return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
}
-
/**
* Initiate price set such that various non-BAO things are set on the form.
*
@@ -630,7 +633,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
//get option count info.
$form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
if ($form->_priceSet['optionsCountTotal']) {
- $optionsCountDetails = array();
+ $optionsCountDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
foreach ($field['options'] as $option) {
@@ -644,7 +647,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
//get option max value info.
$optionsMaxValueTotal = 0;
- $optionsMaxValueDetails = array();
+ $optionsMaxValueDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
@@ -698,13 +701,13 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
$amount_override = NULL;
if ($component) {
- $autoRenew = array();
+ $autoRenew = [];
$autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
}
if ($priceSetID) {
$priceFields = self::filterPriceFieldsFromParams($priceSetID, $params);
- if (count($priceFields) == 1 && !empty($params['total_amount'])) {
- $amount_override = $params['total_amount'];
+ if (count($priceFields) == 1) {
+ $amount_override = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
}
}
foreach ($fields as $id => $field) {
@@ -718,8 +721,8 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
switch ($field['html_type']) {
case 'Text':
$firstOption = reset($field['options']);
- $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
+ $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
$optionValueId = key($field['options']);
if (CRM_Utils_Array::value('name', $field['options'][$optionValueId]) == 'contribution_amount') {
@@ -730,7 +733,7 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
$field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
}
}
- if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
+ if (!empty($field['options'][$optionValueId]['tax_rate'])) {
$lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
}
$totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
@@ -739,15 +742,15 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
case 'Radio':
//special case if user select -none-
if ($params["price_{$id}"] <= 0) {
- continue;
+ break;
}
- $params["price_{$id}"] = array($params["price_{$id}"] => 1);
+ $params["price_{$id}"] = [$params["price_{$id}"] => 1];
$optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, $amount_override);
- if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
+ if (!empty($field['options'][$optionValueId]['tax_rate'])) {
$lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
- if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
+ if ($amount_override) {
$lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
}
}
@@ -764,11 +767,11 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
break;
case 'Select':
- $params["price_{$id}"] = array($params["price_{$id}"] => 1);
+ $params["price_{$id}"] = [$params["price_{$id}"] => 1];
$optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
- if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
+ if (!empty($field['options'][$optionValueId]['tax_rate'])) {
$lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
}
$totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
@@ -783,9 +786,9 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
case 'CheckBox':
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
foreach ($params["price_{$id}"] as $optionId => $option) {
- if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
+ if (!empty($field['options'][$optionId]['tax_rate'])) {
$lineItem = self::setLineItem($field, $lineItem, $optionId, $totalTax);
}
$totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
@@ -801,7 +804,7 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
}
}
- $amount_level = array();
+ $amount_level = [];
$totalParticipant = 0;
if (is_array($lineItem)) {
foreach ($lineItem as $values) {
@@ -838,9 +841,8 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
$params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
}
}
- // @todo this was a fix for CRM-16460 but is too deep in the system for formatting
- // and probably causes negative amounts to save as $0 depending on server config.
- $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
+
+ $params['amount'] = $totalPrice;
$params['tax_amount'] = $totalTax;
if ($component) {
foreach ($autoRenew as $dontCare => $eachAmount) {
@@ -872,7 +874,7 @@ public static function getAmountLevelText($params) {
$priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
$displayParticipantCount = NULL;
- $amount_level = array();
+ $amount_level = [];
foreach ($priceFieldMetadata['fields'] as $field) {
if (!empty($priceFieldSelection[$field['id']])) {
$qtyString = '';
@@ -903,7 +905,7 @@ public static function getAmountLevelText($params) {
*/
public static function filterPriceFieldsFromParams($priceSetID, $params) {
$priceSet = self::getCachedPriceSetDetail($priceSetID);
- $return = array();
+ $return = [];
foreach ($priceSet['fields'] as $field) {
if (!empty($params['price_' . $field['id']])) {
$return[$field['id']] = $params['price_' . $field['id']];
@@ -954,10 +956,10 @@ public static function buildPriceSet(&$form) {
$validFieldsOnly = TRUE;
$className = CRM_Utils_System::getClassName($form);
- if (in_array($className, array(
+ if (in_array($className, [
'CRM_Contribute_Form_Contribution',
'CRM_Member_Form_Membership',
- ))) {
+ ])) {
$validFieldsOnly = FALSE;
}
@@ -976,13 +978,13 @@ public static function buildPriceSet(&$form) {
// Mark which field should have the auto-renew checkbox, if any. CRM-18305
if (!empty($form->_membershipTypeValues) && is_array($form->_membershipTypeValues)) {
- $autoRenewMembershipTypes = array();
+ $autoRenewMembershipTypes = [];
foreach ($form->_membershipTypeValues as $membershiptTypeValue) {
if ($membershiptTypeValue['auto_renew']) {
$autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
}
}
- foreach ($form->_priceSet['fields'] as &$field) {
+ foreach ($form->_priceSet['fields'] as $field) {
if (array_key_exists('options', $field) && is_array($field['options'])) {
foreach ($field['options'] as $option) {
if (!empty($option['membership_type_id'])) {
@@ -1012,19 +1014,9 @@ public static function buildPriceSet(&$form) {
else {
$feeBlock = &$form->_priceSet['fields'];
}
- if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
- foreach ($feeBlock as $key => $value) {
- foreach ($value['options'] as $k => $options) {
- if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
- unset($feeBlock[$key]['options'][$k]);
- }
- }
- if (empty($feeBlock[$key]['options'])) {
- unset($feeBlock[$key]);
- }
- }
- }
- // call the hook.
+
+ self::applyACLFinancialTypeStatusToFeeBlock($feeBlock);
+ // Call the buildAmount hook.
CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
// CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
@@ -1033,6 +1025,11 @@ public static function buildPriceSet(&$form) {
$adminFieldVisible = TRUE;
}
+ $hideAdminValues = TRUE;
+ if (CRM_Core_Permission::check('edit contributions')) {
+ $hideAdminValues = FALSE;
+ }
+
foreach ($feeBlock as $id => $field) {
if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
(CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
@@ -1046,9 +1043,19 @@ public static function buildPriceSet(&$form) {
$form->assign('ispricelifetime', TRUE);
}
}
+
+ $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
+
if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
continue;
}
+ elseif ($hideAdminValues && !in_array($className, $formClasses)) {
+ foreach ($options as $key => $currentOption) {
+ if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField::getVisibilityOptionID('admin')) {
+ unset($options[$key]);
+ }
+ }
+ }
if (!empty($options)) {
CRM_Price_BAO_PriceField::addQuickFormElement($form,
'price_' . $field['id'],
@@ -1063,6 +1070,29 @@ public static function buildPriceSet(&$form) {
}
}
+ /**
+ * Apply ACLs on Financial Type to the price options in a fee block.
+ *
+ * @param array $feeBlock
+ * Fee block: array of price fields.
+ *
+ * @return void
+ */
+ public static function applyACLFinancialTypeStatusToFeeBlock(&$feeBlock) {
+ if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
+ foreach ($feeBlock as $key => $value) {
+ foreach ($value['options'] as $k => $options) {
+ if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
+ unset($feeBlock[$key]['options'][$k]);
+ }
+ }
+ if (empty($feeBlock[$key]['options'])) {
+ unset($feeBlock[$key]);
+ }
+ }
+ }
+ }
+
/**
* Check the current Membership having end date null.
*
@@ -1076,7 +1106,7 @@ public static function checkCurrentMembership(&$options, $userid) {
if (!$userid || empty($options)) {
return FALSE;
}
- static $_contact_memberships = array();
+ static $_contact_memberships = [];
$checkLifetime = FALSE;
foreach ($options as $key => $value) {
if (!empty($value['membership_type_id'])) {
@@ -1240,25 +1270,27 @@ public static function getFieldIds($id) {
*/
public static function copy($id) {
$maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
-
- $title = ts('[Copy id %1]', array(1 => $maxId + 1));
- $fieldsFix = array(
- 'suffix' => array(
- 'title' => ' ' . $title,
- 'name' => '__Copy_id_' . ($maxId + 1) . '_',
- ),
- );
-
- $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
- array('id' => $id),
+ $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
+
+ $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
+ $title = ts('[Copy id %1]', [1 => $maxId + 1]);
+ $fieldsFix = [
+ 'replace' => [
+ 'title' => trim($newTitle) . ' ' . $title,
+ 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId + 1),
+ ],
+ ];
+
+ $copy = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
+ ['id' => $id],
NULL,
$fieldsFix
);
//copying all the blocks pertaining to the price set
- $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
- array('price_set_id' => $id),
- array('price_set_id' => $copy->id)
+ $copyPriceField = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
+ ['price_set_id' => $id],
+ ['price_set_id' => $copy->id]
);
if (!empty($copyPriceField)) {
$price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
@@ -1266,8 +1298,8 @@ public static function copy($id) {
//copy option group and values
foreach ($price as $originalId => $copyId) {
CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
- array('price_field_id' => $originalId),
- array('price_field_id' => $copyId)
+ ['price_field_id' => $originalId],
+ ['price_field_id' => $copyId]
);
}
}
@@ -1317,7 +1349,7 @@ public static function getPricesetCount($sid, $onlyActive = TRUE) {
$where = 'AND value.is_active = 1 AND field.is_active = 1';
}
- static $pricesetFieldCount = array();
+ static $pricesetFieldCount = [];
if (!isset($pricesetFieldCount[$sid])) {
$sql = "
SELECT sum(value.count) as totalCount
@@ -1327,7 +1359,7 @@ public static function getPricesetCount($sid, $onlyActive = TRUE) {
WHERE pset.id = %1
$where";
- $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
+ $count = CRM_Core_DAO::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
$pricesetFieldCount[$sid] = ($count) ? $count : 0;
}
@@ -1341,14 +1373,14 @@ public static function getPricesetCount($sid, $onlyActive = TRUE) {
*/
public static function getMembershipCount($ids) {
$queryString = "
-SELECT count( pfv.id ) AS count, pfv.id AS id
+SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
FROM civicrm_price_field_value pfv
INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
WHERE pfv.id IN ( $ids )
-GROUP BY mt.member_of_contact_id";
+GROUP BY mt.member_of_contact_id ";
$crmDAO = CRM_Core_DAO::executeQuery($queryString);
- $count = array();
+ $count = [];
while ($crmDAO->fetch()) {
$count[$crmDAO->id] = $crmDAO->count;
@@ -1382,7 +1414,7 @@ public static function checkAutoRenewForPriceSet($priceSetId) {
AND pfv.is_active = 1
ORDER BY price_field_id';
- $params = array(1 => array($priceSetId, 'Integer'));
+ $params = [1 => [$priceSetId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
@@ -1393,7 +1425,7 @@ public static function checkAutoRenewForPriceSet($priceSetId) {
}
$autoRenewOption = 2;
- $priceFields = array();
+ $priceFields = [];
while ($dao->fetch()) {
if (!$dao->auto_renew) {
// If any one can't be renewed none can.
@@ -1436,10 +1468,10 @@ public static function getRecurDetails($priceSetId) {
INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
WHERE pf.price_set_id = %1 LIMIT 1';
- $params = array(1 => array($priceSetId, 'Integer'));
+ $params = [1 => [$priceSetId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$dao->fetch();
- return array($dao->duration_interval, $dao->duration_unit);
+ return [$dao->duration_interval, $dao->duration_unit];
}
/**
@@ -1457,8 +1489,8 @@ public static function eventPriceSetDomainID() {
* @param bool $isQuickConfig we want to set the is_quick_config field.
* Value we want to set the is_quick_config field.
*
- * @return Object
- * DAO object on success, null otherwise
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsQuickConfig($id, $isQuickConfig) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
@@ -1497,15 +1529,15 @@ public static function getMembershipTypesFromPriceSet($id) {
WHERE ps.id = %1
";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $membershipTypes = array(
- 'all' => array(),
- 'autorenew' => array(),
- 'autorenew_required' => array(),
- 'autorenew_optional' => array(),
- );
+ $membershipTypes = [
+ 'all' => [],
+ 'autorenew' => [],
+ 'autorenew_required' => [],
+ 'autorenew_optional' => [],
+ ];
while ($dao->fetch()) {
if (empty($dao->membership_type_id)) {
continue;
@@ -1546,12 +1578,12 @@ public static function copyPriceSet($baoName, $id, $newId) {
CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
}
else {
- $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
- array(
+ $copyPriceSet = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
+ [
'entity_id' => $id,
'entity_table' => $baoName,
- ),
- array('entity_id' => $newId)
+ ],
+ ['entity_id' => $newId]
);
}
// copy event discount
@@ -1563,13 +1595,13 @@ public static function copyPriceSet($baoName, $id, $newId) {
CRM_Core_DAO::copyGeneric(
'CRM_Core_DAO_Discount',
- array(
+ [
'id' => $discountId,
- ),
- array(
+ ],
+ [
'entity_id' => $newId,
'price_set_id' => $copyPriceSet->id,
- )
+ ]
);
}
}
@@ -1626,7 +1658,7 @@ public static function parseFirstPriceSetValueIDFromParams($params) {
*/
public static function parsePriceSetValueIDsFromParams($params) {
$priceSetParams = self::parsePriceSetArrayFromParams($params);
- $priceSetValueIDs = array();
+ $priceSetValueIDs = [];
foreach ($priceSetParams as $priceSetParam) {
foreach (array_keys($priceSetParam) as $priceValueID) {
$priceSetValueIDs[] = $priceValueID;
@@ -1644,7 +1676,7 @@ public static function parsePriceSetValueIDsFromParams($params) {
* Array of price fields filtered from the params.
*/
public static function parsePriceSetArrayFromParams($params) {
- $priceSetParams = array();
+ $priceSetParams = [];
foreach ($params as $field => $value) {
$parts = explode('_', $field);
if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
@@ -1688,12 +1720,12 @@ public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem
* )
*/
public static function getFormsUsingPriceSet($id) {
- $forms = array();
+ $forms = [];
$queryString = "
SELECT entity_table, entity_id
FROM civicrm_price_set_entity
WHERE price_set_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
while ($crmFormDAO->fetch()) {
@@ -1719,7 +1751,7 @@ public static function getFormsUsingPriceSet($id) {
* @throws \Exception
*/
protected static function reformatUsedByFormsWithEntityData($forms) {
- $usedBy = array();
+ $usedBy = [];
foreach ($forms as $table => $entities) {
switch ($table) {
case 'civicrm_event':
diff --git a/CRM/Price/DAO/LineItem.php b/CRM/Price/DAO/LineItem.php
index 2f05c853d160..46b36ce92530 100644
--- a/CRM/Price/DAO/LineItem.php
+++ b/CRM/Price/DAO/LineItem.php
@@ -1,416 +1,429 @@
__table = 'civicrm_line_item';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_id', 'civicrm_price_field', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_value_id', 'civicrm_price_field_value', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_id', 'civicrm_price_field', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_value_id', 'civicrm_price_field_value', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item ID') ,
- 'description' => 'Line Item',
- 'required' => true,
+ 'title' => ts('Line Item ID'),
+ 'description' => ts('Line Item'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_line_item.id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Line Item Entity Type') ,
- 'description' => 'table which has the transaction',
- 'required' => true,
+ 'title' => ts('Line Item Entity Type'),
+ 'description' => ts('table which has the transaction'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_line_item.entity_table',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Entity') ,
- 'description' => 'entry in table',
- 'required' => true,
+ 'title' => ts('Line Item Entity'),
+ 'description' => ts('entry in table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_line_item.entity_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Contribution') ,
- 'description' => 'FK to civicrm_contribution',
+ 'title' => ts('Line Item Contribution'),
+ 'description' => ts('FK to civicrm_contribution'),
+ 'where' => 'civicrm_line_item.contribution_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- 'price_field_id' => array(
+ ],
+ 'price_field_id' => [
'name' => 'price_field_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Price Field') ,
- 'description' => 'FK to civicrm_price_field',
+ 'title' => ts('Line Item Price Field'),
+ 'description' => ts('FK to civicrm_price_field'),
+ 'where' => 'civicrm_line_item.price_field_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceField',
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Line Item Label') ,
- 'description' => 'descriptive label for item - from price_field_value.label',
+ 'title' => ts('Line Item Label'),
+ 'description' => ts('descriptive label for item - from price_field_value.label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_line_item.label',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'qty' => array(
+ ],
+ ],
+ 'qty' => [
'name' => 'qty',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Line Item Quantity') ,
- 'description' => 'How many items ordered',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Line Item Quantity'),
+ 'description' => ts('How many items ordered'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_line_item.qty',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'unit_price' => array(
+ ],
+ ],
+ 'unit_price' => [
'name' => 'unit_price',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Unit Price') ,
- 'description' => 'price of each item',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Unit Price'),
+ 'description' => ts('price of each item'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_line_item.unit_price',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'line_total' => array(
+ ],
+ ],
+ 'line_total' => [
'name' => 'line_total',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Line Item Total') ,
- 'description' => 'qty * unit_price',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Line Item Total'),
+ 'description' => ts('qty * unit_price'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_line_item.line_total',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'participant_count' => array(
+ ],
+ 'participant_count' => [
'name' => 'participant_count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Participant Count') ,
- 'description' => 'Participant count for field',
+ 'title' => ts('Line Item Participant Count'),
+ 'description' => ts('Participant count for field'),
+ 'where' => 'civicrm_line_item.participant_count',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'price_field_value_id' => array(
+ ],
+ ],
+ 'price_field_value_id' => [
'name' => 'price_field_value_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Option') ,
- 'description' => 'FK to civicrm_price_field_value',
+ 'title' => ts('Line Item Option'),
+ 'description' => ts('FK to civicrm_price_field_value'),
+ 'where' => 'civicrm_line_item.price_field_value_id',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceFieldValue',
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_line_item.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'non_deductible_amount' => array(
+ ],
+ ],
+ 'non_deductible_amount' => [
'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Non-deductible Amount') ,
- 'description' => 'Portion of total amount which is NOT tax deductible.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Non-deductible Amount'),
+ 'description' => ts('Portion of total amount which is NOT tax deductible.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_line_item.non_deductible_amount',
+ 'headerPattern' => '/non?.?deduct/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'default' => '0.0',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'tax_amount' => array(
+ ],
+ ],
+ 'tax_amount' => [
'name' => 'tax_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Tax Amount') ,
- 'description' => 'tax of each item',
- 'precision' => array(
+ 'title' => ts('Tax Amount'),
+ 'description' => ts('tax of each item'),
+ 'precision' => [
20,
- 2
- ) ,
- 'import' => true,
+ 2,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_line_item.tax_amount',
'headerPattern' => '/tax(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -418,10 +431,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'line_item', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'line_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -429,38 +443,44 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'line_item', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'line_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity' => array(
+ $indices = [
+ 'index_entity' => [
'name' => 'index_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_line_item::0::entity_table::entity_id',
- ) ,
- 'UI_line_item_value' => array(
+ ],
+ 'UI_line_item_value' => [
'name' => 'UI_line_item_value',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
2 => 'contribution_id',
3 => 'price_field_value_id',
4 => 'price_field_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_line_item::1::entity_table::entity_id::contribution_id::price_field_value_id::price_field_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceField.php b/CRM/Price/DAO/PriceField.php
index b9af981d7956..310c8d3bfd85 100644
--- a/CRM/Price/DAO/PriceField.php
+++ b/CRM/Price/DAO/PriceField.php
@@ -1,465 +1,485 @@
1)
*
- * @var boolean
+ * @var bool
*/
public $is_required;
+
/**
* If non-zero, do not show this field before the date specified
*
* @var datetime
*/
public $active_on;
+
/**
* If non-zero, do not show this field after the date specified
*
* @var datetime
*/
public $expire_on;
+
/**
* Optional scripting attributes for field
*
* @var string
*/
public $javascript;
+
/**
* Implicit FK to civicrm_option_group with name = 'visibility'
*
- * @var int unsigned
+ * @var int
*/
public $visibility_id;
+
/**
* Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_set_id', 'civicrm_price_set', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_set_id', 'civicrm_price_set', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field ID') ,
- 'description' => 'Price Field',
- 'required' => true,
+ 'title' => ts('Price Field ID'),
+ 'description' => ts('Price Field'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field.id',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- ) ,
- 'price_set_id' => array(
+ ],
+ 'price_set_id' => [
'name' => 'price_set_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set') ,
- 'description' => 'FK to civicrm_price_set',
- 'required' => true,
+ 'title' => ts('Price Set'),
+ 'description' => ts('FK to civicrm_price_set'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field.price_set_id',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceSet',
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Variable name/programmatic handle for this field.',
- 'required' => true,
+ 'title' => ts('Name'),
+ 'description' => ts('Variable name/programmatic handle for this field.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.name',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'label' => array(
+ ],
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Text for form field label (also friendly name for administering this field).',
- 'required' => true,
+ 'title' => ts('Label'),
+ 'description' => ts('Text for form field label (also friendly name for administering this field).'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.label',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'html_type' => array(
+ ],
+ ],
+ 'html_type' => [
'name' => 'html_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Html Type') ,
- 'required' => true,
+ 'title' => ts('Html Type'),
+ 'required' => TRUE,
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_price_field.html_type',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Price_BAO_PriceField::htmlTypes',
- )
- ) ,
- 'is_enter_qty' => array(
+ ],
+ ],
+ 'is_enter_qty' => [
'name' => 'is_enter_qty',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Quantity Required?') ,
- 'description' => 'Enter a quantity for this field?',
+ 'title' => ts('Price Field Quantity Required?'),
+ 'description' => ts('Enter a quantity for this field?'),
+ 'where' => 'civicrm_price_field.is_enter_qty',
+ 'default' => '0',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Field Pre Text') ,
- 'description' => 'Description and/or help text to display before this field.',
+ 'title' => ts('Price Field Pre Text'),
+ 'description' => ts('Description and/or help text to display before this field.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_field.help_pre',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Field Post Text') ,
- 'description' => 'Description and/or help text to display after this field.',
+ 'title' => ts('Price Field Post Text'),
+ 'description' => ts('Description and/or help text to display after this field.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_field.help_post',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'Order in which the fields should appear',
+ 'title' => ts('Order'),
+ 'description' => ts('Order in which the fields should appear'),
+ 'where' => 'civicrm_price_field.weight',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'is_display_amounts' => array(
+ ],
+ ],
+ 'is_display_amounts' => [
'name' => 'is_display_amounts',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Show Amounts?') ,
- 'description' => 'Should the price be displayed next to the label for each option?',
+ 'title' => ts('Price Field Show Amounts?'),
+ 'description' => ts('Should the price be displayed next to the label for each option?'),
+ 'where' => 'civicrm_price_field.is_display_amounts',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'options_per_line' => array(
+ ],
+ ],
+ 'options_per_line' => [
'name' => 'options_per_line',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Options per Row') ,
- 'description' => 'number of options per line for checkbox and radio',
+ 'title' => ts('Price Field Options per Row'),
+ 'description' => ts('number of options per line for checkbox and radio'),
+ 'where' => 'civicrm_price_field.options_per_line',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Is Active?') ,
- 'description' => 'Is this price field active',
+ 'title' => ts('Price Field Is Active?'),
+ 'description' => ts('Is this price field active'),
+ 'where' => 'civicrm_price_field.is_active',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_required' => array(
+ ],
+ ],
+ 'is_required' => [
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field is Required?') ,
- 'description' => 'Is this price field required (value must be > 1)',
+ 'title' => ts('Price Field is Required?'),
+ 'description' => ts('Is this price field required (value must be > 1)'),
+ 'where' => 'civicrm_price_field.is_required',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'active_on' => array(
+ ],
+ ],
+ 'active_on' => [
'name' => 'active_on',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Price Field Start Date') ,
- 'description' => 'If non-zero, do not show this field before the date specified',
+ 'title' => ts('Price Field Start Date'),
+ 'description' => ts('If non-zero, do not show this field before the date specified'),
+ 'where' => 'civicrm_price_field.active_on',
'default' => 'NULL',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
- 'type' => 'CheckBox',
- ) ,
- ) ,
- 'expire_on' => array(
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'expire_on' => [
'name' => 'expire_on',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Price Field End Date') ,
- 'description' => 'If non-zero, do not show this field after the date specified',
+ 'title' => ts('Price Field End Date'),
+ 'description' => ts('If non-zero, do not show this field after the date specified'),
+ 'where' => 'civicrm_price_field.expire_on',
'default' => 'NULL',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'javascript' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'javascript' => [
'name' => 'javascript',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Field Javascript') ,
- 'description' => 'Optional scripting attributes for field',
+ 'title' => ts('Price Field Javascript'),
+ 'description' => ts('Optional scripting attributes for field'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.javascript',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'visibility_id' => array(
+ ],
+ ],
+ 'visibility_id' => [
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Visibility') ,
- 'description' => 'Implicit FK to civicrm_option_group with name = \'visibility\'',
+ 'title' => ts('Price Field Visibility'),
+ 'description' => ts('Implicit FK to civicrm_option_group with name = \'visibility\''),
+ 'where' => 'civicrm_price_field.visibility_id',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
- )
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -467,10 +487,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -478,24 +499,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_name' => array(
+ $indices = [
+ 'index_name' => [
'name' => 'index_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_price_field::0::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceFieldValue.php b/CRM/Price/DAO/PriceFieldValue.php
index 2b3a301f8a28..570af072cefe 100644
--- a/CRM/Price/DAO/PriceFieldValue.php
+++ b/CRM/Price/DAO/PriceFieldValue.php
@@ -1,472 +1,521 @@
Price field option description.
+ * Price field option description.
*
* @var text
*/
public $description;
+
/**
* Price field option pre help text.
*
* @var text
*/
public $help_pre;
+
/**
* Price field option post field help.
*
* @var text
*/
public $help_post;
+
/**
* Price field option amount
*
- * @var string
+ * @var float
*/
public $amount;
+
/**
* Number of participants per field option
*
- * @var int unsigned
+ * @var int
*/
public $count;
+
/**
* Max number of participants per field options
*
- * @var int unsigned
+ * @var int
*/
public $max_value;
+
/**
* Order in which the field options should appear
*
* @var int
*/
public $weight;
+
/**
* FK to Membership Type
*
- * @var int unsigned
+ * @var int
*/
public $membership_type_id;
+
/**
* Number of terms for this membership
*
- * @var int unsigned
+ * @var int
*/
public $membership_num_terms;
+
/**
* Is this default price field option
*
- * @var boolean
+ * @var bool
*/
public $is_default;
+
/**
* Is this price field value active
*
- * @var boolean
+ * @var bool
*/
public $is_active;
+
/**
* FK to Financial Type.
*
- * @var int unsigned
+ * @var int
*/
public $financial_type_id;
+
/**
* Portion of total amount which is NOT tax deductible.
*
* @var float
*/
public $non_deductible_amount;
+
+ /**
+ * Implicit FK to civicrm_option_group with name = 'visibility'
+ *
+ * @var int
+ */
+ public $visibility_id;
+
/**
* Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field_value';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_id', 'civicrm_price_field', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_id', 'civicrm_price_field', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Value ID') ,
- 'description' => 'Price Field Value',
- 'required' => true,
+ 'title' => ts('Price Field Value ID'),
+ 'description' => ts('Price Field Value'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field_value.id',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- ) ,
- 'price_field_id' => array(
+ ],
+ 'price_field_id' => [
'name' => 'price_field_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field') ,
- 'description' => 'FK to civicrm_price_field',
- 'required' => true,
+ 'title' => ts('Price Field'),
+ 'description' => ts('FK to civicrm_price_field'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field_value.price_field_id',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceField',
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Price field option name',
+ 'title' => ts('Name'),
+ 'description' => ts('Price field option name'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field_value.name',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'label' => array(
+ ],
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Price field option label',
+ 'title' => ts('Label'),
+ 'description' => ts('Price field option label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field_value.label',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Description') ,
- 'description' => '>Price field option description.',
+ 'title' => ts('Description'),
+ 'description' => ts('Price field option description.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.description',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Help Pre') ,
- 'description' => 'Price field option pre help text.',
+ 'title' => ts('Help Pre'),
+ 'description' => ts('Price field option pre help text.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.help_pre',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Help Post') ,
- 'description' => 'Price field option post field help.',
+ 'title' => ts('Help Post'),
+ 'description' => ts('Price field option post field help.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.help_post',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'amount' => array(
+ ],
+ ],
+ 'amount' => [
'name' => 'amount',
- 'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Amount') ,
- 'description' => 'Price field option amount',
- 'required' => true,
- 'maxlength' => 512,
- 'size' => 8,
+ 'type' => CRM_Utils_Type::T_MONEY,
+ 'title' => ts('Amount'),
+ 'description' => ts('Price field option amount'),
+ 'required' => TRUE,
+ 'precision' => [
+ 18,
+ 9,
+ ],
+ 'where' => 'civicrm_price_field_value.amount',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'count' => array(
+ ],
+ ],
+ 'count' => [
'name' => 'count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Count') ,
- 'description' => 'Number of participants per field option',
+ 'title' => ts('Count'),
+ 'description' => ts('Number of participants per field option'),
+ 'where' => 'civicrm_price_field_value.count',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'max_value' => array(
+ ],
+ ],
+ 'max_value' => [
'name' => 'max_value',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Value') ,
- 'description' => 'Max number of participants per field options',
+ 'title' => ts('Max Value'),
+ 'description' => ts('Max number of participants per field options'),
+ 'where' => 'civicrm_price_field_value.max_value',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'Order in which the field options should appear',
+ 'title' => ts('Order'),
+ 'description' => ts('Order in which the field options should appear'),
+ 'where' => 'civicrm_price_field_value.weight',
'default' => '1',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'membership_type_id' => array(
+ ],
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type') ,
- 'description' => 'FK to Membership Type',
+ 'title' => ts('Membership Type'),
+ 'description' => ts('FK to Membership Type'),
+ 'where' => 'civicrm_price_field_value.membership_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'membership_num_terms' => array(
+ ],
+ ],
+ 'membership_num_terms' => [
'name' => 'membership_num_terms',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Num Terms') ,
- 'description' => 'Number of terms for this membership',
+ 'title' => ts('Membership Num Terms'),
+ 'description' => ts('Number of terms for this membership'),
+ 'where' => 'civicrm_price_field_value.membership_num_terms',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_default' => array(
+ ],
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Default Price Field Option?') ,
- 'description' => 'Is this default price field option',
+ 'title' => ts('Is Default Price Field Option?'),
+ 'description' => ts('Is this default price field option'),
+ 'where' => 'civicrm_price_field_value.is_default',
+ 'default' => '0',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Value is Active') ,
- 'description' => 'Is this price field value active',
+ 'title' => ts('Price Field Value is Active'),
+ 'description' => ts('Is this price field value active'),
+ 'where' => 'civicrm_price_field_value.is_active',
'default' => '1',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_price_field_value.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'non_deductible_amount' => array(
+ ],
+ ],
+ 'non_deductible_amount' => [
'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Non-deductible Amount') ,
- 'description' => 'Portion of total amount which is NOT tax deductible.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Non-deductible Amount'),
+ 'description' => ts('Portion of total amount which is NOT tax deductible.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
- 2
- ) ,
+ 2,
+ ],
+ 'where' => 'civicrm_price_field_value.non_deductible_amount',
+ 'headerPattern' => '/non?.?deduct/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'default' => '0.0',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ 'visibility_id' => [
+ 'name' => 'visibility_id',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Price Field Option Visibility'),
+ 'description' => ts('Implicit FK to civicrm_option_group with name = \'visibility\''),
+ 'where' => 'civicrm_price_field_value.visibility_id',
+ 'default' => '1',
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
+ 'optionGroupName' => 'visibility',
+ 'optionEditPath' => 'civicrm/admin/options/visibility',
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -474,10 +523,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field_value', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field_value', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -485,15 +535,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field_value', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field_value', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceSet.php b/CRM/Price/DAO/PriceSet.php
index e310a831a87c..a4b704dd7a1a 100644
--- a/CRM/Price/DAO/PriceSet.php
+++ b/CRM/Price/DAO/PriceSet.php
@@ -1,397 +1,413 @@
__table = 'civicrm_price_set';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set ID') ,
- 'description' => 'Price Set',
- 'required' => true,
+ 'title' => ts('Price Set'),
+ 'description' => ts('Price Set'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set.id',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set Domain') ,
- 'description' => 'Which Domain is this price-set for',
+ 'title' => ts('Price Set Domain'),
+ 'description' => ts('Which Domain is this price-set for'),
+ 'where' => 'civicrm_price_set.domain_id',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'name' => array(
+ ],
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Variable name/programmatic handle for this set of price fields.',
- 'required' => true,
+ 'title' => ts('Name'),
+ 'description' => ts('Variable name/programmatic handle for this set of price fields.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.name',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'title' => array(
+ ],
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Title') ,
- 'description' => 'Displayed title for the Price Set.',
- 'required' => true,
+ 'title' => ts('Price Set Title'),
+ 'description' => ts('Displayed title for the Price Set.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.title',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Set Is Active?') ,
- 'description' => 'Is this price set active',
+ 'title' => ts('Price Set Is Active?'),
+ 'description' => ts('Is this price set active'),
+ 'where' => 'civicrm_price_set.is_active',
'default' => '1',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Set Pre Help') ,
- 'description' => 'Description and/or help text to display before fields in form.',
+ 'title' => ts('Price Set Pre Help'),
+ 'description' => ts('Description and/or help text to display before fields in form.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_set.help_pre',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Set Post Help') ,
- 'description' => 'Description and/or help text to display after fields in form.',
+ 'title' => ts('Price Set Post Help'),
+ 'description' => ts('Description and/or help text to display after fields in form.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_set.help_post',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'javascript' => array(
+ ],
+ ],
+ 'javascript' => [
'name' => 'javascript',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Javascript') ,
- 'description' => 'Optional Javascript script function(s) included on the form with this price_set. Can be used for conditional',
+ 'title' => ts('Price Set Javascript'),
+ 'description' => ts('Optional Javascript script function(s) included on the form with this price_set. Can be used for conditional'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_price_set.javascript',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'extends' => array(
+ ],
+ ],
+ 'extends' => [
'name' => 'extends',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Extends') ,
- 'description' => 'What components are using this price set?',
- 'required' => true,
+ 'title' => ts('Price Set Extends'),
+ 'description' => ts('What components are using this price set?'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.extends',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_component',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'financial_type_id' => array(
+ ],
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type(for membership price sets only).',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type(for membership price sets only).'),
+ 'where' => 'civicrm_price_set.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'is_quick_config' => array(
+ ],
+ ],
+ 'is_quick_config' => [
'name' => 'is_quick_config',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Price Set Quick Config?') ,
- 'description' => 'Is set if edited on Contribution or Event Page rather than through Manage Price Sets',
+ 'title' => ts('Is Price Set Quick Config?'),
+ 'description' => ts('Is set if edited on Contribution or Event Page rather than through Manage Price Sets'),
+ 'where' => 'civicrm_price_set.is_quick_config',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_reserved' => array(
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Set Is Reserved') ,
- 'description' => 'Is this a predefined system price set (i.e. it can not be deleted, edited)?',
+ 'title' => ts('Price Set Is Reserved'),
+ 'description' => ts('Is this a predefined system price set (i.e. it can not be deleted, edited)?'),
+ 'where' => 'civicrm_price_set.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'min_amount' => array(
+ ],
+ ],
+ 'min_amount' => [
'name' => 'min_amount',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Minimum Amount') ,
- 'description' => 'Minimum Amount required for this set.',
+ 'title' => ts('Minimum Amount'),
+ 'description' => ts('Minimum Amount required for this set.'),
+ 'where' => 'civicrm_price_set.min_amount',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -399,10 +415,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -410,25 +427,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_price_set::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceSetEntity.php b/CRM/Price/DAO/PriceSetEntity.php
index 41da550b5546..125a59f37a25 100644
--- a/CRM/Price/DAO/PriceSetEntity.php
+++ b/CRM/Price/DAO/PriceSetEntity.php
@@ -1,189 +1,181 @@
__table = 'civicrm_price_set_entity';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_set_id', 'civicrm_price_set', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_set_id', 'civicrm_price_set', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set Entity ID') ,
- 'description' => 'Price Set Entity',
- 'required' => true,
+ 'title' => ts('Price Set Entity ID'),
+ 'description' => ts('Price Set Entity'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Table which uses this price set',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Table which uses this price set'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_price_set_entity.entity_table',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity IF') ,
- 'description' => 'Item in table',
- 'required' => true,
+ 'title' => ts('Entity IF'),
+ 'description' => ts('Item in table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.entity_id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'price_set_id' => array(
+ ],
+ 'price_set_id' => [
'name' => 'price_set_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set') ,
- 'description' => 'price set being used',
- 'required' => true,
+ 'title' => ts('Price Set'),
+ 'description' => ts('price set being used'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.price_set_id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceSet',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -191,10 +183,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set_entity', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set_entity', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -202,26 +195,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set_entity', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set_entity', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_entity' => array(
+ $indices = [
+ 'UI_entity' => [
'name' => 'UI_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_price_set_entity::1::entity_table::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/Form/DeleteField.php b/CRM/Price/Form/DeleteField.php
index 20319b8591cf..23c5dbda7048 100644
--- a/CRM/Price/Form/DeleteField.php
+++ b/CRM/Price/Form/DeleteField.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Price Field'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -97,7 +97,7 @@ public function buildQuickForm() {
*/
public function postProcess() {
if (CRM_Price_BAO_PriceField::deleteField($this->_fid)) {
- CRM_Core_Session::setStatus(ts('The Price Field \'%1\' has been deleted.', array(1 => $this->_title)), '', 'success');
+ CRM_Core_Session::setStatus(ts('The Price Field \'%1\' has been deleted.', [1 => $this->_title]), '', 'success');
}
}
diff --git a/CRM/Price/Form/DeleteSet.php b/CRM/Price/Form/DeleteSet.php
index a4bb5a0d8a33..a9045f3da35d 100644
--- a/CRM/Price/Form/DeleteSet.php
+++ b/CRM/Price/Form/DeleteSet.php
@@ -1,9 +1,9 @@
assign('title', $this->_title);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Price Set'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -91,12 +91,12 @@ public function buildQuickForm() {
public function postProcess() {
if (CRM_Price_BAO_PriceSet::deleteSet($this->_sid)) {
CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has been deleted.',
- array(1 => $this->_title), ts('Deleted'), 'success'
+ [1 => $this->_title], ts('Deleted'), 'success'
));
}
else {
CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has not been deleted! You must delete all price fields in this set prior to deleting the set.',
- array(1 => $this->_title)
+ [1 => $this->_title]
), 'Unable to Delete', 'error');
}
}
diff --git a/CRM/Price/Form/Field.php b/CRM/Price/Form/Field.php
index f17e11ad1644..08ff9e40afb6 100644
--- a/CRM/Price/Form/Field.php
+++ b/CRM/Price/Form/Field.php
@@ -1,9 +1,9 @@
_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
- $breadCrumb = array(array('title' => ts('Price Set Fields'), 'url' => $url));
+ $breadCrumb = [['title' => ts('Price Set Fields'), 'url' => $url]];
- $this->_extendComponentId = array();
+ $this->_extendComponentId = [];
$extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
if ($extendComponentId) {
$this->_extendComponentId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
@@ -95,10 +96,10 @@ public function preProcess() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
// is it an edit operation ?
if (isset($this->_fid)) {
- $params = array('id' => $this->_fid);
+ $params = ['id' => $this->_fid];
$this->assign('fid', $this->_fid);
CRM_Price_BAO_PriceField::retrieve($params, $defaults);
$this->_sid = $defaults['price_set_id'];
@@ -106,7 +107,7 @@ public function setDefaultValues() {
// if text, retrieve price
if ($defaults['html_type'] == 'Text') {
$isActive = $defaults['is_active'];
- $valueParams = array('price_field_id' => $this->_fid);
+ $valueParams = ['price_field_id' => $this->_fid];
CRM_Price_BAO_PriceFieldValue::retrieve($valueParams, $defaults);
@@ -115,28 +116,18 @@ public function setDefaultValues() {
$defaults['is_active'] = $isActive;
}
- if (!empty($defaults['active_on'])) {
- list($defaults['active_on'],
- $defaults['active_on_time']
- ) = CRM_Utils_Date::setDateDefaults($defaults['active_on'], 'activityDateTime');
- }
-
- if (!empty($defaults['expire_on'])) {
- list($defaults['expire_on'],
- $defaults['expire_on_time']
- ) = CRM_Utils_Date::setDateDefaults($defaults['expire_on'], 'activityDateTime');
- }
}
else {
$defaults['is_active'] = 1;
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
$defaults['option_status[' . $i . ']'] = 1;
$defaults['option_weight[' . $i . ']'] = $i;
+ $defaults['option_visibility_id[' . $i . ']'] = 1;
}
}
if ($this->_action & CRM_Core_Action::ADD) {
- $fieldValues = array('price_set_id' => $this->_sid);
+ $fieldValues = ['price_set_id' => $this->_sid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceField', $fieldValues);
$defaults['options_per_line'] = 1;
$defaults['is_display_amounts'] = 1;
@@ -191,6 +182,11 @@ public function buildQuickForm() {
if (count($financialType)) {
$this->assign('financialType', $financialType);
}
+
+ //Visibility Type Options
+ $visibilityType = CRM_Core_PseudoConstant::visibility();
+ $this->assign('visibilityType', $visibilityType);
+
$enabledComponents = CRM_Core_Component::getEnabledComponents();
$eventComponentId = $memberComponentId = NULL;
if (array_key_exists('CiviEvent', $enabledComponents)) {
@@ -204,7 +200,7 @@ public function buildQuickForm() {
$this->add('select', 'financial_type_id',
ts('Financial Type'),
- array(' ' => ts('- select -')) + $financialType
+ [' ' => ts('- select -')] + $financialType
);
$this->assign('useForMember', FALSE);
@@ -272,7 +268,7 @@ public function buildQuickForm() {
'select',
'option_financial_type_id[' . $i . ']',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType
+ ['' => ts('- select -')] + $financialType
);
if (in_array($eventComponentId, $this->_extendComponentId)) {
// count
@@ -288,20 +284,21 @@ public function buildQuickForm() {
}
elseif (in_array($memberComponentId, $this->_extendComponentId)) {
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
- $js = array('onchange' => "calculateRowValues( $i );");
+ $js = ['onchange' => "calculateRowValues( $i );"];
$this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
- array('' => ' ') + $membershipTypes, FALSE, $js
+ ['' => ' '] + $membershipTypes, FALSE, $js
);
$this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array::value('membership_num_terms', $attributes));
}
// weight
- $this->add('text', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
+ $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
// is active ?
$this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
+ $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
$defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
//for checkbox handling of default option
@@ -315,22 +312,26 @@ public function buildQuickForm() {
$this->add('checkbox', 'is_display_amounts', ts('Display Amount?'));
// weight
- $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
+ $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// checkbox / radio options per line
$this->add('text', 'options_per_line', ts('Options Per Line'));
$this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
+ $this->add('textarea', 'help_pre', ts('Pre Field Help'),
+ CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
+ );
+
// help post, mask, attributes, javascript ?
- $this->add('textarea', 'help_post', ts('Field Help'),
+ $this->add('textarea', 'help_post', ts('Post Field Help'),
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
);
- $this->addDateTime('active_on', ts('Active On'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
// expire_on
- $this->addDateTime('expire_on', ts('Expire On'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
// is required ?
$this->add('checkbox', 'is_required', ts('Required?'));
@@ -339,27 +340,27 @@ public function buildQuickForm() {
$this->add('checkbox', 'is_active', ts('Active?'));
// add buttons
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
// is public?
$this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
// add a form rule to check default value
- $this->addFormRule(array('CRM_Price_Form_Field', 'formRule'), $this);
+ $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
@@ -368,7 +369,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'")
+ ['onclick' => "location.href='$url'"]
);
}
}
@@ -389,7 +390,7 @@ public function buildQuickForm() {
public static function formRule($fields, $files, $form) {
// all option fields are of type "money"
- $errors = array();
+ $errors = [];
/** Check the option values entered
* Appropriate values are required for the selected datatype
@@ -421,7 +422,7 @@ public static function formRule($fields, $files, $form) {
}
if ((is_numeric(CRM_Utils_Array::value('count', $fields)) &&
- CRM_Utils_Array::value('count', $fields) == 0
+ empty($fields['count'])
) &&
(CRM_Utils_Array::value('html_type', $fields) == 'Text')
) {
@@ -431,9 +432,10 @@ public static function formRule($fields, $files, $form) {
if ($form->_action & CRM_Core_Action::ADD) {
if ($fields['html_type'] != 'Text') {
$countemptyrows = 0;
- $_flagOption = $_rowError = 0;
+ $publicOptionCount = $_flagOption = $_rowError = 0;
$_showHide = new CRM_Core_ShowHideBlocks('', '');
+ $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, ['labelColumn' => 'name']);
for ($index = 1; $index <= self::NUM_OPTION; $index++) {
@@ -519,6 +521,12 @@ public static function formRule($fields, $files, $form) {
$_showHide->addHide($hideBlock);
}
+ if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel || !$noAmount)) {
+ if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
+ $publicOptionCount++;
+ }
+ }
+
$_flagOption = $_emptyRow = 0;
}
@@ -526,7 +534,7 @@ public static function formRule($fields, $files, $form) {
// check for checkboxes allowing user to select multiple memberships from same membership organization
if ($fields['html_type'] == 'CheckBox') {
$foundDuplicate = FALSE;
- $orgIds = array();
+ $orgIds = [];
foreach ($memTypesIDS as $key => $val) {
$org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
if (in_array($org[$val], $orgIds)) {
@@ -566,6 +574,29 @@ public static function formRule($fields, $files, $form) {
$errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
$_flagOption = 1;
}
+
+ if ($visibilityOptions[$fields['visibility_id']] == 'public' && $publicOptionCount == 0) {
+ $errors['visibility_id'] = ts('You have selected to make this field public but have not enabled any public price options. Please update your selections to include a public price option, or make this field admin visibility only.');
+ for ($index = 1; $index <= self::NUM_OPTION; $index++) {
+ if (!empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index])) {
+ $errors["option_visibility_id[{$index}]"] = ts('Public field should at least have one public option.');
+ }
+ }
+ }
+
+ if ($visibilityOptions[$fields['visibility_id']] == 'admin' && $publicOptionCount > 0) {
+ $errors['visibility_id'] = ts('Field with \'Admin\' visibility should only contain \'Admin\' options.');
+
+ for ($index = 1; $index <= self::NUM_OPTION; $index++) {
+
+ $isOptionSet = !empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index]);
+ $currentOptionVisibility = CRM_Utils_Array::value($fields['option_visibility_id'][$index], $visibilityOptions);
+
+ if ($isOptionSet && $currentOptionVisibility == 'public') {
+ $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
+ }
+ }
+ }
}
elseif (!empty($fields['max_value']) &&
!empty($fields['count']) &&
@@ -580,11 +611,11 @@ public static function formRule($fields, $files, $form) {
}
if (empty($fields['option_name'])) {
- $fields['option_amount'] = array();
+ $fields['option_amount'] = [];
}
if (empty($fields['option_label'])) {
- $fields['option_label'] = array();
+ $fields['option_label'] = [];
}
}
@@ -602,18 +633,6 @@ public function postProcess() {
$params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
- if (isset($params['active_on'])) {
- $params['active_on'] = CRM_Utils_Date::processDate($params['active_on'],
- CRM_Utils_Array::value('active_on_time', $params),
- TRUE
- );
- }
- if (isset($params['expire_on'])) {
- $params['expire_on'] = CRM_Utils_Date::processDate($params['expire_on'],
- CRM_Utils_Array::value('expire_on_time', $params),
- TRUE
- );
- }
$params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
$params['count'] = CRM_Utils_Array::value('count', $params, FALSE);
@@ -621,7 +640,7 @@ public function postProcess() {
$params['price_set_id'] = $this->_sid;
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $fieldValues = array('price_set_id' => $this->_sid);
+ $fieldValues = ['price_set_id' => $this->_sid];
$oldWeight = NULL;
if ($this->_fid) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'weight', 'id');
@@ -640,13 +659,14 @@ public function postProcess() {
$params['is_enter_qty'] = 1;
// modify params values as per the option group and option
// value
- $params['option_amount'] = array(1 => $params['price']);
- $params['option_label'] = array(1 => $params['label']);
- $params['option_count'] = array(1 => $params['count']);
- $params['option_max_value'] = array(1 => CRM_Utils_Array::value('max_value', $params));
+ $params['option_amount'] = [1 => $params['price']];
+ $params['option_label'] = [1 => $params['label']];
+ $params['option_count'] = [1 => $params['count']];
+ $params['option_max_value'] = [1 => CRM_Utils_Array::value('max_value', $params)];
//$params['option_description'] = array( 1 => $params['description'] );
- $params['option_weight'] = array(1 => $params['weight']);
- $params['option_financial_type_id'] = array(1 => $params['financial_type_id']);
+ $params['option_weight'] = [1 => $params['weight']];
+ $params['option_financial_type_id'] = [1 => $params['financial_type_id']];
+ $params['option_visibility_id'] = [1 => CRM_Utils_Array::value('visibility_id', $params)];
}
if ($this->_fid) {
@@ -658,7 +678,7 @@ public function postProcess() {
$priceField = CRM_Price_BAO_PriceField::create($params);
if (!is_a($priceField, 'CRM_Core_Error')) {
- CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', array(1 => $priceField->label)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label]), ts('Saved'), 'success');
}
$buttonName = $this->controller->getButtonName();
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Price/Form/Option.php b/CRM/Price/Form/Option.php
index 0bd160b25c13..3e52ab48c914 100644
--- a/CRM/Price/Form/Option.php
+++ b/CRM/Price/Form/Option.php
@@ -1,9 +1,9 @@
_action == CRM_Core_Action::DELETE) {
return NULL;
}
- $defaults = array();
+ $defaults = [];
if (isset($this->_oid)) {
- $params = array('id' => $this->_oid);
+ $params = ['id' => $this->_oid];
CRM_Price_BAO_PriceFieldValue::retrieve($params, $defaults);
// fix the display of the monetary value, CRM-4038
- $defaults['value'] = CRM_Utils_Money::format(CRM_Utils_Array::value('value', $defaults), NULL, '%a');
+ foreach ($this->_moneyFields as $field) {
+ $defaults[$field] = CRM_Utils_Money::format(CRM_Utils_Array::value($field, $defaults), NULL, '%a');
+ }
}
$memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
@@ -99,7 +108,7 @@ public function setDefaultValues() {
$defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'financial_type_id', 'id');;
}
if (!isset($defaults['weight']) || !$defaults['weight']) {
- $fieldValues = array('price_field_id' => $this->_fid);
+ $fieldValues = ['price_field_id' => $this->_fid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceFieldValue', $fieldValues);
$defaults['is_active'] = 1;
}
@@ -120,16 +129,16 @@ public function buildQuickForm() {
}
}
if ($this->_action == CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
return NULL;
}
else {
@@ -163,11 +172,11 @@ public function buildQuickForm() {
if ($memberComponentId == $extendComponentId) {
$this->assign('showMember', TRUE);
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
- $this->add('select', 'membership_type_id', ts('Membership Type'), array(
+ $this->add('select', 'membership_type_id', ts('Membership Type'), [
'' => ' ',
- ) + $membershipTypes, FALSE,
- array('onClick' => "calculateRowValues( );"));
- $this->add('text', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']);
+ ] + $membershipTypes, FALSE,
+ ['onClick' => "calculateRowValues( );"]);
+ $this->add('number', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']);
}
else {
$allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
@@ -175,10 +184,10 @@ public function buildQuickForm() {
if (in_array($eventComponentId, $allComponents)) {
$this->isEvent = TRUE;
// count
- $this->add('text', 'count', ts('Participant Count'));
+ $this->add('number', 'count', ts('Participant Count'));
$this->addRule('count', ts('Please enter a valid Max Participants.'), 'positiveInteger');
- $this->add('text', 'max_value', ts('Max Participants'));
+ $this->add('number', 'max_value', ts('Max Participants'));
$this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger');
}
@@ -193,7 +202,7 @@ public function buildQuickForm() {
'select',
'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType,
+ ['' => ts('- select -')] + $financialType,
TRUE
);
@@ -223,12 +232,15 @@ public function buildQuickForm() {
$this->add('textarea', 'help_post', ts('Post Option Help'));
// weight
- $this->add('text', 'weight', ts('Order'), NULL, TRUE);
+ $this->add('number', 'weight', ts('Order'), NULL, TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// is active ?
$this->add('checkbox', 'is_active', ts('Active?'));
+ // is public?
+ $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
+
//is default
$this->add('checkbox', 'is_default', ts('Default'));
@@ -241,31 +253,31 @@ public function buildQuickForm() {
}
}
// add buttons
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
- $this->addFormRule(array('CRM_Price_Form_Option', 'formRule'), $this);
+ $this->addFormRule(['CRM_Price_Form_Option', 'formRule'], $this);
}
/**
@@ -282,12 +294,33 @@ public function buildQuickForm() {
* true otherwise
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
if (!empty($fields['count']) && !empty($fields['max_value']) &&
$fields['count'] > $fields['max_value']
) {
$errors['count'] = ts('Participant count can not be greater than max participants.');
}
+
+ $priceField = CRM_Price_BAO_PriceField::findById($fields['fieldId']);
+ $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, ['labelColumn' => 'name']);
+
+ $publicCount = 0;
+ $options = CRM_Price_BAO_PriceField::getOptions($priceField->id);
+ foreach ($options as $currentOption) {
+ if ($fields['optionId'] == $currentOption['id'] && $visibilityOptions[$fields['visibility_id']] == 'public') {
+ $publicCount++;
+ }
+ elseif ($fields['optionId'] != $currentOption['id'] && $visibilityOptions[$currentOption['visibility_id']] == 'public') {
+ $publicCount++;
+ }
+ }
+ if ($visibilityOptions[$priceField->visibility_id] == 'public' && $publicCount == 0 && $visibilityOptions[$fields['visibility_id']] == 'admin') {
+ $errors['visibility_id'] = ts('All other options for this \'Public\' field have \'Admin\' visibility. There should at least be one \'Public\' option, or make the field \'Admin\' only.');
+ }
+ elseif ($visibilityOptions[$priceField->visibility_id] == 'admin' && $visibilityOptions[$fields['visibility_id']] == 'public') {
+ $errors['visibility_id'] = ts('You must choose \'Admin\' visibility for this price option, as it belongs to a field with \'Admin\' visibility.');
+ }
+
return empty($errors) ? TRUE : $errors;
}
@@ -298,7 +331,7 @@ public static function formRule($fields, $files, $form) {
*/
public function postProcess() {
if ($this->_action == CRM_Core_Action::DELETE) {
- $fieldValues = array('price_field_id' => $this->_fid);
+ $fieldValues = ['price_field_id' => $this->_fid];
$wt = CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceFieldValue', $this->_oid, $fieldValues);
$label = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
$this->_oid,
@@ -306,26 +339,29 @@ public function postProcess() {
);
if (CRM_Price_BAO_PriceFieldValue::del($this->_oid)) {
- CRM_Core_Session::setStatus(ts('%1 option has been deleted.', array(1 => $label)), ts('Record Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts('%1 option has been deleted.', [1 => $label]), ts('Record Deleted'), 'success');
}
return NULL;
}
else {
- $params = $ids = array();
+ $params = $ids = [];
$params = $this->controller->exportValues('Option');
$fieldLabel = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'label');
- $params['amount'] = CRM_Utils_Rule::cleanMoney(trim($params['amount']));
+ foreach ($this->_moneyFields as $field) {
+ $params[$field] = CRM_Utils_Rule::cleanMoney(trim($params[$field]));
+ }
$params['price_field_id'] = $this->_fid;
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
- $ids = array();
+ $params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
+ $ids = [];
if ($this->_oid) {
- $ids['id'] = $this->_oid;
+ $params['id'] = $this->_oid;
}
$optionValue = CRM_Price_BAO_PriceFieldValue::create($params, $ids);
- CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", array(1 => $params['label'])), ts('Value Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", [1 => $params['label']]), ts('Value Saved'), 'success');
}
}
diff --git a/CRM/Price/Form/Preview.php b/CRM/Price/Form/Preview.php
index 70d4b3c986eb..4d3cad25e525 100644
--- a/CRM/Price/Form/Preview.php
+++ b/CRM/Price/Form/Preview.php
@@ -1,9 +1,9 @@
_groupTree[$groupId]['fields'][$fieldId] = $groupTree[$groupId]['fields'][$fieldId];
$this->assign('preview_type', 'field');
$url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$groupId}");
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Set Fields'),
'url' => $url,
- ),
- );
+ ],
+ ];
}
else {
// group preview
@@ -80,12 +80,12 @@ public function preProcess() {
$this->assign('preview_type', 'group');
$this->assign('setTitle', CRM_Price_BAO_PriceSet::getTitle($groupId));
$url = CRM_Utils_System::url('civicrm/admin/price', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Sets'),
'url' => $url,
- ),
- );
+ ],
+ ];
}
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -97,7 +97,7 @@ public function preProcess() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$groupId = $this->get('groupId');
$fieldId = $this->get('fieldId');
if (!empty($this->_groupTree[$groupId]['fields'])) {
@@ -139,13 +139,13 @@ public function buildQuickForm() {
}
}
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done with Preview'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Price/Form/Set.php b/CRM/Price/Form/Set.php
index 0169689aa7ea..1f49fa4e0461 100644
--- a/CRM/Price/Form/Set.php
+++ b/CRM/Price/Form/Set.php
@@ -1,9 +1,9 @@
_sid;
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'PriceSet';
+ }
+
+ /**
+ * Fields for the entity to be assigned to the template.
+ *
+ * Fields may have keys
+ * - name (required to show in tpl from the array)
+ * - description (optional, will appear below the field)
+ * - not-auto-addable - this class will not attempt to add the field using addField.
+ * (this will be automatically set if the field does not have html in it's metadata
+ * or is not a core field on the form's entity).
+ * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'title' => [
+ 'required' => 'TRUE',
+ 'name' => 'title',
+ ],
+ 'min_amount' => ['name' => 'min_amount'],
+ 'help_pre' => ['name' => 'help_pre'],
+ 'help_post' => ['name' => 'help_post'],
+ 'is_active' => ['name' => 'is_active'],
+ ];
+ }
+
+ /**
+ * Deletion message to be assigned to the form.
+ *
+ * @var string
+ */
+ protected $deleteMessage;
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {}
+
/**
* Set variables up before form is built.
*/
@@ -52,24 +115,24 @@ public function preProcess() {
// setting title for html page
$title = ts('New Price Set');
- if ($this->_sid) {
- $title = CRM_Price_BAO_PriceSet::getTitle($this->_sid);
+ if ($this->getEntityId()) {
+ $title = CRM_Price_BAO_PriceSet::getTitle($this->getEntityId());
}
if ($this->_action & CRM_Core_Action::UPDATE) {
- $title = ts('Edit %1', array(1 => $title));
+ $title = ts('Edit %1', [1 => $title]);
}
elseif ($this->_action & CRM_Core_Action::VIEW) {
- $title = ts('Preview %1', array(1 => $title));
+ $title = ts('Preview %1', [1 => $title]);
}
CRM_Utils_System::setTitle($title);
$url = CRM_Utils_System::url('civicrm/admin/price', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Sets'),
'url' => $url,
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -87,7 +150,7 @@ public function preProcess() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
- $errors = array();
+ $errors = [];
$count = count(CRM_Utils_Array::value('extends', $fields));
//price sets configured for membership
if ($count && array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $fields['extends'])) {
@@ -95,11 +158,8 @@ public static function formRule($fields, $files, $options) {
$errors['extends'] = ts('If you plan on using this price set for membership signup and renewal, you can not also use it for Events or Contributions. However, a membership price set may include additional fields for non-membership options that require an additional fee (e.g. magazine subscription).');
}
}
- //checks the given price set doesnot start with digit
- $title = $fields['title'];
- // gives the ascii value
- $asciiValue = ord($title{0});
- if ($asciiValue >= 48 && $asciiValue <= 57) {
+ // Checks the given price set does not start with a digit
+ if (strlen($fields['title']) && is_numeric($fields['title'][0])) {
$errors['title'] = ts("Name cannot not start with a digit");
}
return empty($errors) ? TRUE : $errors;
@@ -109,23 +169,18 @@ public static function formRule($fields, $files, $options) {
* Build the form object.
*/
public function buildQuickForm() {
- $this->applyFilter('__ALL__', 'trim');
-
- $this->assign('sid', $this->_sid);
+ $this->buildQuickEntityForm();
+ $this->assign('sid', $this->getEntityId());
- // title
- $this->add('text', 'title', ts('Set Name'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title'), TRUE);
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Price_DAO_PriceSet', $this->_sid, 'title')
+ 'objectExists', ['CRM_Price_DAO_PriceSet', $this->getEntityId(), 'title']
);
- $priceSetUsedTables = $extends = array();
- if ($this->_action == CRM_Core_Action::UPDATE && $this->_sid) {
- $priceSetUsedTables = CRM_Price_BAO_PriceSet::getUsedBy($this->_sid, 'table');
+ $priceSetUsedTables = $extends = [];
+ if ($this->_action == CRM_Core_Action::UPDATE && $this->getEntityId()) {
+ $priceSetUsedTables = CRM_Price_BAO_PriceSet::getUsedBy($this->getEntityId(), 'table');
}
- $config = CRM_Core_Config::singleton();
- $showContribution = FALSE;
$enabledComponents = CRM_Core_Component::getEnabledComponents();
foreach ($enabledComponents as $name => $compObj) {
@@ -133,7 +188,7 @@ public function buildQuickForm() {
case 'CiviEvent':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Event'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_event', 'civicrm_participant') as $table) {
+ foreach (['civicrm_event', 'civicrm_participant'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -146,7 +201,7 @@ public function buildQuickForm() {
case 'CiviContribute':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Contribution'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_contribution', 'civicrm_contribution_page') as $table) {
+ foreach (['civicrm_contribution', 'civicrm_contribution_page'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -159,7 +214,7 @@ public function buildQuickForm() {
case 'CiviMember':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Membership'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_membership', 'civicrm_contribution_page') as $table) {
+ foreach (['civicrm_membership', 'civicrm_contribution_page'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -171,8 +226,6 @@ public function buildQuickForm() {
}
}
- $this->addElement('text', 'min_amount', ts('Minimum Amount'));
-
if (CRM_Utils_System::isNull($extends)) {
$this->assign('extends', FALSE);
}
@@ -182,54 +235,21 @@ public function buildQuickForm() {
$this->addGroup($extends, 'extends', ts('Used For'), ' ', TRUE);
- $this->addRule('extends', ts('%1 is a required field.', array(1 => ts('Used For'))), 'required');
+ $this->addRule('extends', ts('%1 is a required field.', [1 => ts('Used For')]), 'required');
// financial type
$financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
- foreach ($financialType as $finTypeId => $type) {
- if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
- && !CRM_Core_Permission::check('add contributions of type ' . $type)
- ) {
- unset($financialType[$finTypeId]);
- }
- }
-
$this->add('select', 'financial_type_id',
ts('Default Financial Type'),
- array('' => ts('- select -')) + $financialType, 'required'
+ ['' => ts('- select -')] + $financialType, 'required'
);
- // help text
- $this->add('textarea', 'help_pre', ts('Pre-form Help'),
- CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'help_pre')
- );
- $this->add('textarea', 'help_post', ts('Post-form Help'),
- CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'help_post')
- );
-
- // is this set active ?
- $this->addElement('checkbox', 'is_active', ts('Is this Price Set active?'));
-
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- ));
-
- $this->addFormRule(array('CRM_Price_Form_Set', 'formRule'));
+ $this->addFormRule(['CRM_Price_Form_Set', 'formRule']);
// views are implemented as frozen form
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
- //$this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/price?reset=1&action=browse'"));
}
}
@@ -242,9 +262,9 @@ public function buildQuickForm() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array('is_active' => TRUE);
- if ($this->_sid) {
- $params = array('id' => $this->_sid);
+ $defaults = ['is_active' => TRUE];
+ if ($this->getEntityId()) {
+ $params = ['id' => $this->getEntityId()];
CRM_Price_BAO_PriceSet::retrieve($params, $defaults);
$extends = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['extends']);
unset($defaults['extends']);
@@ -266,7 +286,7 @@ public function postProcess() {
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
- $compIds = array();
+ $compIds = [];
$extends = CRM_Utils_Array::value('extends', $params);
if (is_array($extends)) {
foreach ($extends as $compId => $selected) {
@@ -278,7 +298,7 @@ public function postProcess() {
$params['extends'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $compIds);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $params['id'] = $this->_sid;
+ $params['id'] = $this->getEntityId();
}
else {
$params['name'] = CRM_Utils_String::titleToVar($params['title'],
@@ -287,19 +307,19 @@ public function postProcess() {
$set = CRM_Price_BAO_PriceSet::create($params);
if ($this->_action & CRM_Core_Action::UPDATE) {
- CRM_Core_Session::setStatus(ts('The Set \'%1\' has been saved.', array(1 => $set->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The Set \'%1\' has been saved.', [1 => $set->title]), ts('Saved'), 'success');
}
else {
// Jump directly to adding a field if popups are disabled
$action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? 'browse' : 'add';
- $url = CRM_Utils_System::url('civicrm/admin/price/field', array(
+ $url = CRM_Utils_System::url('civicrm/admin/price/field', [
'reset' => 1,
'action' => $action,
'sid' => $set->id,
'new' => 1,
- ));
+ ]);
CRM_Core_Session::setStatus(ts("Your Set '%1' has been added. You can add fields to this set now.",
- array(1 => $set->title)
+ [1 => $set->title]
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
$session->replaceUserContext($url);
diff --git a/CRM/Price/Page/Field.php b/CRM/Price/Page/Field.php
index 536195af8fc9..d32d22d2e4d0 100644
--- a/CRM/Price/Page/Field.php
+++ b/CRM/Price/Page/Field.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Price Field'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=update&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Edit Price'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview Field'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=preview&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Preview Price'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=delete&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Delete Price'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -117,7 +117,7 @@ public function browse() {
$resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
}
- $priceField = array();
+ $priceField = [];
$priceFieldBAO = new CRM_Price_BAO_PriceField();
// fkey is sid
@@ -133,13 +133,13 @@ public function browse() {
$taxRate = CRM_Core_PseudoConstant::getTaxRates();
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
while ($priceFieldBAO->fetch()) {
- $priceField[$priceFieldBAO->id] = array();
+ $priceField[$priceFieldBAO->id] = [];
CRM_Core_DAO::storeValues($priceFieldBAO, $priceField[$priceFieldBAO->id]);
// get price if it's a text field
if ($priceFieldBAO->html_type == 'Text') {
- $optionValues = array();
- $params = array('price_field_id' => $priceFieldBAO->id);
+ $optionValues = [];
+ $params = ['price_field_id' => $priceFieldBAO->id];
CRM_Price_BAO_PriceFieldValue::retrieve($params, $optionValues);
$priceField[$priceFieldBAO->id]['price'] = CRM_Utils_Array::value('amount', $optionValues);
@@ -149,7 +149,7 @@ public function browse() {
$getTaxDetails = TRUE;
}
if (isset($priceField[$priceFieldBAO->id]['tax_rate'])) {
- $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate']);
+ $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate'], TRUE);
$priceField[$priceFieldBAO->id]['tax_amount'] = $taxAmount['tax_amount'];
}
}
@@ -183,10 +183,10 @@ public function browse() {
$priceField[$priceFieldBAO->id]['action'] = CRM_Core_Action::formLink(
self::actionLinks(),
$action,
- array(
+ [
'fid' => $priceFieldBAO->id,
'sid' => $this->_sid,
- ),
+ ],
ts('more'),
FALSE,
'priceField.row.actions',
@@ -256,12 +256,12 @@ public function run() {
$this->assign('isReserved', $this->_isSetReserved);
CRM_Price_BAO_PriceSet::checkPermission($this->_sid);
- $comps = array(
+ $comps = [
'Event' => 'civicrm_event',
'Contribution' => 'civicrm_contribution_page',
'EventTemplate' => 'civicrm_event_template',
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -298,7 +298,7 @@ public function run() {
$groupTitle = CRM_Price_BAO_PriceSet::getTitle($this->_sid);
$this->assign('sid', $this->_sid);
$this->assign('groupTitle', $groupTitle);
- CRM_Utils_System::setTitle(ts('%1 - Price Fields', array(1 => $groupTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Price Fields', [1 => $groupTitle]));
}
// assign vars to templates
diff --git a/CRM/Price/Page/Option.php b/CRM/Price/Page/Option.php
index ba409c9a386d..fd610f35c9e7 100644
--- a/CRM/Price/Page/Option.php
+++ b/CRM/Price/Page/Option.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Option'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'reset=1&action=update&oid=%%oid%%&fid=%%fid%%&sid=%%sid%%',
'title' => ts('Edit Price Option'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'action=view&oid=%%oid%%',
'title' => ts('View Price Option'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price Option'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price Option'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'action=delete&oid=%%oid%%',
'title' => ts('Disable Price Option'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -121,12 +121,16 @@ public static function &actionLinks() {
* @return void
*/
public function browse() {
- $priceOptions = civicrm_api3('PriceFieldValue', 'get', array(
- 'price_field_id' => $this->_fid,
+ $priceOptions = civicrm_api3('PriceFieldValue', 'get', [
+ 'price_field_id' => $this->_fid,
// Explicitly do not check permissions so we are not
// restricted by financial type, so we can change them.
- 'check_permissions' => FALSE,
- ));
+ 'check_permissions' => FALSE,
+ 'options' => [
+ 'limit' => 0,
+ 'sort' => ['weight', 'label'],
+ ],
+ ]);
$customOption = $priceOptions['values'];
// CRM-15378 - check if these price options are in an Event price set
@@ -149,15 +153,16 @@ public function browse() {
$action = array_sum(array_keys(self::actionLinks()));
// Adding the required fields in the array
if (isset($taxRate[$values['financial_type_id']])) {
- $customOption[$id]['tax_rate'] = $taxRate[$values['financial_type_id']];
+ // Cast to float so trailing zero decimals are removed
+ $customOption[$id]['tax_rate'] = (float) $taxRate[$values['financial_type_id']];
if ($invoicing && isset($customOption[$id]['tax_rate'])) {
$getTaxDetails = TRUE;
}
- $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate']);
+ $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate'], TRUE);
$customOption[$id]['tax_amount'] = $taxAmount['tax_amount'];
}
- if (!empty($values['financial_type_id']) && !empty($financialType[$values['financial_type_id']])) {
- $customOption[$id]['financial_type_id'] = $financialType[$values['financial_type_id']];
+ if (!empty($values['financial_type_id'])) {
+ $customOption[$id]['financial_type_id'] = CRM_Contribute_PseudoConstant::financialType($values['financial_type_id']);
}
// update enable/disable links depending on price_field properties.
if ($this->_isSetReserved) {
@@ -179,11 +184,11 @@ public function browse() {
}
$customOption[$id]['order'] = $customOption[$id]['weight'];
$customOption[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
- array(
+ [
'oid' => $id,
'fid' => $this->_fid,
'sid' => $this->_sid,
- ),
+ ],
ts('more'),
FALSE,
'priceFieldValue.row.actions',
@@ -219,7 +224,7 @@ public function edit($action) {
$oid = CRM_Utils_Request::retrieve('oid', 'Positive',
$this, FALSE, 0
);
- $params = array();
+ $params = [];
if ($oid) {
$params['oid'] = $oid;
$sid = CRM_Price_BAO_PriceSet::getSetId($params);
@@ -246,11 +251,11 @@ public function edit($action) {
);
$this->assign('usedPriceSetTitle', CRM_Price_BAO_PriceFieldValue::getOptionLabel($oid));
$this->assign('usedBy', $usedBy);
- $comps = array(
+ $comps = [
"Event" => "civicrm_event",
"Contribution" => "civicrm_contribution_page",
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -284,19 +289,19 @@ public function run() {
$this->assign('isReserved', $this->_isSetReserved);
}
//as url contain $sid so append breadcrumb dynamically.
- $breadcrumb = array(
- array(
+ $breadcrumb = [
+ [
'title' => ts('Price Fields'),
'url' => CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&sid=' . $this->_sid),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadcrumb);
if ($this->_fid) {
$fieldTitle = CRM_Price_BAO_PriceField::getTitle($this->_fid);
$this->assign('fid', $this->_fid);
$this->assign('fieldTitle', $fieldTitle);
- CRM_Utils_System::setTitle(ts('%1 - Price Options', array(1 => $fieldTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Price Options', [1 => $fieldTitle]));
$htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $this->_fid, 'html_type');
$this->assign('addMoreFields', TRUE);
diff --git a/CRM/Price/Page/Set.php b/CRM/Price/Page/Set.php
index c3ec481e7b5f..accc307829e5 100644
--- a/CRM/Price/Page/Set.php
+++ b/CRM/Price/Page/Set.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::BROWSE => [
'name' => ts('View and Edit Price Fields'),
'url' => 'civicrm/admin/price/field',
'qs' => 'reset=1&action=browse&sid=%%sid%%',
'title' => ts('View and Edit Price Fields'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview'),
'url' => 'civicrm/admin/price',
'qs' => 'action=preview&reset=1&sid=%%sid%%',
'title' => ts('Preview Price Set'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Settings'),
'url' => 'civicrm/admin/price',
'qs' => 'action=update&reset=1&sid=%%sid%%',
'title' => ts('Edit Price Set'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price Set'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price Set'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price',
'qs' => 'action=delete&reset=1&sid=%%sid%%',
'title' => ts('Delete Price Set'),
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
- ),
- CRM_Core_Action::COPY => array(
+ ],
+ CRM_Core_Action::COPY => [
'name' => ts('Copy Price Set'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=copy&sid=%%sid%%',
'title' => ts('Make a Copy of Price Set'),
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -168,12 +168,12 @@ public function run() {
$this->assign('usedPriceSetTitle', CRM_Price_BAO_PriceSet::getTitle($sid));
$this->assign('usedBy', $usedBy);
- $comps = array(
+ $comps = [
'Event' => 'civicrm_event',
'Contribution' => 'civicrm_contribution_page',
'EventTemplate' => 'civicrm_event_template',
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -224,7 +224,7 @@ public function edit($sid, $action) {
public function preview($sid) {
$controller = new CRM_Core_Controller_Simple('CRM_Price_Form_Preview', ts('Preview Price Set'), NULL);
$session = CRM_Core_Session::singleton();
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
if ($context == 'field') {
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/price/field', "action=browse&sid={$sid}"));
}
@@ -247,12 +247,12 @@ public function preview($sid) {
*/
public function browse($action = NULL) {
// get all price sets
- $priceSet = array();
- $comps = array(
+ $priceSet = [];
+ $comps = [
'CiviEvent' => ts('Event'),
'CiviContribute' => ts('Contribution'),
'CiviMember' => ts('Membership'),
- );
+ ];
$dao = new CRM_Price_DAO_PriceSet();
if (CRM_Price_BAO_PriceSet::eventPriceSetDomainID()) {
@@ -261,13 +261,13 @@ public function browse($action = NULL) {
$dao->is_quick_config = 0;
$dao->find();
while ($dao->fetch()) {
- $priceSet[$dao->id] = array();
+ $priceSet[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $priceSet[$dao->id]);
$compIds = explode(CRM_Core_DAO::VALUE_SEPARATOR,
CRM_Utils_Array::value('extends', $priceSet[$dao->id])
);
- $extends = array();
+ $extends = [];
//CRM-10225
foreach ($compIds as $compId) {
if (!empty($comps[CRM_Core_Component::getComponentName($compId)])) {
@@ -294,10 +294,10 @@ public function browse($action = NULL) {
$actionLinks = self::actionLinks();
//CRM-10117
if ($dao->is_reserved) {
- $actionLinks[CRM_Core_Action::BROWSE]['name'] = 'View Price Fields';
+ $actionLinks[CRM_Core_Action::BROWSE]['name'] = ts('View Price Fields');
}
$priceSet[$dao->id]['action'] = CRM_Core_Action::formLink($actionLinks, $action,
- array('sid' => $dao->id),
+ ['sid' => $dao->id],
ts('more'),
FALSE,
'priceSet.row.actions',
diff --git a/CRM/Profile/Form.php b/CRM/Profile/Form.php
index 1b57c6380706..0013777bee9d 100644
--- a/CRM/Profile/Form.php
+++ b/CRM/Profile/Form.php
@@ -1,9 +1,9 @@
'unknown');
+ protected $_ufGroup = ['name' => 'unknown'];
/**
* The group id that we are passing in url.
@@ -79,7 +79,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Name of button for saving matching contacts.
- * @var
+ * @var string
*/
protected $_duplicateButtonName;
/**
@@ -113,6 +113,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Dedupe using a specific rule (CRM-6131).
* Not currently exposed in profile settings, but can be set in a buildForm hook.
+ * @var int
*/
public $_ruleGroupID = NULL;
@@ -137,8 +138,9 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Store profile ids if multiple profile ids are passed using comma separated.
* Currently lets implement this functionality only for dialog mode.
+ * @var array
*/
- protected $_profileIds = array();
+ protected $_profileIds = [];
/**
* Contact profile having activity fields?
@@ -179,6 +181,104 @@ class CRM_Profile_Form extends CRM_Core_Form {
protected $_currentUserID = NULL;
protected $_session = NULL;
+ /**
+ * Check for any duplicates.
+ *
+ * Depending on form settings & usage scenario we potentially use the found id,
+ * create links to found ids or add an error.
+ *
+ * @param array $errors
+ * @param array $fields
+ * @param CRM_Profile_Form $form
+ *
+ * @return array
+ */
+ protected static function handleDuplicateChecking(&$errors, $fields, $form) {
+ if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
+ // fix for CRM-2888
+ $exceptions = [];
+ }
+ else {
+ // for edit mode we need to allow our own record to be a dupe match!
+ $exceptions = [CRM_Core_Session::singleton()->get('userID')];
+ }
+ $contactType = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
+ // If all profile fields is of Contact Type then consider
+ // profile is of Individual type(default).
+ if (!$contactType) {
+ $contactType = 'Individual';
+ }
+
+ $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
+ $fields, $contactType,
+ ($form->_context === 'dialog' ? 'Supervised' : 'Unsupervised'),
+ $exceptions,
+ FALSE,
+ $form->_ruleGroupID
+ );
+ if ($ids) {
+ if ($form->_isUpdateDupe == 2) {
+ CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
+ }
+ elseif ($form->_isUpdateDupe == 1) {
+ $form->_id = $ids[0];
+ }
+ else {
+ if ($form->_context == 'dialog') {
+ $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
+
+ $duplicateContactsLinks = '
',
+ ]);
+ if ($contactLinks['msg'] == 'view') {
+ $duplicateContactsLinks .= ts('You can View the existing contact.', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View the existing contacts.',
+ ]);
+ }
+ else {
+ $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View or Edit the existing contacts.',
+ ]);
+ }
+ $duplicateContactsLinks .= '';
+ $row = '';
+ for ($i = 0; $i < count($contactLinks['rows']); $i++) {
+ $row .= '
';
+ $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
+
+ $errors['_qf_default'] = $duplicateContactsLinks;
+
+ // let smarty know that there are duplicates
+ $template = CRM_Core_Smarty::singleton();
+ $template->assign('isDuplicate', 1);
+ }
+ else {
+ $errors['_qf_default'] = ts('A record already exists with the same information.');
+ }
+ }
+ }
+ return $errors;
+ }
+
/**
* Explicitly declare the entity api name.
*/
@@ -195,7 +295,7 @@ public function preProcess() {
$this->_id = $this->get('id');
$this->_profileIds = $this->get('profileIds');
$this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
//unset from session when $_GET doesn't have it
//except when the form is submitted
@@ -208,8 +308,7 @@ public function preProcess() {
}
}
- $this->_session = CRM_Core_Session::singleton();
- $this->_currentUserID = $this->_session->get('userID');
+ $this->_currentUserID = CRM_Core_Session::singleton()->get('userID');
if ($this->_mode == self::MODE_EDIT) {
//specifies the action being done on a multi record field
@@ -220,7 +319,7 @@ public function preProcess() {
}
if ($this->_multiRecord &&
- !in_array($this->_multiRecord, array(CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE))
+ !in_array($this->_multiRecord, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE])
) {
CRM_Core_Error::fatal(ts('Proper action not specified for this custom value record profile'));
}
@@ -272,12 +371,11 @@ public function preProcess() {
$this->_isAddCaptcha = $dao->add_captcha;
$this->_ufGroup = (array) $dao;
}
- $dao->free();
if (!CRM_Utils_Array::value('is_active', $this->_ufGroup)) {
- CRM_Core_Error::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(
+ CRM_Core_Error::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', [
1 => $this->_gid,
- )));
+ ]));
}
}
$this->assign('ufGroupName', $this->_ufGroup['name']);
@@ -325,17 +423,17 @@ public function preProcess() {
&& ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE)
) {
CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
- array(1 => $this->_gid)
+ [1 => $this->_gid]
));
}
elseif (empty($this->_multiRecordFields)) {
CRM_Core_Error::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
- array(1 => $this->_gid)
+ [1 => $this->_gid]
));
}
$fieldId = CRM_Core_BAO_CustomField::getKeyID(key($this->_multiRecordFields));
- $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId));
+ $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
$this->_customGroupTitle = $customGroupDetails[$fieldId]['groupTitle'];
$this->_customGroupId = $customGroupDetails[$fieldId]['groupID'];
@@ -352,7 +450,7 @@ public function preProcess() {
else {
$this->_recordExists = FALSE;
if ($this->_multiRecord & CRM_Core_Action::UPDATE) {
- CRM_Core_Session::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', array(1 => $this->_recordId)), ts('Record doesnot exist'), 'alert');
+ CRM_Core_Session::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', [1 => $this->_recordId]), ts('Record doesnot exist'), 'alert');
}
}
}
@@ -365,10 +463,10 @@ public function preProcess() {
}
elseif (!empty($this->_multiRecordFields)
- && (!$this->_multiRecord || !in_array($this->_multiRecord, array(
+ && (!$this->_multiRecord || !in_array($this->_multiRecord, [
CRM_Core_Action::DELETE,
CRM_Core_Action::UPDATE,
- )))
+ ]))
) {
CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
//multi-record listing page
@@ -398,7 +496,7 @@ public function preProcess() {
if (!$emailField) {
$status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
- $this->_session->setStatus($status);
+ CRM_Core_Session::singleton()->setStatus($status);
}
}
@@ -425,7 +523,7 @@ public function preProcess() {
*
*/
public function setDefaultsValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
return;
}
@@ -437,7 +535,7 @@ public function setDefaultsValues() {
if ($this->_id && !$this->_multiRecordProfile) {
if ($this->_isContactActivityProfile) {
- $contactFields = $activityFields = array();
+ $contactFields = $activityFields = [];
foreach ($this->_fields as $fieldName => $field) {
if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
$activityFields[$fieldName] = $field;
@@ -463,7 +561,7 @@ public function setDefaultsValues() {
$fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
}
- $defaultValues = array();
+ $defaultValues = [];
if ($this->_multiRecord && $this->_multiRecord == CRM_Core_Action::UPDATE) {
$defaultValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
if ($this->_recordExists == TRUE) {
@@ -511,8 +609,9 @@ public function setDefaultsValues() {
$deleteExtra = ts("Are you sure you want to delete attached file?");
$fileId = $url['file_id'];
+ $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId);
$deleteURL = CRM_Utils_System::url('civicrm/file',
- "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
+ "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
);
$text = ts("Delete Attached File");
$customFiles[$field['name']]['deleteURL'] = "$text";
@@ -551,8 +650,9 @@ public function setDefaultsValues() {
$deleteExtra = ts("Are you sure you want to delete attached file?");
$fileId = $url['file_id'];
+ $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
$deleteURL = CRM_Utils_System::url('civicrm/file',
- "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
+ "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
);
$text = ts("Delete Attached File");
$customFiles[$field['name']]['deleteURL'] = "$text";
@@ -578,14 +678,6 @@ public function setDefaultsValues() {
$this->removeFileRequiredRules('image_URL');
}
- if (array_key_exists('contact_sub_type', $this->_defaults) &&
- !empty($this->_defaults['contact_sub_type'])
- ) {
- $this->_defaults['contact_sub_type'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
- trim($this->_defaults['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
- );
- }
-
$this->setDefaults($this->_defaults);
}
@@ -619,7 +711,7 @@ public function buildQuickForm() {
if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
if (!$this->_recordExists) {
- CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId)), ts('Record doesnot exists'), 'alert');
+ CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId]), ts('Record doesnot exists'), 'alert');
}
else {
$this->assign('deleteRecord', TRUE);
@@ -669,7 +761,7 @@ public function buildQuickForm() {
$return = TRUE;
if (!$statusMessage) {
$statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
- array(1 => $profileSubType ? $profileSubType : $profileType));
+ [1 => $profileSubType ? $profileSubType : $profileType]);
}
}
}
@@ -677,7 +769,7 @@ public function buildQuickForm() {
if (
in_array(
$profileType,
- array("Membership", "Participant", "Contribution")
+ ["Membership", "Participant", "Contribution"]
)
) {
$return = TRUE;
@@ -733,7 +825,7 @@ public function buildQuickForm() {
}
$this->assign('anonUser', $anonUser);
- $addCaptcha = array();
+ $addCaptcha = [];
$emailPresent = FALSE;
// add the form elements
@@ -798,10 +890,8 @@ public function buildQuickForm() {
//finally add captcha to form.
if ($this->_isAddCaptcha) {
- $captcha = CRM_Utils_ReCAPTCHA::singleton();
- $captcha->add($this);
+ CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
}
- $this->assign("isCaptcha", $this->_isAddCaptcha);
if ($this->_mode != self::MODE_SEARCH) {
if (isset($addToGroupId)) {
@@ -847,18 +937,18 @@ public function buildQuickForm() {
* @return array
*/
public static function validateContactActivityProfile($activityId, $contactId, $gid) {
- $errors = array();
+ $errors = [];
if (!$activityId) {
- $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
+ $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
return $errors;
}
- $activityDetails = array();
- $activityParams = array('id' => $activityId);
+ $activityDetails = [];
+ $activityParams = ['id' => $activityId];
CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
if (empty($activityDetails)) {
- $errors[] = 'Invalid Activity Id (aid).';
+ $errors[] = ts('Invalid Activity Id (aid).');
return $errors;
}
@@ -871,7 +961,7 @@ public static function validateContactActivityProfile($activityId, $contactId, $
!in_array($contactId, $activityDetails['target_contact'])
)
) {
- $errors[] = 'This activity cannot be edited or viewed via this profile.';
+ $errors[] = ts('This activity cannot be edited or viewed via this profile.');
}
return $errors;
@@ -893,16 +983,21 @@ public static function validateContactActivityProfile($activityId, $contactId, $
public static function formRule($fields, $files, $form) {
CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
- $errors = array();
// if no values, return
if (empty($fields)) {
return TRUE;
}
+ $errors = [];
$register = NULL;
// hack we use a -1 in options to indicate that its registration
+ // ... and I can't remove that comment because even though it's clear as mud
+ // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
+ // as to what it means....
if ($form->_id) {
+ // @todo - wonder if it ever occurred to someone that if they didn't document this param
+ // it might not be crystal clear why we have it....
$form->_isUpdateDupe = 1;
}
@@ -922,90 +1017,8 @@ public static function formRule($fields, $files, $form) {
$fields['phone-Primary'] = $fields['phone-Primary-1'];
}
- $ctype = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
- // If all profile fields is of Contact Type then consider
- // profile is of Individual type(default).
- if (!$ctype) {
- $ctype = 'Individual';
- }
-
- if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
- // fix for CRM-2888
- $exceptions = array();
- }
- else {
- // for edit mode we need to allow our own record to be a dupe match!
- $exceptions = array($form->_session->get('userID'));
- }
-
- $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
- $fields, $ctype,
- ($form->_context === 'dialog' ? 'Supervised' : 'Unsupervised'),
- $exceptions,
- FALSE,
- $form->_ruleGroupID
- );
- if ($ids) {
- if ($form->_isUpdateDupe == 2) {
- CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
- }
- elseif ($form->_isUpdateDupe == 1) {
- if (!$form->_id) {
- $form->_id = $ids[0];
- }
- }
- else {
- if ($form->_context == 'dialog') {
- $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
-
- $duplicateContactsLinks = ' ';
+ $row .= ' ';
+ }
+
+ $duplicateContactsLinks .= $row . ' ';
+ $row .= $contactLinks['rows'][$i]['display_name'];
+ $row .= ' ';
+ $row .= ' ';
+ $row .= $contactLinks['rows'][$i]['primary_email'];
+ $row .= ' ';
+ $row .= ' ';
+ $row .= $contactLinks['rows'][$i]['view'] . ' ';
+ $row .= $contactLinks['rows'][$i]['edit'];
+ $row .= ' ';
+ $row .= '
',
- ));
- if ($contactLinks['msg'] == 'view') {
- $duplicateContactsLinks .= ts('You can View the existing contact.', array(
- 'count' => count($contactLinks['rows']),
- 'plural' => 'You can View the existing contacts.',
- ));
- }
- else {
- $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array(
- 'count' => count($contactLinks['rows']),
- 'plural' => 'You can View or Edit the existing contacts.',
- ));
- }
- $duplicateContactsLinks .= '';
- $row = '';
- for ($i = 0; $i < count($contactLinks['rows']); $i++) {
- $row .= '
';
- $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
-
- $errors['_qf_default'] = $duplicateContactsLinks;
-
- // let smarty know that there are duplicates
- $template = CRM_Core_Smarty::singleton();
- $template->assign('isDuplicate', 1);
- }
- else {
- $errors['_qf_default'] = ts('A record already exists with the same information.');
- }
- }
+ if (!$form->_id) {
+ self::handleDuplicateChecking($errors, $fields, $form);
}
}
@@ -1051,10 +1064,10 @@ public static function formRule($fields, $files, $form) {
}
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
- $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
+ $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
$errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
- array(1 => ucwords(str_replace('_', ' ', $greeting)))
+ [1 => ucwords(str_replace('_', ' ', $greeting))]
);
}
}
@@ -1074,15 +1087,15 @@ public function postProcess() {
if ($this->_deleteButtonName) {
if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
$filterParams['id'] = $this->_customGroupId;
- $returnProperties = array('is_multiple', 'table_name');
+ $returnProperties = ['is_multiple', 'table_name'];
CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
if (!empty($returnValues['is_multiple'])) {
if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
$sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
- $sqlParams = array(
- 1 => array($this->_recordId, 'Integer'),
- 2 => array($this->_id, 'Integer'),
- );
+ $sqlParams = [
+ 1 => [$this->_recordId, 'Integer'],
+ 2 => [$this->_id, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($sql, $sqlParams);
CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
}
@@ -1095,13 +1108,13 @@ public function postProcess() {
CRM_Contact_BAO_Contact::processImageParams($params);
}
- $greetingTypes = array(
+ $greetingTypes = [
'addressee' => 'addressee_id',
'email_greeting' => 'email_greeting_id',
'postal_greeting' => 'postal_greeting_id',
- );
+ ];
- $details = array();
+ $details = [];
if ($this->_id) {
$contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
$greetingTypes
@@ -1138,7 +1151,7 @@ public function postProcess() {
//used to send subscribe mail to the group which user want.
//if the profile double option in is enabled
- $mailingType = array();
+ $mailingType = [];
$result = NULL;
foreach ($params as $name => $values) {
@@ -1148,18 +1161,18 @@ public function postProcess() {
}
//array of group id, subscribed by contact
- $contactGroup = array();
+ $contactGroup = [];
if (!empty($params['group']) &&
CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
) {
- $groupSubscribed = array();
+ $groupSubscribed = [];
if (!empty($result['email'])) {
if ($this->_id) {
$contactGroups = new CRM_Contact_DAO_GroupContact();
$contactGroups->contact_id = $this->_id;
$contactGroups->status = 'Added';
$contactGroups->find();
- $contactGroup = array();
+ $contactGroup = [];
while ($contactGroups->fetch()) {
$contactGroup[] = $contactGroups->group_id;
$groupSubscribed[$contactGroups->group_id] = 1;
@@ -1204,13 +1217,13 @@ public function postProcess() {
) {
if (!count($contactGroup)) {
//array of group id, subscribed by contact
- $contactGroup = array();
+ $contactGroup = [];
if ($this->_id) {
$contactGroups = new CRM_Contact_DAO_GroupContact();
$contactGroups->contact_id = $this->_id;
$contactGroups->status = 'Added';
$contactGroups->find();
- $contactGroup = array();
+ $contactGroup = [];
while ($contactGroups->fetch()) {
$contactGroup[] = $contactGroups->group_id;
$groupSubscribed[$contactGroups->group_id] = 1;
@@ -1243,7 +1256,7 @@ public function postProcess() {
$profileFields = $this->_fields;
if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
- $profileFields = $activityParams = array();
+ $profileFields = $activityParams = [];
foreach ($this->_fields as $fieldName => $field) {
if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
if (isset($params[$fieldName])) {
@@ -1290,7 +1303,7 @@ public function postProcess() {
CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
}
- $ufGroups = array();
+ $ufGroups = [];
if ($this->_gid) {
$ufGroups[$this->_gid] = 1;
}
diff --git a/CRM/Profile/Form/Dynamic.php b/CRM/Profile/Form/Dynamic.php
index 67bf3e136021..c1e6c50ac595 100644
--- a/CRM/Profile/Form/Dynamic.php
+++ b/CRM/Profile/Form/Dynamic.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
// also add a hidden element for to trick drupal
$this->addElement('hidden', "edit[civicrm_dummy_field]", "CiviCRM Dummy Field for Drupal");
parent::buildQuickForm();
- $this->addFormRule(array('CRM_Profile_Form_Dynamic', 'formRule'), $this);
+ $this->addFormRule(['CRM_Profile_Form_Dynamic', 'formRule'], $this);
}
/**
@@ -100,7 +100,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
// if no values, return
if (empty($fields) || empty($fields['edit'])) {
diff --git a/CRM/Profile/Form/Edit.php b/CRM/Profile/Form/Edit.php
index 63e741ee58fa..c5d493bacf88 100644
--- a/CRM/Profile/Form/Edit.php
+++ b/CRM/Profile/Form/Edit.php
@@ -1,9 +1,9 @@
assign('onPopupClose', $this->_onPopupClose);
//set the context for the profile
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
//set the block no
$this->_blockNo = CRM_Utils_Request::retrieve('blockNo', 'String', $this);
@@ -88,8 +88,7 @@ public function preProcess() {
if ($this->get('edit')) {
// make sure we have right permission to edit this user
- $session = CRM_Core_Session::singleton();
- $userID = $session->get('userID');
+ $userID = CRM_Core_Session::getLoggedInContactID();
// Set the ID from the query string, otherwise default to the current user
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, $userID);
@@ -129,7 +128,7 @@ public function preProcess() {
WHERE civicrm_uf_group.id = %1
";
- $params = array(1 => array($this->_gid, 'Integer'));
+ $params = [1 => [$this->_gid, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$isProfile = FALSE;
@@ -143,7 +142,7 @@ public function preProcess() {
//Remove need for Profile module type when using reserved profiles [CRM-14488]
if (!$dao->N || (!$isProfile && !($dao->is_reserved && $canAdd))) {
CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) is not configured to be used for \'Profile\' edit and view forms in its Settings. Contact the site administrator if you need assistance.',
- array(1 => $this->_gid)
+ [1 => $this->_gid]
));
}
}
@@ -221,9 +220,12 @@ public function buildQuickForm() {
$this->assign('cancelURL', $this->_cancelURL);
+ $cancelButtonValue = !empty($this->_ufGroup['cancel_button_text']) ? $this->_ufGroup['cancel_button_text'] : ts('Cancel');
+ $this->assign('cancelButtonText', $cancelButtonValue);
+ $this->assign('includeCancelButton', CRM_Utils_Array::value('add_cancel_button', $this->_ufGroup));
+
if (($this->_multiRecord & CRM_Core_Action::DELETE) && $this->_recordExists) {
$this->_deleteButtonName = $this->getButtonName('upload', 'delete');
-
$this->addElement('submit', $this->_deleteButtonName, ts('Delete'));
return;
@@ -240,15 +242,15 @@ public function buildQuickForm() {
$buttonName = 'next';
}
- $buttons[] = array(
+ $buttons[] = [
'type' => $buttonName,
- 'name' => ts('Save'),
+ 'name' => !empty($this->_ufGroup['submit_button_text']) ? $this->_ufGroup['submit_button_text'] : ts('Save'),
'isDefault' => TRUE,
- );
+ ];
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Profile_Form', 'formRule'), $this);
+ $this->addFormRule(['CRM_Profile_Form', 'formRule'], $this);
}
/**
@@ -260,10 +262,10 @@ public function postProcess() {
// Send back data for the EntityRef widget
if ($this->returnExtra) {
- $contact = civicrm_api3('Contact', 'getsingle', array(
+ $contact = civicrm_api3('Contact', 'getsingle', [
'id' => $this->_id,
'return' => $this->returnExtra,
- ));
+ ]);
foreach (explode(',', $this->returnExtra) as $field) {
$field = trim($field);
$this->ajaxResponse['extra'][$field] = CRM_Utils_Array::value($field, $contact);
@@ -299,10 +301,10 @@ public function postProcess() {
}
else {
// Replace tokens from post URL
- $contactParams = array(
+ $contactParams = [
'contact_id' => $this->_id,
'version' => 3,
- );
+ ];
$contact = civicrm_api('contact', 'get', $contactParams);
$contact = reset($contact['values']);
diff --git a/CRM/Profile/Form/Search.php b/CRM/Profile/Form/Search.php
index bb8f0a57b200..c674f74280fb 100644
--- a/CRM/Profile/Form/Search.php
+++ b/CRM/Profile/Form/Search.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
parent::buildQuickForm();
}
diff --git a/CRM/Profile/Page/Dynamic.php b/CRM/Profile/Page/Dynamic.php
index 4f663608c414..0ea100a3378c 100644
--- a/CRM/Profile/Page/Dynamic.php
+++ b/CRM/Profile/Page/Dynamic.php
@@ -1,9 +1,9 @@
_profileIds = $profileIds;
}
else {
- $this->_profileIds = array($gid);
+ $this->_profileIds = [$gid];
}
$this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
@@ -236,7 +239,7 @@ public function run() {
$admin = TRUE;
}
- $values = array();
+ $values = [];
$fields = CRM_Core_BAO_UFGroup::getFields($this->_profileIds, FALSE, CRM_Core_Action::VIEW,
NULL, NULL, FALSE, $this->_restrict,
$this->_skipPermission, NULL,
@@ -268,7 +271,7 @@ public function run() {
}
if ($this->_isContactActivityProfile) {
- $contactFields = $activityFields = array();
+ $contactFields = $activityFields = [];
foreach ($fields as $fieldName => $field) {
if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
@@ -286,7 +289,7 @@ public function run() {
$activityFields,
$values,
TRUE,
- array(array('activity_id', '=', $this->_activityId, 0, 0))
+ [['activity_id', '=', $this->_activityId, 0, 0]]
);
}
}
@@ -311,8 +314,8 @@ public function run() {
}
// $profileFields array can be used for customized display of field labels and values in Profile/View.tpl
- $profileFields = array();
- $labels = array();
+ $profileFields = [];
+ $labels = [];
foreach ($fields as $name => $field) {
//CRM-14338
@@ -329,10 +332,10 @@ public function run() {
}
foreach ($values as $title => $value) {
- $profileFields[$labels[$title]] = array(
+ $profileFields[$labels[$title]] = [
'label' => $title,
'value' => $value,
- );
+ ];
}
$template->assign_by_ref('row', $values);
@@ -350,7 +353,7 @@ public function run() {
if (($this->_multiRecord & CRM_Core_Action::VIEW) && $this->_recordId && !$this->_allFields) {
$fieldDetail = reset($fields);
$fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldDetail['name']);
- $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId));
+ $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
$multiRecTitle = $customGroupDetails[$fieldId]['groupTitle'];
}
else {
@@ -374,7 +377,7 @@ public function run() {
$title .= ' - ' . $displayName;
}
- $title = isset($multiRecTitle) ? ts('View %1 Record', array(1 => $multiRecTitle)) : $title;
+ $title = isset($multiRecTitle) ? ts('View %1 Record', [1 => $multiRecTitle]) : $title;
CRM_Utils_System::setTitle($title);
// invoke the pagRun hook, CRM-3906
diff --git a/CRM/Profile/Page/Listings.php b/CRM/Profile/Page/Listings.php
index 6cf74ea5eeb3..0fdc3a2d1e19 100644
--- a/CRM/Profile/Page/Listings.php
+++ b/CRM/Profile/Page/Listings.php
@@ -1,9 +1,9 @@
_customFields = CRM_Core_BAO_CustomField::getFieldsForImport(NULL, FALSE, FALSE, FALSE, TRUE, TRUE);
- $this->_params = array();
+ $this->_params = [];
- $resetArray = array(
+ $resetArray = [
'group',
'tag',
'preferred_communication_method',
@@ -153,13 +154,13 @@ public function preProcess() {
'do_not_sms',
'do_not_trade',
'gender',
- );
+ ];
foreach ($this->_fields as $name => $field) {
if ((substr($name, 0, 6) == 'custom') && !empty($field['is_search_range'])) {
$from = CRM_Utils_Request::retrieve($name . '_from', 'String', $this);
$to = CRM_Utils_Request::retrieve($name . '_to', 'String', $this);
- $value = array();
+ $value = [];
if ($from && $to) {
$value[$name . '_from'] = $from;
$value[$name . '_to'] = $to;
@@ -214,7 +215,7 @@ public function preProcess() {
if (($name == 'group' || $name == 'tag') && !empty($value) && !is_array($value)) {
$v = explode(',', $value);
- $value = array();
+ $value = [];
foreach ($v as $item) {
$value[$item] = 1;
}
@@ -226,7 +227,7 @@ public function preProcess() {
if ($customField) {
// reset checkbox/radio because a form does not send null checkbox values
if (in_array($customField['html_type'],
- array('Multi-Select', 'CheckBox', 'Multi-Select State/Province', 'Multi-Select Country', 'Radio', 'Select')
+ ['Multi-Select', 'CheckBox', 'Multi-Select State/Province', 'Multi-Select Country', 'Radio', 'Select']
)) {
// only reset on a POST submission if we don't see any value
$value = NULL;
@@ -258,7 +259,7 @@ public function preProcess() {
// set the prox params
// need to ensure proximity searching is enabled
- $proximityVars = array(
+ $proximityVars = [
'street_address',
'city',
'postal_code',
@@ -266,7 +267,7 @@ public function preProcess() {
'country_id',
'distance',
'distance_unit',
- );
+ ];
foreach ($proximityVars as $var) {
$value = CRM_Utils_Request::retrieve("prox_{$var}",
'String',
@@ -416,8 +417,8 @@ public static function getProfileContact($gid) {
$session = CRM_Core_Session::singleton();
$params = $session->get('profileParams');
- $details = array();
- $ufGroupParam = array('id' => $gid);
+ $details = [];
+ $ufGroupParam = ['id' => $gid];
CRM_Core_BAO_UFGroup::retrieve($ufGroupParam, $details);
// make sure this group can be mapped
@@ -433,7 +434,7 @@ public static function getProfileContact($gid) {
$params['group'][$groupId] = 1;
}
else {
- $params['group'] = array($groupId => 1);
+ $params['group'] = [$groupId => 1];
}
}
diff --git a/CRM/Profile/Page/MultipleRecordFieldsListing.php b/CRM/Profile/Page/MultipleRecordFieldsListing.php
index 49d3a214bf29..66bc8ed9eb3e 100644
--- a/CRM/Profile/Page/MultipleRecordFieldsListing.php
+++ b/CRM/Profile/Page/MultipleRecordFieldsListing.php
@@ -1,9 +1,9 @@
_pageViewType])) {
// helper variable for nicer formatting
- $links = array();
+ $links = [];
$view = array_search(CRM_Core_Action::VIEW, CRM_Core_Action::$_names);
$update = array_search(CRM_Core_Action::UPDATE, CRM_Core_Action::$_names);
$delete = array_search(CRM_Core_Action::DELETE, CRM_Core_Action::$_names);
// names and titles
- $links[CRM_Core_Action::VIEW] = array(
+ $links[CRM_Core_Action::VIEW] = [
'name' => ts('View'),
- 'title' => ts('View %1', array(1 => $this->_customGroupTitle . ' record')),
- );
+ 'title' => ts('View %1', [1 => $this->_customGroupTitle . ' record']),
+ ];
- $links[CRM_Core_Action::UPDATE] = array(
+ $links[CRM_Core_Action::UPDATE] = [
'name' => ts('Edit'),
- 'title' => ts('Edit %1', array(1 => $this->_customGroupTitle . ' record')),
- );
+ 'title' => ts('Edit %1', [1 => $this->_customGroupTitle . ' record']),
+ ];
- $links[CRM_Core_Action::DELETE] = array(
+ $links[CRM_Core_Action::DELETE] = [
'name' => ts('Delete'),
- 'title' => ts('Delete %1', array(1 => $this->_customGroupTitle . ' record')),
- );
+ 'title' => ts('Delete %1', [1 => $this->_customGroupTitle . ' record']),
+ ];
// urls and queryStrings
if ($this->_pageViewType == 'profileDataView') {
@@ -116,12 +116,12 @@ public function &links() {
// NOTE : links for DELETE action for customDataView is handled in browse
// copy action
- $links[CRM_Core_Action::COPY] = array(
+ $links[CRM_Core_Action::COPY] = [
'name' => ts('Copy'),
- 'title' => ts('Copy %1', array(1 => $this->_customGroupTitle . ' record')),
+ 'title' => ts('Copy %1', [1 => $this->_customGroupTitle . ' record']),
'url' => 'civicrm/contact/view/cd/edit',
'qs' => 'reset=1&type=%%type%%&groupID=%%groupID%%&entityID=%%entityID%%&cgcount=%%newCgCount%%&multiRecordDisplay=single©ValueId=%%cgcount%%&mode=copy',
- );
+ ];
}
self::$_links[$this->_pageViewType] = $links;
@@ -168,7 +168,7 @@ public function run() {
public function browse() {
$dateFields = NULL;
$newCgCount = $cgcount = 0;
- $attributes = $result = $headerAttr = array();
+ $attributes = $result = $headerAttr = [];
$dateFieldsVals = NULL;
if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
$fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL,
@@ -178,7 +178,7 @@ public function browse() {
NULL,
CRM_Core_Permission::EDIT
);
- $multiRecordFields = array();
+ $multiRecordFields = [];
$fieldIDs = NULL;
$result = NULL;
$multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
@@ -199,10 +199,10 @@ public function browse() {
elseif ($this->_pageViewType == 'customDataView') {
// require custom group id for _pageViewType of customDataView
$customGroupId = $this->_customGroupId;
+ $this->assign('customGroupId', $customGroupId);
$reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
if (!$reached) {
$this->assign('contactId', $this->_contactId);
- $this->assign('customGroupId', $customGroupId);
$this->assign('ctype', $this->_contactType);
}
$this->assign('reachedMax', $reached);
@@ -217,8 +217,8 @@ public function browse() {
$this->_customGroupTitle = $groupDetail[$customGroupId]['title'];
}
if (!empty($fieldIDs) && $this->_contactId) {
- $options = array();
- $returnProperities = array(
+ $options = [];
+ $returnProperities = [
'html_type',
'data_type',
'date_format',
@@ -226,11 +226,11 @@ public function browse() {
'default_value',
'is_required',
'is_view',
- );
+ ];
foreach ($fieldIDs as $key => $fieldID) {
$fieldIDs[$key] = !is_numeric($fieldID) ? CRM_Core_BAO_CustomField::getKeyID($fieldID) : $fieldID;
- $param = array('id' => $fieldIDs[$key]);
- $returnValues = array();
+ $param = ['id' => $fieldIDs[$key]];
+ $returnValues = [];
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
if ($returnValues['data_type'] == 'Date') {
$dateFields[$fieldIDs[$key]] = 1;
@@ -264,7 +264,7 @@ public function browse() {
// commonly used for both views i.e profile listing view (profileDataView) and custom data listing view (customDataView)
$result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE, $DTparams);
$resultCount = !empty($result['count']) ? $result['count'] : count($result);
- $sortedResult = !empty($result['sortedResult']) ? $result['sortedResult'] : array();
+ $sortedResult = !empty($result['sortedResult']) ? $result['sortedResult'] : [];
unset($result['count']);
unset($result['sortedResult']);
@@ -279,7 +279,7 @@ public function browse() {
$nonListingFieldIds = array_keys($multiRecordFields);
$singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
$fieldIdInput = $singleField;
- $singleField = array($singleField);
+ $singleField = [$singleField];
$fieldInput = $singleField;
}
$customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
@@ -339,15 +339,15 @@ public function browse() {
// Set field attributes to support crmEditable
// Note that $fieldAttributes[data-type] actually refers to the html type not the sql data type
// TODO: Not all widget types and validation rules are supported by crmEditable so some fields will not be in-place editable
- $fieldAttributes = array('class' => "crmf-custom_{$fieldId}_$recId");
+ $fieldAttributes = ['class' => "crmf-custom_{$fieldId}_$recId"];
$editable = FALSE;
- if (!$options[$fieldId]['attributes']['is_view'] && $linkAction & CRM_Core_Action::UPDATE) {
+ if (!$options[$fieldId]['attributes']['is_view'] && $this->_pageViewType == 'customDataView' && $linkAction & CRM_Core_Action::UPDATE) {
$spec = $options[$fieldId]['attributes'];
switch ($spec['html_type']) {
case 'Text':
// Other data types like money would require some extra validation
// FIXME: crmEditable currently does not support any validation rules :(
- $supportedDataTypes = array('Float', 'String', 'Int');
+ $supportedDataTypes = ['Float', 'String', 'Int'];
$editable = in_array($spec['data_type'], $supportedDataTypes);
break;
@@ -375,11 +375,11 @@ public function browse() {
$op = NULL;
if ($this->_pageViewType == 'profileDataView') {
- $actionParams = array(
+ $actionParams = [
'recordId' => $recId,
'gid' => $this->_profileId,
'id' => $this->_contactId,
- );
+ ];
$op = 'profile.multiValue.row';
}
else {
@@ -392,12 +392,12 @@ public function browse() {
$actionParams['newCgCount'] = $newCgCount;
// DELETE action links
- $deleteData = array(
+ $deleteData = [
'valueID' => $recId,
'groupID' => $this->_customGroupId,
'contactId' => $this->_contactId,
'key' => CRM_Core_Key::get('civicrm/ajax/customvalue'),
- );
+ ];
$links[CRM_Core_Action::DELETE]['url'] = '#';
$links[CRM_Core_Action::DELETE]['extra'] = ' data-delete_params="' . htmlspecialchars(json_encode($deleteData)) . '"';
$links[CRM_Core_Action::DELETE]['class'] = 'delete-custom-row';
@@ -423,9 +423,9 @@ public function browse() {
}
}
- $headers = array();
+ $headers = [];
if (!empty($fieldIDs)) {
- $fields = array('Radio', 'Select', 'Select Country', 'Select State/Province');
+ $fields = ['Radio', 'Select', 'Select Country', 'Select State/Province'];
foreach ($fieldIDs as $fieldID) {
if ($this->_pageViewType == 'profileDataView') {
$headers[$fieldID] = $customGroupInfo[$fieldID]['fieldLabel'];
@@ -461,7 +461,7 @@ public function browse() {
$this->assign('records', $result);
$this->assign('attributes', $attributes);
- return array($result, $attributes);
+ return [$result, $attributes];
}
/**
diff --git a/CRM/Profile/Page/Router.php b/CRM/Profile/Page/Router.php
index 58ace32aa72d..668739537943 100644
--- a/CRM/Profile/Page/Router.php
+++ b/CRM/Profile/Page/Router.php
@@ -1,9 +1,9 @@
run('CRM_Profile_Form_Edit',
ts('Create Profile'),
- array(
+ [
'mode' => CRM_Core_Action::ADD,
'ignoreKey' => $allowRemoteSubmit,
- )
+ ]
);
}
}
diff --git a/CRM/Profile/Page/View.php b/CRM/Profile/Page/View.php
index dae13fc7f5b6..593d656d4110 100644
--- a/CRM/Profile/Page/View.php
+++ b/CRM/Profile/Page/View.php
@@ -1,9 +1,9 @@
1) {
if (!empty($gids)) {
foreach ($gids as $pfId) {
@@ -95,7 +95,7 @@ public function preProcess() {
$anyContent = TRUE;
if ($this->_gid) {
$page = new CRM_Profile_Page_Dynamic($this->_id, $this->_gid, 'Profile', FALSE, $profileIds);
- $profileGroup = array();
+ $profileGroup = [];
$profileGroup['title'] = NULL;
$profileGroup['content'] = $page->run();
if (empty($profileGroup['content'])) {
@@ -130,10 +130,10 @@ public function preProcess() {
else {
$ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('Profile');
- $profileGroups = array();
+ $profileGroups = [];
foreach ($ufGroups as $groupid => $group) {
$page = new CRM_Profile_Page_Dynamic($this->_id, $groupid, 'Profile', FALSE, $profileIds);
- $profileGroup = array();
+ $profileGroup = [];
$profileGroup['title'] = $group['title'];
$profileGroup['content'] = $page->run();
if (empty($profileGroup['content'])) {
diff --git a/CRM/Profile/Selector/Listings.php b/CRM/Profile/Selector/Listings.php
index 566667537b55..e92eb6641fe4 100644
--- a/CRM/Profile/Selector/Listings.php
+++ b/CRM/Profile/Selector/Listings.php
@@ -1,9 +1,9 @@
_gid = $ufGroupIds[0];
}
else {
- $this->_profileIds = array($ufGroupIds);
+ $this->_profileIds = [$ufGroupIds];
$this->_gid = $ufGroupIds;
}
@@ -172,7 +173,7 @@ public function __construct(
$this->_params['group'][$groupId] = 1;
}
else {
- $this->_params['group'] = array($groupId => 1);
+ $this->_params['group'] = [$groupId => 1];
}
}
@@ -211,7 +212,7 @@ public function __construct(
*/
public static function &links($map = FALSE, $editLink = FALSE, $ufLink = FALSE, $gids = NULL) {
if (!self::$_links) {
- self::$_links = array();
+ self::$_links = [];
$viewPermission = TRUE;
if ($gids) {
@@ -226,39 +227,39 @@ public static function &links($map = FALSE, $editLink = FALSE, $ufLink = FALSE,
}
if ($viewPermission) {
- self::$_links[CRM_Core_Action::VIEW] = array(
+ self::$_links[CRM_Core_Action::VIEW] = [
'name' => ts('View'),
'url' => 'civicrm/profile/view',
'qs' => 'reset=1&id=%%id%%&gid=%%gid%%',
'title' => ts('View Profile Details'),
- );
+ ];
}
if ($editLink) {
- self::$_links[CRM_Core_Action::UPDATE] = array(
+ self::$_links[CRM_Core_Action::UPDATE] = [
'name' => ts('Edit'),
'url' => 'civicrm/profile/edit',
'qs' => 'reset=1&id=%%id%%&gid=%%gid%%',
'title' => ts('Edit'),
- );
+ ];
}
if ($ufLink) {
- self::$_links[CRM_Core_Action::PROFILE] = array(
+ self::$_links[CRM_Core_Action::PROFILE] = [
'name' => ts('Website Profile'),
'url' => 'user/%%ufID%%',
'qs' => ' ',
'title' => ts('View Website Profile'),
- );
+ ];
}
if ($map) {
- self::$_links[CRM_Core_Action::MAP] = array(
+ self::$_links[CRM_Core_Action::MAP] = [
'name' => ts('Map'),
'url' => 'civicrm/profile/map',
'qs' => 'reset=1&cid=%%id%%&gid=%%gid%%',
'title' => ts('Map'),
- );
+ ];
}
}
return self::$_links;
@@ -293,20 +294,20 @@ public function getPagerParams($action, &$params) {
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
- static $skipFields = array('group', 'tag');
- $multipleFields = array('url');
+ static $skipFields = ['group', 'tag'];
+ $multipleFields = ['url'];
$direction = CRM_Utils_Sort::ASCENDING;
$empty = TRUE;
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array('name' => ''),
- array(
+ self::$_columnHeaders = [
+ ['name' => ''],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
'field_name' => 'sort_name',
- ),
- );
+ ],
+ ];
$locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
@@ -334,11 +335,11 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
$locationTypeName = $locationTypes[$lType];
}
- if (in_array($fieldName, array(
+ if (in_array($fieldName, [
'phone',
'im',
'email',
- ))) {
+ ])) {
if ($type) {
$name = "`$locationTypeName-$fieldName-$type`";
}
@@ -355,12 +356,12 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
}
}
- self::$_columnHeaders[] = array(
+ self::$_columnHeaders[] = [
'name' => $field['title'],
'sort' => $name,
'direction' => $direction,
'field_name' => CRM_Core_BAO_UFField::isValidFieldName($name) ? $name : $fieldName,
- );
+ ];
$direction = CRM_Utils_Sort::DONTCARE;
$empty = FALSE;
@@ -370,10 +371,10 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
// if we don't have any valid columns, don't add the implicit ones
// this allows the template to check on emptiness of column headers
if ($empty) {
- self::$_columnHeaders = array();
+ self::$_columnHeaders = [];
}
else {
- self::$_columnHeaders[] = array('desc' => ts('Actions'));
+ self::$_columnHeaders[] = ['desc' => ts('Actions')];
}
}
return self::$_columnHeaders;
@@ -443,11 +444,11 @@ public function getQill() {
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $extraWhereClause = NULL) {
- $multipleFields = array('url');
+ $multipleFields = ['url'];
//$sort object processing for location fields
if ($sort) {
$vars = $sort->_vars;
- $varArray = array();
+ $varArray = [];
foreach ($vars as $key => $field) {
$field = $vars[$key];
$fieldArray = explode('-', $field['name']);
@@ -494,7 +495,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
}
// process the result of the query
- $rows = array();
+ $rows = [];
// check if edit is configured in profile settings
if ($this->_gid) {
@@ -502,11 +503,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
}
//FIXME : make sure to handle delete separately. CRM-4418
- $mask = CRM_Core_Action::mask(array(CRM_Core_Permission::getPermission()));
+ $mask = CRM_Core_Action::mask([CRM_Core_Permission::getPermission()]);
if ($editLink && ($mask & CRM_Core_Permission::EDIT)) {
// do not allow edit for anon users in joomla frontend, CRM-4668
$config = CRM_Core_Config::singleton();
- if (!$config->userFrameworkFrontend) {
+ if (!$config->userFrameworkFrontend || CRM_Core_Session::singleton()->getLoggedInContactID()) {
$this->_editLink = TRUE;
}
}
@@ -514,8 +515,8 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
$locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $names = array();
- static $skipFields = array('group', 'tag');
+ $names = [];
+ static $skipFields = ['group', 'tag'];
foreach ($this->_fields as $key => $field) {
// skip pseudo fields
@@ -547,11 +548,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
continue;
}
$locationTypeName = str_replace(' ', '_', $locationTypeName);
- if (in_array($fieldName, array(
+ if (in_array($fieldName, [
'phone',
'im',
'email',
- ))) {
+ ])) {
if ($type) {
$names[] = "{$locationTypeName}-{$fieldName}-{$type}";
}
@@ -576,7 +577,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
}
}
- $multipleSelectFields = array('preferred_communication_method' => 1);
+ $multipleSelectFields = ['preferred_communication_method' => 1];
$multiRecordTableId = NULL;
if ($this->_multiRecordTableName) {
$multiRecordTableId = "{$this->_multiRecordTableName}_id";
@@ -593,7 +594,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
$i18n = CRM_Core_I18n::singleton();
$result->country = $i18n->translate($result->country);
}
- $row = array();
+ $row = [];
$empty = TRUE;
$row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type,
FALSE,
@@ -634,8 +635,8 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
elseif ($multipleSelectFields &&
array_key_exists($name, $multipleSelectFields)
) {
- $paramsNew = array($name => $result->$name);
- $name = array($name => array('newName' => $name, 'groupName' => $name));
+ $paramsNew = [$name => $result->$name];
+ $name = [$name => ['newName' => $name, 'groupName' => $name]];
CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
$row[] = $paramsNew[$key];
@@ -659,18 +660,18 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
$row[] = $result->$name;
}
}
- elseif (in_array($name, array(
+ elseif (in_array($name, [
'addressee',
'email_greeting',
'postal_greeting',
- ))) {
+ ])) {
$dname = $name . '_display';
$row[] = $result->$dname;
}
- elseif (in_array($name, array(
+ elseif (in_array($name, [
'birth_date',
'deceased_date',
- ))) {
+ ])) {
$row[] = CRM_Utils_Date::customFormat($result->$name);
}
elseif (isset($result->$name)) {
@@ -686,10 +687,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ex
}
$newLinks = $links;
- $params = array(
+ $params = [
'id' => $result->contact_id,
'gid' => implode(',', $this->_profileIds),
- );
+ ];
// pass record id param to view url for multi record view
if ($multiRecordTableId && $newLinks) {
diff --git a/CRM/Queue/BAO/QueueItem.php b/CRM/Queue/BAO/QueueItem.php
index c0e75cafbe1d..7a561c742346 100644
--- a/CRM/Queue/BAO/QueueItem.php
+++ b/CRM/Queue/BAO/QueueItem.php
@@ -1,9 +1,9 @@
__table = 'civicrm_queue_item';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Queue ID') ,
- 'required' => true,
+ 'title' => ts('Queue ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_queue_item.id',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- ) ,
- 'queue_name' => array(
+ ],
+ 'queue_name' => [
'name' => 'queue_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Queue Name') ,
- 'description' => 'Name of the queue which includes this item',
- 'required' => true,
+ 'title' => ts('Queue Name'),
+ 'description' => ts('Name of the queue which includes this item'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_queue_item.queue_name',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'required' => true,
+ 'title' => ts('Order'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_queue_item.weight',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'submit_time' => array(
+ ],
+ ],
+ 'submit_time' => [
'name' => 'submit_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Submit Time') ,
- 'description' => 'date on which this item was submitted to the queue',
- 'required' => true,
+ 'title' => ts('Submit Time'),
+ 'description' => ts('date on which this item was submitted to the queue'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_queue_item.submit_time',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'release_time' => array(
+ ],
+ ],
+ 'release_time' => [
'name' => 'release_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Release Time') ,
- 'description' => 'date on which this job becomes available; null if ASAP',
+ 'title' => ts('Release Time'),
+ 'description' => ts('date on which this job becomes available; null if ASAP'),
+ 'where' => 'civicrm_queue_item.release_time',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'data' => array(
+ ],
+ ],
+ 'data' => [
'name' => 'data',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Queue item datas') ,
- 'description' => 'Serialized queue',
+ 'title' => ts('Queue item data'),
+ 'description' => ts('Serialized queue data'),
+ 'where' => 'civicrm_queue_item.data',
'table_name' => 'civicrm_queue_item',
'entity' => 'QueueItem',
'bao' => 'CRM_Queue_BAO_QueueItem',
'localizable' => 0,
- ) ,
- );
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -215,10 +209,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'queue_item', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'queue_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -226,26 +221,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'queue_item', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'queue_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_queueids' => array(
+ $indices = [
+ 'index_queueids' => [
'name' => 'index_queueids',
- 'field' => array(
+ 'field' => [
0 => 'queue_name',
1 => 'weight',
2 => 'id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_queue_item::0::queue_name::weight::id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Queue/ErrorPolicy.php b/CRM/Queue/ErrorPolicy.php
index 34a68401206a..600b45d25a62 100644
--- a/CRM/Queue/ErrorPolicy.php
+++ b/CRM/Queue/ErrorPolicy.php
@@ -1,9 +1,9 @@
active = TRUE;
- $this->backup = array();
- foreach (array(
- 'display_errors',
- 'html_errors',
- 'xmlrpc_errors',
- ) as $key) {
+ $this->backup = [];
+ foreach ([
+ 'display_errors',
+ 'html_errors',
+ 'xmlrpc_errors',
+ ] as $key) {
$this->backup[$key] = ini_get($key);
ini_set($key, 0);
}
- set_error_handler(array($this, 'onError'), $this->level);
+ set_error_handler([$this, 'onError'], $this->level);
// FIXME make this temporary/reversible
$this->errorScope = CRM_Core_TemporaryErrorScope::useException();
}
@@ -81,11 +81,11 @@ public function activate() {
public function deactivate() {
$this->errorScope = NULL;
restore_error_handler();
- foreach (array(
- 'display_errors',
- 'html_errors',
- 'xmlrpc_errors',
- ) as $key) {
+ foreach ([
+ 'display_errors',
+ 'html_errors',
+ 'xmlrpc_errors',
+ ] as $key) {
ini_set($key, $this->backup[$key]);
}
$this->active = FALSE;
@@ -155,11 +155,11 @@ public function onShutdown() {
* The PHP error (with "type", "message", etc).
*/
public function reportError($error) {
- $response = array(
+ $response = [
'is_error' => 1,
'is_continue' => 0,
'exception' => htmlentities(sprintf('Error %s: %s in %s, line %s', $error['type'], $error['message'], $error['file'], $error['line'])),
- );
+ ];
global $activeQueueRunner;
if (is_object($activeQueueRunner)) {
$response['last_task_title'] = $activeQueueRunner->lastTaskTitle;
@@ -178,10 +178,10 @@ public function reportError($error) {
public function reportException(Exception $e) {
CRM_Core_Error::debug_var('CRM_Queue_ErrorPolicy_reportException', CRM_Core_Error::formatTextException($e));
- $response = array(
+ $response = [
'is_error' => 1,
'is_continue' => 0,
- );
+ ];
$config = CRM_Core_Config::singleton();
if ($config->backtrace || CRM_Core_Config::isUpgradeMode()) {
diff --git a/CRM/Queue/Menu.php b/CRM/Queue/Menu.php
index e14d5b963ddb..43671437fac8 100644
--- a/CRM/Queue/Menu.php
+++ b/CRM/Queue/Menu.php
@@ -1,9 +1,9 @@
title);
- $this->assign('queueRunnerData', array(
+ $this->assign('queueRunnerData', [
'qrid' => $runner->qrid,
'runNextAjax' => CRM_Utils_System::url($runner->pathPrefix . '/ajax/runNext', NULL, FALSE, NULL, FALSE),
'skipNextAjax' => CRM_Utils_System::url($runner->pathPrefix . '/ajax/skipNext', NULL, FALSE, NULL, FALSE),
@@ -64,7 +64,7 @@ public function run() {
'completed' => 0,
'numberOfItems' => $runner->queue->numberOfItems(),
'buttons' => $runner->buttons,
- ));
+ ]);
if ($runner->isMinimal) {
// Render page header
diff --git a/CRM/Queue/Queue.php b/CRM/Queue/Queue.php
index 5cc6dece1963..6057668ddc89 100644
--- a/CRM/Queue/Queue.php
+++ b/CRM/Queue/Queue.php
@@ -1,9 +1,9 @@
items = array();
- $this->releaseTimes = array();
+ $this->items = [];
+ $this->releaseTimes = [];
}
/**
@@ -104,7 +104,7 @@ public function existsQueue() {
* Queue-dependent options; for example, if this is a
* priority-queue, then $options might specify the item's priority.
*/
- public function createItem($data, $options = array()) {
+ public function createItem($data, $options = []) {
$id = $this->nextQueueItemId++;
// force copy, no unintendedsharing effects from pointers
$this->items[$id] = serialize($data);
diff --git a/CRM/Queue/Queue/Sql.php b/CRM/Queue/Queue/Sql.php
index dda9d5a1844e..28f13506de65 100644
--- a/CRM/Queue/Queue/Sql.php
+++ b/CRM/Queue/Queue/Sql.php
@@ -1,9 +1,9 @@
array($this->getName(), 'String'),
- ));
+ ", [
+ 1 => [$this->getName(), 'String'],
+ ]);
}
/**
@@ -92,7 +92,7 @@ public function existsQueue() {
* Queue-dependent options; for example, if this is a
* priority-queue, then $options might specify the item's priority.
*/
- public function createItem($data, $options = array()) {
+ public function createItem($data, $options = []) {
$dao = new CRM_Queue_DAO_QueueItem();
$dao->queue_name = $this->getName();
$dao->submit_time = CRM_Utils_Time::getTime('YmdHis');
@@ -111,9 +111,9 @@ public function numberOfItems() {
SELECT count(*)
FROM civicrm_queue_item
WHERE queue_name = %1
- ", array(
- 1 => array($this->getName(), 'String'),
- ));
+ ", [
+ 1 => [$this->getName(), 'String'],
+ ]);
}
/**
@@ -126,16 +126,23 @@ public function numberOfItems() {
* With key 'data' that matches the inputted data.
*/
public function claimItem($lease_time = 3600) {
+
+ $result = NULL;
+ $dao = CRM_Core_DAO::executeQuery('LOCK TABLES civicrm_queue_item WRITE;');
$sql = "
- SELECT id, queue_name, submit_time, release_time, data
- FROM civicrm_queue_item
- WHERE queue_name = %1
- ORDER BY weight ASC, id ASC
- LIMIT 1
- ";
- $params = array(
- 1 => array($this->getName(), 'String'),
- );
+ SELECT first_in_queue.* FROM (
+ SELECT id, queue_name, submit_time, release_time, data
+ FROM civicrm_queue_item
+ WHERE queue_name = %1
+ ORDER BY weight ASC, id ASC
+ LIMIT 1
+ ) first_in_queue
+ WHERE release_time IS NULL OR release_time < %2
+ ";
+ $params = [
+ 1 => [$this->getName(), 'String'],
+ 2 => [CRM_Utils_Time::getTime(), 'Timestamp'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $params, TRUE, 'CRM_Queue_DAO_QueueItem');
if (is_a($dao, 'DB_Error')) {
// FIXME - Adding code to allow tests to pass
@@ -144,19 +151,22 @@ public function claimItem($lease_time = 3600) {
if ($dao->fetch()) {
$nowEpoch = CRM_Utils_Time::getTimeRaw();
- if ($dao->release_time === NULL || strtotime($dao->release_time) < $nowEpoch) {
- CRM_Core_DAO::executeQuery("UPDATE civicrm_queue_item SET release_time = %1 WHERE id = %2", array(
- '1' => array(date('YmdHis', $nowEpoch + $lease_time), 'String'),
- '2' => array($dao->id, 'Integer'),
- ));
- // work-around: inconsistent date-formatting causes unintentional breakage
- # $dao->submit_time = date('YmdHis', strtotime($dao->submit_time));
- # $dao->release_time = date('YmdHis', $nowEpoch + $lease_time);
- # $dao->save();
- $dao->data = unserialize($dao->data);
- return $dao;
- }
+ CRM_Core_DAO::executeQuery("UPDATE civicrm_queue_item SET release_time = %1 WHERE id = %2", [
+ '1' => [date('YmdHis', $nowEpoch + $lease_time), 'String'],
+ '2' => [$dao->id, 'Integer'],
+ ]);
+ // (Comment by artfulrobot Sep 2019: Not sure what the below comment means, should be removed/clarified?)
+ // work-around: inconsistent date-formatting causes unintentional breakage
+ # $dao->submit_time = date('YmdHis', strtotime($dao->submit_time));
+ # $dao->release_time = date('YmdHis', $nowEpoch + $lease_time);
+ # $dao->save();
+ $dao->data = unserialize($dao->data);
+ $result = $dao;
}
+
+ $dao = CRM_Core_DAO::executeQuery('UNLOCK TABLES;');
+
+ return $result;
}
/**
@@ -176,16 +186,16 @@ public function stealItem($lease_time = 3600) {
ORDER BY weight ASC, id ASC
LIMIT 1
";
- $params = array(
- 1 => array($this->getName(), 'String'),
- );
+ $params = [
+ 1 => [$this->getName(), 'String'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $params, TRUE, 'CRM_Queue_DAO_QueueItem');
if ($dao->fetch()) {
$nowEpoch = CRM_Utils_Time::getTimeRaw();
- CRM_Core_DAO::executeQuery("UPDATE civicrm_queue_item SET release_time = %1 WHERE id = %2", array(
- '1' => array(date('YmdHis', $nowEpoch + $lease_time), 'String'),
- '2' => array($dao->id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery("UPDATE civicrm_queue_item SET release_time = %1 WHERE id = %2", [
+ '1' => [date('YmdHis', $nowEpoch + $lease_time), 'String'],
+ '2' => [$dao->id, 'Integer'],
+ ]);
$dao->data = unserialize($dao->data);
return $dao;
}
@@ -199,7 +209,6 @@ public function stealItem($lease_time = 3600) {
*/
public function deleteItem($dao) {
$dao->delete();
- $dao->free();
}
/**
@@ -210,11 +219,10 @@ public function deleteItem($dao) {
*/
public function releaseItem($dao) {
$sql = "UPDATE civicrm_queue_item SET release_time = NULL WHERE id = %1";
- $params = array(
- 1 => array($dao->id, 'Integer'),
- );
+ $params = [
+ 1 => [$dao->id, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($sql, $params);
- $dao->free();
}
}
diff --git a/CRM/Queue/Runner.php b/CRM/Queue/Runner.php
index 0433f1decb26..fa2817e7130a 100644
--- a/CRM/Queue/Runner.php
+++ b/CRM/Queue/Runner.php
@@ -1,9 +1,9 @@
onEnd = CRM_Utils_Array::value('onEnd', $runnerSpec, NULL);
$this->onEndUrl = CRM_Utils_Array::value('onEndUrl', $runnerSpec, NULL);
$this->pathPrefix = CRM_Utils_Array::value('pathPrefix', $runnerSpec, 'civicrm/queue');
- $this->buttons = CRM_Utils_Array::value('buttons', $runnerSpec, array('retry' => TRUE, 'skip' => TRUE));
+ $this->buttons = CRM_Utils_Array::value('buttons', $runnerSpec, ['retry' => TRUE, 'skip' => TRUE]);
// perhaps this value should be randomized?
$this->qrid = $this->queue->getName();
}
@@ -122,7 +125,7 @@ public function __construct($runnerSpec) {
*/
public function __sleep() {
// exclude taskCtx
- return array(
+ return [
'title',
'queue',
'errorMode',
@@ -132,7 +135,7 @@ public function __sleep() {
'pathPrefix',
'qrid',
'buttons',
- );
+ ];
}
/**
@@ -300,7 +303,7 @@ public function handleEnd() {
}
// Fallback; web UI does redirect in Javascript
- $result = array();
+ $result = [];
$result['is_error'] = 0;
$result['numberOfItems'] = 0;
$result['is_continue'] = 0;
@@ -324,7 +327,7 @@ public function handleEnd() {
public function formatTaskResult($isOK, $exception = NULL) {
$numberOfItems = $this->queue->numberOfItems();
- $result = array();
+ $result = [];
$result['is_error'] = $isOK ? 0 : 1;
$result['exception'] = $exception;
$result['last_task_title'] = isset($this->lastTaskTitle) ? $this->lastTaskTitle : '';
diff --git a/CRM/Queue/Service.php b/CRM/Queue/Service.php
index e855cd6e7575..d7dd024d3946 100644
--- a/CRM/Queue/Service.php
+++ b/CRM/Queue/Service.php
@@ -1,9 +1,9 @@
CRM_Queue_Queue)
+ * Queues.
+ *
+ * Format is (string $queueName => CRM_Queue_Queue).
+ *
+ * @var array
*/
public $queues;
/**
+ * Class constructor.
*/
public function __construct() {
- $this->queues = array();
+ $this->queues = [];
}
/**
diff --git a/CRM/Queue/Task.php b/CRM/Queue/Task.php
index b48b81d0ce90..251bf7130055 100644
--- a/CRM/Queue/Task.php
+++ b/CRM/Queue/Task.php
@@ -1,9 +1,9 @@
_queryObjects === NULL) {
- $this->_queryObjects = array();
+ $this->_queryObjects = [];
CRM_Utils_Hook::queryObjects($this->_queryObjects, 'Report');
}
return $this->_queryObjects;
@@ -98,7 +98,7 @@ public function logDiffClause(&$reportObj, $table) {
$contactIdClause .= $cidClause;
}
}
- return array($contactIdClause, $join);
+ return [$contactIdClause, $join];
}
}
diff --git a/CRM/Report/BAO/HookInterface.php b/CRM/Report/BAO/HookInterface.php
index f01d63a0c694..3b8820c50dac 100644
--- a/CRM/Report/BAO/HookInterface.php
+++ b/CRM/Report/BAO/HookInterface.php
@@ -1,9 +1,9 @@
$value) {
$grouprole_array[$value] = $value;
}
@@ -78,7 +77,7 @@ public static function add(&$params) {
}
$instance = new CRM_Report_DAO_ReportInstance();
- $instance->copyValues($params);
+ $instance->copyValues($params, TRUE);
if (CRM_Core_Config::singleton()->userFramework == 'Joomla') {
$instance->permission = 'null';
@@ -109,10 +108,10 @@ public static function add(&$params) {
$instance->save();
if ($instanceID) {
- CRM_Utils_Hook::pre('edit', 'ReportInstance', $instance->id, $instance);
+ CRM_Utils_Hook::post('edit', 'ReportInstance', $instance->id, $instance);
}
else {
- CRM_Utils_Hook::pre('create', 'ReportInstance', $instance->id, $instance);
+ CRM_Utils_Hook::post('create', 'ReportInstance', $instance->id, $instance);
}
return $instance;
}
@@ -140,11 +139,11 @@ public static function &create(&$params) {
// build navigation parameters
if (!empty($params['is_navigation'])) {
if (!array_key_exists('navigation', $params)) {
- $params['navigation'] = array();
+ $params['navigation'] = [];
}
$navigationParams =& $params['navigation'];
- $navigationParams['permission'] = array();
+ $navigationParams['permission'] = [];
$navigationParams['label'] = $params['title'];
$navigationParams['name'] = $params['title'];
@@ -168,12 +167,12 @@ public static function &create(&$params) {
}
// add to dashboard
- $dashletParams = array();
+ $dashletParams = [];
if (!empty($params['addToDashboard'])) {
- $dashletParams = array(
+ $dashletParams = [
'label' => $params['title'],
'is_active' => 1,
- );
+ ];
if ($permission = CRM_Utils_Array::value('permission', $params)) {
$dashletParams['permission'][] = $permission;
}
@@ -268,7 +267,6 @@ public static function retrieve($params, &$defaults) {
if ($instance->find(TRUE)) {
CRM_Core_DAO::storeValues($instance, $defaults);
- $instance->free();
return $instance;
}
return NULL;
@@ -364,32 +362,43 @@ public static function doFormDelete($instanceId, $bounceTo = 'civicrm/report/lis
* - general script-add.
*/
public static function getActionMetadata() {
- $actions = array(
- 'report_instance.save' => array('title' => ts('Save')),
- 'report_instance.copy' => array(
+ $actions = [];
+ if (CRM_Core_Permission::check('save Report Criteria')) {
+ $actions['report_instance.save'] = ['title' => ts('Save')];
+ $actions['report_instance.copy'] = [
'title' => ts('Save a Copy'),
- 'data' => array(
+ 'data' => [
'is_confirm' => TRUE,
'confirm_title' => ts('Save a copy...'),
- 'confirm_refresh_fields' => json_encode(array(
- 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ts('(Copy) ')),
- 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
- 'parent_id' => array('selector' => '.crm-report-instanceForm-form-block-parent_id', 'prepend' => ''),
- )),
- ),
- ),
- 'report_instance.print' => array('title' => ts('Print Report')),
- 'report_instance.pdf' => array('title' => ts('Print to PDF')),
- 'report_instance.csv' => array('title' => ts('Export as CSV')),
- );
+ 'confirm_refresh_fields' => json_encode([
+ 'title' => [
+ 'selector' => '.crm-report-instanceForm-form-block-title',
+ 'prepend' => ts('(Copy) '),
+ ],
+ 'description' => [
+ 'selector' => '.crm-report-instanceForm-form-block-description',
+ 'prepend' => '',
+ ],
+ 'parent_id' => [
+ 'selector' => '.crm-report-instanceForm-form-block-parent_id',
+ 'prepend' => '',
+ ],
+ ]),
+ ],
+ ];
+ }
+ $actions['report_instance.print'] = ['title' => ts('Print Report')];
+ $actions['report_instance.pdf'] = ['title' => ts('Print to PDF')];
+ $actions['report_instance.csv'] = ['title' => ts('Export as CSV')];
+
if (CRM_Core_Permission::check('administer Reports')) {
- $actions['report_instance.delete'] = array(
+ $actions['report_instance.delete'] = [
'title' => ts('Delete report'),
- 'data' => array(
+ 'data' => [
'is_confirm' => TRUE,
'confirm_message' => ts('Are you sure you want delete this report? This action cannot be undone.'),
- ),
- );
+ ],
+ ];
}
return $actions;
}
diff --git a/CRM/Report/DAO/ReportInstance.php b/CRM/Report/DAO/ReportInstance.php
index dbf8e30875b8..584131d54308 100644
--- a/CRM/Report/DAO/ReportInstance.php
+++ b/CRM/Report/DAO/ReportInstance.php
@@ -1,545 +1,563 @@
__table = 'civicrm_report_instance';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'owner_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'navigation_id', 'civicrm_navigation', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'drilldown_id', 'civicrm_report_instance', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'owner_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'navigation_id', 'civicrm_navigation', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'drilldown_id', 'civicrm_report_instance', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Report Instance ID') ,
- 'description' => 'Report Instance ID',
- 'required' => true,
+ 'title' => ts('Report Instance ID'),
+ 'description' => ts('Report Instance ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_report_instance.id',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Report Instance Domain ID') ,
- 'description' => 'Which Domain is this instance for',
- 'required' => true,
+ 'title' => ts('Report Instance Domain ID'),
+ 'description' => ts('Which Domain is this instance for'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_report_instance.domain_id',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'title' => array(
+ ],
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance Title') ,
- 'description' => 'Report Instance Title.',
+ 'title' => ts('Report Instance Title'),
+ 'description' => ts('Report Instance Title.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.title',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'report_id' => array(
+ ],
+ ],
+ 'report_id' => [
'name' => 'report_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report template ID') ,
- 'description' => 'FK to civicrm_option_value for the report template',
- 'required' => true,
- 'maxlength' => 64,
- 'size' => CRM_Utils_Type::BIG,
+ 'title' => ts('Report template ID'),
+ 'description' => ts('FK to civicrm_option_value for the report template'),
+ 'required' => TRUE,
+ 'maxlength' => 512,
+ 'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.report_id',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'name' => array(
+ ],
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report instance Name') ,
- 'description' => 'when combined with report_id/template uniquely identifies the instance',
+ 'title' => ts('Report instance Name'),
+ 'description' => ts('when combined with report_id/template uniquely identifies the instance'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.name',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'args' => array(
+ ],
+ ],
+ 'args' => [
'name' => 'args',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance Arguments') ,
- 'description' => 'arguments that are passed in the url when invoking the instance',
+ 'title' => ts('Report Instance Arguments'),
+ 'description' => ts('arguments that are passed in the url when invoking the instance'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.args',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance description') ,
- 'description' => 'Report Instance description.',
+ 'title' => ts('Report Instance description'),
+ 'description' => ts('Report Instance description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.description',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'permission' => array(
+ ],
+ ],
+ 'permission' => [
'name' => 'permission',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance Permissions') ,
- 'description' => 'permission required to be able to run this instance',
+ 'title' => ts('Report Instance Permissions'),
+ 'description' => ts('permission required to be able to run this instance'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.permission',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'grouprole' => array(
+ ],
+ ],
+ 'grouprole' => [
'name' => 'grouprole',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance Assigned to Roles') ,
- 'description' => 'role required to be able to run this instance',
+ 'title' => ts('Report Instance Assigned to Roles'),
+ 'description' => ts('role required to be able to run this instance'),
'maxlength' => 1024,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.grouprole',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'form_values' => array(
+ ],
+ ],
+ 'form_values' => [
'name' => 'form_values',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Submitted Form Values') ,
- 'description' => 'Submitted form values for this report',
- 'import' => true,
+ 'title' => ts('Submitted Form Values'),
+ 'description' => ts('Submitted form values for this report'),
+ 'import' => TRUE,
'where' => 'civicrm_report_instance.form_values',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Report Instance is Active') ,
- 'description' => 'Is this entry active?',
+ 'title' => ts('Report Instance is Active'),
+ 'description' => ts('Is this entry active?'),
+ 'where' => 'civicrm_report_instance.is_active',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'created_id' => array(
+ ],
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Report Instance Created By') ,
- 'description' => 'FK to contact table.',
+ 'title' => ts('Report Instance Created By'),
+ 'description' => ts('FK to contact table.'),
+ 'where' => 'civicrm_report_instance.created_id',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'owner_id' => array(
+ ],
+ 'owner_id' => [
'name' => 'owner_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Report Instance Owned By') ,
- 'description' => 'FK to contact table.',
+ 'title' => ts('Report Instance Owned By'),
+ 'description' => ts('FK to contact table.'),
+ 'where' => 'civicrm_report_instance.owner_id',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'email_subject' => array(
+ ],
+ 'email_subject' => [
'name' => 'email_subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Report Instance email Subject') ,
- 'description' => 'Subject of email',
+ 'title' => ts('Report Instance email Subject'),
+ 'description' => ts('Subject of email'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_report_instance.email_subject',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'email_to' => array(
+ ],
+ ],
+ 'email_to' => [
'name' => 'email_to',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Email Report Instance To') ,
- 'description' => 'comma-separated list of email addresses to send the report to',
+ 'title' => ts('Email Report Instance To'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
+ 'where' => 'civicrm_report_instance.email_to',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'email_cc' => array(
+ ],
+ ],
+ 'email_cc' => [
'name' => 'email_cc',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('cc Email Report Instance To') ,
- 'description' => 'comma-separated list of email addresses to send the report to',
+ 'title' => ts('cc Email Report Instance To'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
+ 'where' => 'civicrm_report_instance.email_cc',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'header' => array(
+ ],
+ ],
+ 'header' => [
'name' => 'header',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Report Instance Header') ,
- 'description' => 'comma-separated list of email addresses to send the report to',
+ 'title' => ts('Report Instance Header'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_report_instance.header',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'footer' => array(
+ ],
+ ],
+ 'footer' => [
'name' => 'footer',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Report Instance Footer') ,
- 'description' => 'comma-separated list of email addresses to send the report to',
+ 'title' => ts('Report Instance Footer'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_report_instance.footer',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'navigation_id' => array(
+ ],
+ ],
+ 'navigation_id' => [
'name' => 'navigation_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Navigation ID') ,
- 'description' => 'FK to navigation ID',
- 'import' => true,
+ 'title' => ts('Navigation ID'),
+ 'description' => ts('FK to navigation ID'),
+ 'import' => TRUE,
'where' => 'civicrm_report_instance.navigation_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Navigation',
- ) ,
- 'drilldown_id' => array(
+ ],
+ 'drilldown_id' => [
'name' => 'drilldown_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Drilldown Report ID') ,
- 'description' => 'FK to instance ID drilldown to',
- 'import' => true,
+ 'title' => ts('Drilldown Report ID'),
+ 'description' => ts('FK to instance ID drilldown to'),
+ 'import' => TRUE,
'where' => 'civicrm_report_instance.drilldown_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
'FKClassName' => 'CRM_Report_DAO_ReportInstance',
- ) ,
- 'is_reserved' => array(
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Instance is Reserved') ,
+ 'title' => ts('Instance is Reserved'),
+ 'where' => 'civicrm_report_instance.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_report_instance',
'entity' => 'ReportInstance',
'bao' => 'CRM_Report_BAO_ReportInstance',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -547,10 +565,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'report_instance', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'report_instance', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -558,15 +577,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'report_instance', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'report_instance', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Report/Form.php b/CRM/Report/Form.php
index 9892c29aa1ac..783026daa273 100644
--- a/CRM/Report/Form.php
+++ b/CRM/Report/Form.php
@@ -1,9 +1,9 @@
';
- $row .= ' ';
- }
-
- $duplicateContactsLinks .= $row . ' ';
- $row .= $contactLinks['rows'][$i]['display_name'];
- $row .= ' ';
- $row .= ' ';
- $row .= $contactLinks['rows'][$i]['primary_email'];
- $row .= ' ';
- $row .= ' ';
- $row .= $contactLinks['rows'][$i]['view'] . ' ';
- $row .= $contactLinks['rows'][$i]['edit'];
- $row .= ' ';
- $row .= ' ',
' ',
' ',
'
"; exit(); } @@ -203,11 +206,23 @@ public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location * @throws CRM_Core_Exception */ public function processInbound($from, $body, $to = NULL, $trackID = NULL) { - $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like"); - $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String'); - $fromContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $escapedFrom . '"'); + $message = new CRM_SMS_Message(); + $message->from = $from; + $message->to = $to; + $message->body = $body; + $message->trackID = $trackID; + // call hook_civicrm_inboundSMS + CRM_Utils_Hook::inboundSMS($message); + + if (!$message->fromContactID) { + // find sender by phone number if $fromContactID not set by hook + $formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from), $like, "like"); + $message->fromContactID = CRM_Core_DAO::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array( + 1 => array($formatFrom, 'String'), + )); + } - if (!$fromContactID) { + if (!$message->fromContactID) { // unknown mobile sender -- create new contact // use fake @mobile.sms email address for new contact since civi // requires email or name for all contacts @@ -215,7 +230,7 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) { $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $phoneloc = array_search('Home', $locationTypes); $phonetype = array_search('Mobile', $phoneTypes); - $stripFrom = $this->stripPhone($from); + $stripFrom = $this->stripPhone($message->from); $contactparams = array( 'contact_type' => 'Individual', 'email' => array( @@ -233,38 +248,38 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) { ), ); $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE); - $fromContactID = $fromContact->id; + $message->fromContactID = $fromContact->id; } - if ($to) { - $to = CRM_Utils_Type::escape($to, 'String'); - $toContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $to . '"'); - } - else { - $toContactID = $fromContactID; + if (!$message->toContactID) { + // find recipient if $toContactID not set by hook + if ($message->to) { + $message->toContactID = CRM_Core_DAO::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array( + 1 => array('%' . $message->to, 'String'), + )); + } + else { + $message->toContactID = $message->fromContactID; + } } - if ($fromContactID) { - $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status')); - $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'); - + if ($message->fromContactID) { // note: lets not pass status here, assuming status will be updated by callback $activityParams = array( - 'source_contact_id' => $toContactID, - 'target_contact_id' => $fromContactID, - 'activity_type_id' => $activityTypeID, + 'source_contact_id' => $message->toContactID, + 'target_contact_id' => $message->fromContactID, + 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'), 'activity_date_time' => date('YmdHis'), - 'status_id' => $actStatusIDs['Completed'], - 'details' => $body, - 'phone_number' => $from, + 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'), + 'details' => $message->body, + 'phone_number' => $message->from, ); - if ($trackID) { - $trackID = CRM_Utils_Type::escape($trackID, 'String'); - $activityParams['result'] = $trackID; + if ($message->trackID) { + $activityParams['result'] = CRM_Utils_Type::escape($message->trackID, 'String'); } $result = CRM_Activity_BAO_Activity::create($activityParams); - CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}."); + Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}."); return $result; } } diff --git a/CRM/SMS/StateMachine/Send.php b/CRM/SMS/StateMachine/Send.php index 985b078c4f90..1d4646114fe1 100644 --- a/CRM/SMS/StateMachine/Send.php +++ b/CRM/SMS/StateMachine/Send.php @@ -1,9 +1,9 @@ _pages = array( + $this->_pages = [ 'CRM_SMS_Form_Group' => NULL, 'CRM_SMS_Form_Upload' => NULL, 'CRM_SMS_Form_Schedule' => NULL, - ); + ]; $this->addSequentialPages($this->_pages, $action); } diff --git a/CRM/Tag/Form/Edit.php b/CRM/Tag/Form/Edit.php index 0919c7f07005..14b4adb6e124 100644 --- a/CRM/Tag/Form/Edit.php +++ b/CRM/Tag/Form/Edit.php @@ -1,9 +1,9 @@ _action == CRM_Core_Action::DELETE) { - $url = CRM_Utils_System::url('civicrm/tag'); if (!$this->_id) { $this->_id = explode(',', CRM_Utils_Request::retrieve('id', 'String')); } $this->_id = (array) $this->_id; if (!$this->_id) { - CRM_Core_Error::statusBounce(ts("Unknown tag."), $url); + CRM_Core_Error::statusBounce(ts("Unknown tag."), $bounceUrl); } foreach ($this->_id as $id) { if (!CRM_Utils_Rule::positiveInteger($id)) { - CRM_Core_Error::statusBounce(ts("Unknown tag."), $url); + CRM_Core_Error::statusBounce(ts("Unknown tag."), $bounceUrl); } if ($tag = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'name', 'parent_id')) { - CRM_Core_Error::statusBounce(ts("This tag cannot be deleted. You must delete all its child tags ('%1', etc) prior to deleting this tag.", array(1 => $tag)), $url); + CRM_Core_Error::statusBounce(ts("This tag cannot be deleted. You must delete all its child tags ('%1', etc) prior to deleting this tag.", [1 => $tag]), $bounceUrl); } if (!CRM_Core_Permission::check('administer reserved tags') && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved')) { - CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to delete this reserved tag."), $url); + CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to delete this reserved tag."), $bounceUrl); } } if (count($this->_id) > 1) { - $this->assign('delName', ts('%1 tags', array(1 => count($this->_id)))); + $this->assign('delName', ts('%1 tags', [1 => count($this->_id)])); } } else { + $adminTagset = CRM_Core_Permission::check('administer Tagsets'); + $adminReservedTags = CRM_Core_Permission::check('administer reserved tags'); + $this->_isTagSet = CRM_Utils_Request::retrieve('tagset', 'Positive', $this); if (!$this->_isTagSet && $this->_id && @@ -86,6 +89,12 @@ public function buildQuickForm() { ) { $this->_isTagSet = TRUE; } + if ($this->_isTagSet && !$adminTagset) { + CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to edit this tagset."), $bounceUrl); + } + if ($this->_id && !$adminReservedTags && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $this->_id, 'is_reserved')) { + CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to edit this reserved tag."), $bounceUrl); + } if ($this->_id) { $parentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $this->_id, 'parent_id'); @@ -98,7 +107,7 @@ public function buildQuickForm() { if (!$this->_isTagSet) { if (!$isTagSetChild) { $colorTags = CRM_Core_BAO_Tag::getColorTags(NULL, TRUE, $this->_id); - $this->add('select2', 'parent_id', ts('Parent Tag'), $colorTags, FALSE, array('placeholder' => ts('- select -'))); + $this->add('select2', 'parent_id', ts('Parent Tag'), $colorTags, FALSE, ['placeholder' => ts('- select -')]); } // Tagsets are not selectable by definition so only include the selectable field if NOT a tagset. @@ -118,10 +127,10 @@ public function buildQuickForm() { $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'name'), TRUE ); - $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array( - 'CRM_Core_DAO_Tag', - $this->_id, - )); + $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [ + 'CRM_Core_DAO_Tag', + $this->_id, + ]); $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'description') @@ -130,19 +139,13 @@ public function buildQuickForm() { $isReserved = $this->add('checkbox', 'is_reserved', ts('Reserved?')); if (!$isTagSetChild) { - $this->addSelect('used_for', array('multiple' => TRUE, 'option_url' => NULL)); + $this->addSelect('used_for', ['multiple' => TRUE, 'option_url' => NULL]); } - $adminTagset = TRUE; - if (!CRM_Core_Permission::check('administer Tagsets')) { - $adminTagset = FALSE; - } $this->assign('adminTagset', $adminTagset); - $adminReservedTags = TRUE; - if (!CRM_Core_Permission::check('administer reserved tags')) { + if (!$adminReservedTags) { $isReserved->freeze(); - $adminReservedTags = FALSE; } $this->assign('adminReservedTags', $adminReservedTags); } @@ -159,9 +162,12 @@ public function setDefaultValues() { $defaults = parent::setDefaultValues(); $cloneFrom = CRM_Utils_Request::retrieve('clone_from', 'Integer'); if (empty($this->_id) && $cloneFrom) { - $params = array('id' => $cloneFrom); + $params = ['id' => $cloneFrom]; CRM_Core_BAO_Tag::retrieve($params, $this->_values); $this->_values['name'] .= ' (' . ts('copy') . ')'; + if (!empty($this->_values['is_reserved']) && !CRM_Core_Permission::check('administer reserved tags')) { + $this->_values['is_reserved'] = 0; + } $defaults = $this->_values; } if (empty($defaults['color'])) { @@ -179,7 +185,7 @@ public function setDefaultValues() { public function postProcess() { if ($this->_action == CRM_Core_Action::DELETE) { $deleted = 0; - $tag = civicrm_api3('tag', 'getsingle', array('id' => $this->_id[0])); + $tag = civicrm_api3('tag', 'getsingle', ['id' => $this->_id[0]]); foreach ($this->_id as $id) { if (CRM_Core_BAO_Tag::del($id)) { $deleted++; @@ -187,14 +193,14 @@ public function postProcess() { } if (count($this->_id) == 1 && $deleted == 1) { if ($tag['is_tagset']) { - CRM_Core_Session::setStatus(ts("The tag set '%1' has been deleted.", array(1 => $tag['name'])), ts('Deleted'), 'success'); + CRM_Core_Session::setStatus(ts("The tag set '%1' has been deleted.", [1 => $tag['name']]), ts('Deleted'), 'success'); } else { - CRM_Core_Session::setStatus(ts("The tag '%1' has been deleted.", array(1 => $tag['name'])), ts('Deleted'), 'success'); + CRM_Core_Session::setStatus(ts("The tag '%1' has been deleted.", [1 => $tag['name']]), ts('Deleted'), 'success'); } } else { - CRM_Core_Session::setStatus(ts("Deleted %1 tags.", array(1 => $deleted)), ts('Deleted'), 'success'); + CRM_Core_Session::setStatus(ts("Deleted %1 tags.", [1 => $deleted]), ts('Deleted'), 'success'); } } else { @@ -227,7 +233,7 @@ public function postProcess() { $params['is_selectable'] = 0; } $tag = CRM_Core_BAO_Tag::add($params); - CRM_Core_Session::setStatus(ts("The tag '%1' has been saved.", array(1 => $tag->name)), ts('Saved'), 'success'); + CRM_Core_Session::setStatus(ts("The tag '%1' has been saved.", [1 => $tag->name]), ts('Saved'), 'success'); $this->ajaxResponse['tag'] = $tag->toArray(); } CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/tag')); diff --git a/CRM/Tag/Form/Merge.php b/CRM/Tag/Form/Merge.php index f6778083d0b1..67ef526fb430 100644 --- a/CRM/Tag/Form/Merge.php +++ b/CRM/Tag/Form/Merge.php @@ -1,9 +1,9 @@ _id) < 2) { CRM_Core_Error::statusBounce(ts("You must select at least 2 tags for merging."), $url); } - $tags = civicrm_api3('Tag', 'get', array('id' => array('IN' => $this->_id), 'options' => array('limit' => 0))); + $tags = civicrm_api3('Tag', 'get', ['id' => ['IN' => $this->_id], 'options' => ['limit' => 0]]); $this->_tags = $tags['values']; if (count($this->_id) != count($this->_tags)) { CRM_Core_Error::statusBounce(ts("Unknown tag."), $url); @@ -66,19 +66,18 @@ public function buildQuickForm() { $this->add('text', 'name', ts('Name of combined tag'), TRUE); $this->assign('tags', CRM_Utils_Array::collect('name', $this->_tags)); - $this->addButtons(array( - array( + $this->addButtons([ + [ 'type' => 'next', 'name' => ts('Merge'), 'spacing' => ' ', 'isDefault' => TRUE, - ), - array( + ], + [ 'type' => 'cancel', 'name' => ts('Cancel'), - ), - ) - ); + ], + ]); } /** @@ -88,9 +87,9 @@ public function buildQuickForm() { */ public function setDefaultValues() { $primary = CRM_Utils_Array::first($this->_tags); - return array( + return [ 'name' => $primary['name'], - ); + ]; } /** @@ -106,7 +105,7 @@ public function postProcess() { } if ($params['name'] != $primary['name']) { - civicrm_api3('Tag', 'create', array('id' => $primary['id'], 'name' => $params['name'])); + civicrm_api3('Tag', 'create', ['id' => $primary['id'], 'name' => $params['name']]); } $key = array_search($params['name'], $deleted); @@ -115,8 +114,8 @@ public function postProcess() { } CRM_Core_Session::setStatus( - ts('All records previously tagged %1 are now tagged %2.', array(1 => implode(' ' . ts('or') . ' ', $deleted), 2 => $params['name'])), - ts('%1 Tags Merged', array(1 => count($this->_id))), + ts('All records previously tagged %1 are now tagged %2.', [1 => implode(' ' . ts('or') . ' ', $deleted), 2 => $params['name']]), + ts('%1 Tags Merged', [1 => count($this->_id)]), 'success' ); diff --git a/CRM/Tag/Form/Tag.php b/CRM/Tag/Form/Tag.php index 231fb43db0a4..27e5048e21b4 100644 --- a/CRM/Tag/Form/Tag.php +++ b/CRM/Tag/Form/Tag.php @@ -1,9 +1,9 @@ $varValue) { if (in_array($tagID, $entityTag)) { - $tagAttribute = array( + $tagAttribute = [ 'checked' => 'checked', 'id' => "tag_{$tagID}", - ); + ]; } else { - $tagAttribute = array( + $tagAttribute = [ 'id' => "tag_{$tagID}", - ); + ]; } $tagChk[$tagID] = $this->createElement('checkbox', $tagID, '', '', $tagAttribute); @@ -113,7 +113,7 @@ public function buildQuickForm() { * @return void */ public function postProcess() { - CRM_Utils_System::flushCache('CRM_Core_DAO_Tag'); + CRM_Utils_System::flushCache(); // array contains the posted values // exportvalues is not used because its give value 1 of the checkbox which were checked by default, diff --git a/CRM/Tag/Page/Tag.php b/CRM/Tag/Page/Tag.php index 1c98beca0462..11d899a511f9 100644 --- a/CRM/Tag/Page/Tag.php +++ b/CRM/Tag/Page/Tag.php @@ -1,9 +1,9 @@ addScriptFile('civicrm', 'bower_components/jstree/dist/jstree.min.js', 0, 'html-header') ->addStyleFile('civicrm', 'bower_components/jstree/dist/themes/default/style.min.css') - ->addPermissions(array('administer reserved tags', 'administer Tagsets')); + ->addPermissions(['administer reserved tags', 'administer Tagsets']); - $usedFor = $tagsets = array(); + $usedFor = $tagsets = []; - $result = civicrm_api3('OptionValue', 'get', array( - 'return' => array("value", "name"), + $result = civicrm_api3('OptionValue', 'get', [ + 'return' => ["value", "name"], 'option_group_id' => "tag_used_for", - )); + ]); foreach ($result['values'] as $value) { $usedFor[$value['value']] = $value['name']; } - $result = civicrm_api3('Tag', 'get', array( - 'return' => array("name", "used_for", "description", "created_id.display_name", "created_date", "is_reserved"), + $result = civicrm_api3('Tag', 'get', [ + 'return' => ["name", "used_for", "description", "created_id.display_name", "created_date", "is_reserved"], 'is_tagset' => 1, - 'options' => array('limit' => 0), - )); + 'options' => ['limit' => 0], + ]); foreach ($result['values'] as $id => $tagset) { $used = explode(',', CRM_Utils_Array::value('used_for', $tagset, '')); $tagset['used_for_label'] = array_values(array_intersect_key($usedFor, array_flip($used))); diff --git a/CRM/UF/Form/AbstractPreview.php b/CRM/UF/Form/AbstractPreview.php index 3e41c2c12ac7..d0b0889b0392 100644 --- a/CRM/UF/Form/AbstractPreview.php +++ b/CRM/UF/Form/AbstractPreview.php @@ -1,9 +1,9 @@ _fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER); @@ -111,6 +111,7 @@ public function buildQuickForm() { * * @return string */ + /** * @return string */ diff --git a/CRM/UF/Form/AdvanceSetting.php b/CRM/UF/Form/AdvanceSetting.php index 28a6c62d30e5..7caff1af5dea 100644 --- a/CRM/UF/Form/AdvanceSetting.php +++ b/CRM/UF/Form/AdvanceSetting.php @@ -1,9 +1,9 @@ assign('advancedFieldsConverted', $entityFields); + // should mapping be enabled for this group $form->addElement('checkbox', 'is_map', ts('Enable mapping for this profile?')); // should we allow updates on a exisitng contact - $options = array(); + $options = []; $options[] = $form->createElement('radio', NULL, NULL, ts('Issue warning and do not save'), 0); $options[] = $form->createElement('radio', NULL, NULL, ts('Update the matching contact'), 1); $options[] = $form->createElement('radio', NULL, NULL, ts('Allow duplicate contact to be created'), 2); @@ -50,10 +56,12 @@ public static function buildAdvanceSetting(&$form) { $form->addGroup($options, 'is_update_dupe', ts('What to do upon duplicate match')); // we do not have any url checks to allow relative urls $form->addElement('text', 'post_URL', ts('Redirect URL'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFGroup', 'post_URL')); + + $form->add('advcheckbox', 'add_cancel_button', ts('Include Cancel Button?')); $form->addElement('text', 'cancel_URL', ts('Cancel Redirect URL'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFGroup', 'cancel_URL')); // add select for groups - $group = array('' => ts('- select -')) + $form->_group; + $group = ['' => ts('- select -')] + $form->_group; $form->_groupElement = &$form->addElement('select', 'group', ts('Limit listings to a specific Group?'), $group); //add notify field @@ -70,7 +78,7 @@ public static function buildAdvanceSetting(&$form) { // should we display a link to the website profile $config = CRM_Core_Config::singleton(); - $form->addElement('checkbox', 'is_uf_link', ts('Include %1 user account information links in search results?', array(1 => $config->userFramework))); + $form->addElement('checkbox', 'is_uf_link', ts('Include %1 user account information links in search results?', [1 => $config->userFramework])); // want to create cms user $session = CRM_Core_Session::singleton(); @@ -79,15 +87,15 @@ public static function buildAdvanceSetting(&$form) { $form->_cmsId = TRUE; } - $options = array(); + $options = []; $options[] = $form->createElement('radio', NULL, NULL, ts('No account create option'), 0); $options[] = $form->createElement('radio', NULL, NULL, ts('Give option, but not required'), 1); $options[] = $form->createElement('radio', NULL, NULL, ts('Account creation required'), 2); - $form->addGroup($options, 'is_cms_user', ts('%1 user account registration option?', array(1 => $config->userFramework))); + $form->addGroup($options, 'is_cms_user', ts('%1 user account registration option?', [1 => $config->userFramework])); // options for including Proximity Search in the profile search form - $proxOptions = array(); + $proxOptions = []; $proxOptions[] = $form->createElement('radio', NULL, NULL, ts('None'), 0); $proxOptions[] = $form->createElement('radio', NULL, NULL, ts('Optional'), 1); $proxOptions[] = $form->createElement('radio', NULL, NULL, ts('Required'), 2); diff --git a/CRM/UF/Form/Field.php b/CRM/UF/Form/Field.php index 35bd5f45d2c5..0f0eb5ecde4c 100644 --- a/CRM/UF/Form/Field.php +++ b/CRM/UF/Form/Field.php @@ -1,9 +1,9 @@ pushUserContext($url); - $breadCrumb = array( - array( + $breadCrumb = [ + [ 'title' => ts('CiviCRM Profile Fields'), 'url' => $url, - ), - ); + ], + ]; CRM_Utils_System::appendBreadCrumb($breadCrumb); } @@ -149,7 +149,7 @@ public function preProcess() { $this->_fields = array_merge($this->_fields, CRM_Contact_BAO_Query_Hook::singleton()->getFields()); - $this->_selectFields = array(); + $this->_selectFields = []; foreach ($this->_fields as $name => $field) { // lets skip note for now since we dont support it if ($name == 'note') { @@ -182,30 +182,31 @@ public function preProcess() { */ public function buildQuickForm() { if ($this->_action & CRM_Core_Action::DELETE) { - $this->addButtons(array( - array( + $this->addButtons([ + [ 'type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => ' ', 'isDefault' => TRUE, - ), - array( + ], + [ 'type' => 'cancel', 'name' => ts('Cancel'), - ), - )); + ], + ]); return; } + $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address')); if (isset($this->_id)) { - $params = array('id' => $this->_id); + $params = ['id' => $this->_id]; CRM_Core_BAO_UFField::retrieve($params, $defaults); // set it to null if so (avoids crappy E_NOTICE errors below $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults); - $specialFields = CRM_Core_BAO_UFGroup::getLocationFields(); - + //CRM-20861 - Include custom fields defined for address to set its default location type to 0. + $specialFields = array_merge(CRM_Core_BAO_UFGroup::getLocationFields(), $addressCustomFields); if (!$defaults['location_type_id'] && $defaults["field_type"] != "Formatting" && in_array($defaults['field_name'], $specialFields) @@ -213,12 +214,12 @@ public function buildQuickForm() { $defaults['location_type_id'] = 0; } - $defaults['field_name'] = array( + $defaults['field_name'] = [ $defaults['field_type'], ($defaults['field_type'] == "Formatting" ? "" : $defaults['field_name']), ($defaults['field_name'] == "url") ? $defaults['website_type_id'] : $defaults['location_type_id'], CRM_Utils_Array::value('phone_type_id', $defaults), - ); + ]; $this->_gid = $defaults['uf_group_id']; } else { @@ -229,7 +230,7 @@ public function buildQuickForm() { $this->assign('otherModules', $otherModules); if ($this->_action & CRM_Core_Action::ADD) { - $fieldValues = array('uf_group_id' => $this->_gid); + $fieldValues = ['uf_group_id' => $this->_gid]; $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues); } @@ -244,8 +245,7 @@ public function buildQuickForm() { $fields = CRM_Core_BAO_UFField::getAvailableFields($this->_gid, $defaults); - $noSearchable = $hasWebsiteTypes = array(); - $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address')); + $noSearchable = $hasWebsiteTypes = []; foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { @@ -290,20 +290,20 @@ public function buildQuickForm() { if ($defaultLocationType) { $defaultLocation = $this->_location_types[$defaultLocationType->id]; unset($this->_location_types[$defaultLocationType->id]); - $this->_location_types = array( + $this->_location_types = [ $defaultLocationType->id => $defaultLocation, - ) + $this->_location_types; + ] + $this->_location_types; } - $this->_location_types = array('Primary') + $this->_location_types; + $this->_location_types = ['Primary'] + $this->_location_types; // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE); unset($contactTypes['']); - $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array(); - $sel1 = array('' => '- select -') + $contactTypes; + $contactTypes = !empty($contactTypes) ? ['Contact' => 'Contacts'] + $contactTypes : []; + $sel1 = ['' => '- select -'] + $contactTypes; if (!empty($fields['Activity'])) { $sel1['Activity'] = 'Activity'; @@ -365,7 +365,7 @@ public function buildQuickForm() { } } - $this->_defaults = array(); + $this->_defaults = []; $js = "@siu', '@
@siu', @@ -113,8 +104,8 @@ public static function html2pdf(&$text, $fileName = 'civicrm.pdf', $output = FAL '@]*?>@siu', '@@siu', '@]*?>@siu', - ); - $htmlElementsInstead = array('', '', '', '', '', ''); + ]; + $htmlElementsInstead = ['', '', '', '', '', '']; foreach ($pages as & $page) { $page = preg_replace($htmlElementstoStrip, $htmlElementsInstead, @@ -127,12 +118,11 @@ public static function html2pdf(&$text, $fileName = 'civicrm.pdf', $output = FAL "; - if ($config->wkhtmltopdfPath) { + if (CRM_Core_Config::singleton()->wkhtmltopdfPath) { return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName); } else { return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName); - //return self::_html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path); } } @@ -152,9 +142,10 @@ public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $htm // This function also uses the FPDI library documented at: http://www.setasign.com/products/fpdi/about/ // Syntax borrowed from https://github.com/jake-mw/CDNTaxReceipts/blob/master/cdntaxreceipts.functions.inc require_once 'tcpdf/tcpdf.php'; - require_once 'FPDI/fpdi.php'; // This library is only in the 'packages' area as of version 4.5 + // This library is only in the 'packages' area as of version 4.5 + require_once 'FPDI/fpdi.php'; - $paper_size_arr = array($paper_size[2], $paper_size[3]); + $paper_size_arr = [$paper_size[2], $paper_size[3]]; $pdf = new TCPDF($orientation, 'pt', $paper_size_arr); $pdf->Open(); @@ -189,7 +180,7 @@ public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $htm $pdf->Close(); $pdf_file = 'CiviLetter' . '.pdf'; $pdf->Output($pdf_file, 'D'); - CRM_Utils_System::civiExit(1); + CRM_Utils_System::civiExit(); } /** diff --git a/CRM/Utils/Pager.php b/CRM/Utils/Pager.php index bd33490a8361..390764d766ac 100644 --- a/CRM/Utils/Pager.php +++ b/CRM/Utils/Pager.php @@ -1,9 +1,9 @@ $start, 2 => $end, 3 => $params['total'])); + $statusMessage = ts('%1 - %2 of %3', [1 => $start, 2 => $end, 3 => $params['total']]); } $params['status'] = str_replace('%%StatusMessage%%', $statusMessage, $params['status']); - $this->_response = array( + $this->_response = [ 'first' => $this->getFirstPageLink(), 'back' => $this->getBackPageLink(), 'next' => $this->getNextPageLink(), @@ -104,21 +104,21 @@ public function __construct($params) { 'buttonTop' => CRM_Utils_Array::value('buttonTop', $params), 'buttonBottom' => CRM_Utils_Array::value('buttonBottom', $params), 'currentLocation' => $this->getCurrentLocation(), - ); + ]; /** * A page cannot have two variables with the same form name. Hence in the * pager display, we have a form submission at the top with the normal * page variable, but a different form element for one at the bottom. */ - $this->_response['titleTop'] = ts('Page %1 of %2', array( - 1 => '', - 2 => $this->_response['numPages'], - )); - $this->_response['titleBottom'] = ts('Page %1 of %2', array( - 1 => '', - 2 => $this->_response['numPages'], - )); + $this->_response['titleTop'] = ts('Page %1 of %2', [ + 1 => '', + 2 => $this->_response['numPages'], + ]); + $this->_response['titleBottom'] = ts('Page %1 of %2', [ + 1 => '', + 2 => $this->_response['numPages'], + ]); } /** @@ -148,8 +148,8 @@ public function initialize(&$params) { $params['separator'] = ''; $params['spacesBeforeSeparator'] = 1; $params['spacesAfterSeparator'] = 1; - $params['extraVars'] = array('force' => 1); - $params['excludeVars'] = array('reset', 'snippet', 'section'); + $params['extraVars'] = ['force' => 1]; + $params['excludeVars'] = ['reset', 'snippet', 'section']; // set previous and next text labels $params['prevImg'] = ' ' . ts('< Previous'); @@ -248,7 +248,7 @@ public function getOffsetAndRowCount() { $offset = ($pageId - 1) * $this->_perPage; - return array($offset, $this->_perPage); + return [$offset, $this->_perPage]; } /** diff --git a/CRM/Utils/PagerAToZ.php b/CRM/Utils/PagerAToZ.php index 8e0fccf207e0..32da0ee8cc46 100644 --- a/CRM/Utils/PagerAToZ.php +++ b/CRM/Utils/PagerAToZ.php @@ -1,9 +1,9 @@ fetch()) { - $dynamicAlphabets[] = $result->sort_name; + $dynamicAlphabets[] = strtoupper($result->sort_name); } return $dynamicAlphabets; } @@ -151,16 +151,18 @@ public static function createLinks(&$query, $sortByCharacter, $isDAO) { $qfKey = CRM_Utils_Array::value('qfKey', $query->_formValues); } if (empty($qfKey)) { - $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this, FALSE, NULL, $_REQUEST); + // CRM-20943 Can only pass variables by reference and also cannot use $this so using $empty setting to NULL which is default. + $emptyVariable = NULL; + $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $emptyVariable, FALSE, NULL, $_REQUEST); } - $aToZBar = array(); + $aToZBar = []; foreach ($AToZBar as $key => $link) { if ($link === NULL) { continue; } - $element = array(); + $element = []; if (in_array($link, $dynamicAlphabets)) { $klass = ''; if ($link == $sortByCharacter) { @@ -191,7 +193,7 @@ public static function createLinks(&$query, $sortByCharacter, $isDAO) { ), ts('All') ); - $aToZBar[] = array('item' => $url); + $aToZBar[] = ['item' => $url]; return $aToZBar; } diff --git a/CRM/Utils/PseudoConstant.php b/CRM/Utils/PseudoConstant.php index 6ffc725adfcc..7a3cf0d54768 100644 --- a/CRM/Utils/PseudoConstant.php +++ b/CRM/Utils/PseudoConstant.php @@ -1,9 +1,9 @@ hasDeclaredIndex($tableName, $columns) ) { $formattedQuery = $this->format($queryText, CRM_Utils_QueryFormatter::LANG_SQL_FTSBOOL); - $prefixedFieldNames = array(); + $prefixedFieldNames = []; foreach ($columns as $fieldName) { $prefixedFieldNames[] = "$tableAlias.$fieldName"; } @@ -287,8 +292,8 @@ protected function _formatFts($text, $mode) { */ protected function _formatFtsBool($text, $mode) { $result = NULL; - $operators = array('+', '-', '~', '(', ')'); - $wildCards = array('@', '%', '*'); + $operators = ['+', '-', '~', '(', ')']; + $wildCards = ['@', '%', '*']; $expression = preg_quote(implode('', array_merge($operators, $wildCards)), '/'); //Return if searched string ends with an unsupported operator. @@ -399,7 +404,7 @@ protected function _formatLike($text, $mode) { * @return string */ protected function mapWords($text, $template, $quotes = FALSE) { - $result = array(); + $result = []; foreach ($this->parseWords($text, $quotes) as $word) { $result[] = str_replace('word', $word, $template); } @@ -407,8 +412,8 @@ protected function mapWords($text, $template, $quotes = FALSE) { } /** - * @param $text - * @bool $quotes + * @param string $text + * @param bool $quotes * @return array */ protected function parseWords($text, $quotes) { @@ -458,13 +463,13 @@ protected function dedupeWildcards($text, $wildcard) { * @return array */ public static function getModes() { - return array( + return [ self::MODE_NONE, self::MODE_PHRASE, self::MODE_WILDPHRASE, self::MODE_WILDWORDS, self::MODE_WILDWORDS_SUFFIX, - ); + ]; } /** @@ -473,12 +478,12 @@ public static function getModes() { * @return array */ public static function getLanguages() { - return array( + return [ self::LANG_SOLR, self::LANG_SQL_FTS, self::LANG_SQL_FTSBOOL, self::LANG_SQL_LIKE, - ); + ]; } /** diff --git a/CRM/Utils/REST.php b/CRM/Utils/REST.php index bd88f4202714..b1df33aee17c 100644 --- a/CRM/Utils/REST.php +++ b/CRM/Utils/REST.php @@ -1,9 +1,9 @@ get('key'); // $session->set( 'key', $var ); - return self::simple(array('message' => "PONG: $key")); + return self::simple(['message' => "PONG: $key"]); } /** @@ -78,10 +80,10 @@ public static function ping($var = NULL) { * @return array */ public static function error($message = 'Unknown Error') { - $values = array( + $values = [ 'error_message' => $message, 'is_error' => 1, - ); + ]; return $values; } @@ -92,7 +94,7 @@ public static function error($message = 'Unknown Error') { * @return array */ public static function simple($params) { - $values = array('is_error' => 0); + $values = ['is_error' => 0]; $values += $params; return $values; } @@ -129,7 +131,7 @@ public static function output(&$result) { if (!$result) { $result = 0; } - $result = self::simple(array('result' => $result)); + $result = self::simple(['result' => $result]); } elseif (is_array($result)) { if (CRM_Utils_Array::isHierarchical($result)) { @@ -146,6 +148,7 @@ public static function output(&$result) { if (!empty($requestParams['json'])) { if (!empty($requestParams['prettyprint'])) { // Don't set content-type header for api explorer output + return json_encode(array_merge($result), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE); return self::jsonFormated(array_merge($result)); } CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); @@ -181,100 +184,6 @@ public static function output(&$result) { return $xml; } - /** - * @param $data - * - * @deprecated - switch to native JSON_PRETTY_PRINT when we drop support for php 5.3 - * - * @return string - */ - public static function jsonFormated($data) { - // If php is 5.4+ we can use the native method - if (defined('JSON_PRETTY_PRINT')) { - return json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE); - } - - // PHP 5.3 shim - $json = str_replace('\/', '/', json_encode($data)); - $tabcount = 0; - $result = ''; - $inquote = FALSE; - $inarray = FALSE; - $ignorenext = FALSE; - - $tab = "\t"; - $newline = "\n"; - - for ($i = 0; $i < strlen($json); $i++) { - $char = $json[$i]; - - if ($ignorenext) { - $result .= $char; - $ignorenext = FALSE; - } - else { - switch ($char) { - case '{': - if ($inquote) { - $result .= $char; - } - else { - $inarray = FALSE; - $tabcount++; - $result .= $char . $newline . str_repeat($tab, $tabcount); - } - break; - - case '}': - if ($inquote) { - $result .= $char; - } - else { - $tabcount--; - $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char; - } - break; - - case ',': - if ($inquote || $inarray) { - $result .= $char; - } - else { - $result .= $char . $newline . str_repeat($tab, $tabcount); - } - break; - - case '"': - $inquote = !$inquote; - $result .= $char; - break; - - case '\\': - if ($inquote) { - $ignorenext = TRUE; - } - $result .= $char; - break; - - case '[': - $inarray = TRUE; - $result .= $char; - break; - - case ']': - $inarray = FALSE; - $result .= $char; - break; - - default: - $result .= $char; - } - } - } - - return $result; - } - /** * @return array|int */ @@ -309,7 +218,7 @@ public static function handle() { } else { // or the api format (entity+action) - $args = array(); + $args = []; $args[0] = 'civicrm'; $args[1] = CRM_Utils_Array::value('entity', $requestParams); $args[2] = CRM_Utils_Array::value('action', $requestParams); @@ -370,7 +279,7 @@ public static function process(&$args, $params) { return self::error('Unknown function invocation.'); } - return call_user_func(array($params['className'], $params['fnName']), $params); + return call_user_func([$params['className'], $params['fnName']], $params); } if (!array_key_exists('version', $params)) { @@ -385,22 +294,25 @@ public static function process(&$args, $params) { } if ($_SERVER['REQUEST_METHOD'] == 'GET' && - strtolower(substr($args[2], 0, 3)) != 'get' && - strtolower($args[2] != 'check')) { + strtolower(substr($args[2], 0, 3)) != 'get' && + strtolower($args[2] != 'check')) { // get only valid for non destructive methods require_once 'api/v3/utils.php'; return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.", - array( + [ 'IP' => $_SERVER['REMOTE_ADDR'], 'level' => 'security', 'referer' => $_SERVER['HTTP_REFERER'], 'reason' => 'Destructive HTTP GET', - ) + ] ); } // trap all fatal errors - $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); + $errorScope = CRM_Core_TemporaryErrorScope::create([ + 'CRM_Utils_REST', + 'fatal', + ]); $result = civicrm_api($args[1], $args[2], $params); unset($errorScope); @@ -415,21 +327,25 @@ public static function process(&$args, $params) { */ public static function &buildParamList() { $requestParams = CRM_Utils_Request::exportValues(); - $params = array(); + $params = []; - $skipVars = array( + $skipVars = [ 'q' => 1, 'json' => 1, 'key' => 1, 'api_key' => 1, 'entity' => 1, 'action' => 1, - ); + ]; if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") { $params = json_decode($requestParams['json'], TRUE); if ($params === NULL) { - CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.')); + CRM_Utils_JSON::output([ + 'is_error' => 1, + 0 => 'error_message', + 1 => 'Unable to decode supplied JSON.', + ]); } } foreach ($requestParams as $n => $v) { @@ -450,7 +366,7 @@ public static function &buildParamList() { */ public static function fatal($pearError) { CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml'); - $error = array(); + $error = []; $error['code'] = $pearError->getCode(); $error['error_message'] = $pearError->getMessage(); $error['mode'] = $pearError->getMode(); @@ -471,7 +387,7 @@ public static function fatal($pearError) { public static function loadTemplate() { $request = CRM_Utils_Request::retrieve('q', 'String'); if (FALSE !== strpos($request, '..')) { - die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org"); + die("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org"); } $request = explode('/', $request); @@ -483,15 +399,17 @@ public static function loadTemplate() { CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl"); if (!$smarty->template_exists($tpl)) { CRM_Utils_System::setHttpHeader("Status", "404 Not Found"); - die ("Can't find the requested template file templates/$tpl"); + die("Can't find the requested template file templates/$tpl"); } - if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used - $smarty->assign('id', (int) $_GET['id']);// an id is always positive + // special treatmenent, because it's often used + if (array_key_exists('id', $_GET)) { + // an id is always positive + $smarty->assign('id', (int) $_GET['id']); } $pos = strpos(implode(array_keys($_GET)), '<'); if ($pos !== FALSE) { - die ("SECURITY FATAL: one of the param names contains <"); + die("SECURITY FATAL: one of the param names contains <"); } $param = array_map('htmlentities', $_GET); unset($param['q']); @@ -537,12 +455,12 @@ public static function ajaxJson() { ) ) { $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", - array( + [ 'IP' => $_SERVER['REMOTE_ADDR'], 'level' => 'security', 'referer' => $_SERVER['HTTP_REFERER'], 'reason' => 'CSRF suspected', - ) + ] ); CRM_Utils_JSON::output($error); } @@ -558,21 +476,25 @@ public static function ajaxJson() { $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams)); $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams)); if (!is_array($params)) { - CRM_Utils_JSON::output(array( - 'is_error' => 1, - 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}', - )); + CRM_Utils_JSON::output([ + 'is_error' => 1, + 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}', + ]); } $params['check_permissions'] = TRUE; $params['version'] = 3; - $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions + // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions + $_GET['json'] = $requestParams['json'] = 1; if (!$params['sequential']) { $params['sequential'] = 1; } // trap all fatal errors - $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); + $errorScope = CRM_Core_TemporaryErrorScope::create([ + 'CRM_Utils_REST', + 'fatal', + ]); $result = civicrm_api($entity, $action, $params); unset($errorScope); @@ -600,12 +522,12 @@ public static function ajax() { ) { require_once 'api/v3/utils.php'; $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", - array( + [ 'IP' => $_SERVER['REMOTE_ADDR'], 'level' => 'security', 'referer' => $_SERVER['HTTP_REFERER'], 'reason' => 'CSRF suspected', - ) + ] ); CRM_Utils_JSON::output($error); } @@ -615,11 +537,14 @@ public static function ajax() { $entity = CRM_Utils_Array::value('entity', $requestParams); $action = CRM_Utils_Array::value('action', $requestParams); if (!$entity || !$action) { - $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1); + $err = [ + 'error_message' => 'missing mandatory params "entity=" or "action="', + 'is_error' => 1, + ]; echo self::output($err); CRM_Utils_System::civiExit(); } - $args = array('civicrm', $entity, $action); + $args = ['civicrm', $entity, $action]; } else { $args = explode('/', $q); @@ -651,14 +576,14 @@ public static function ajax() { * @return array */ public static function processMultiple() { - $output = array(); + $output = []; foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) { - $args = array( + $args = [ 'civicrm', $call[0], $call[1], - ); - $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, array())); + ]; + $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, [])); } return $output; } @@ -676,8 +601,9 @@ public function loadCMSBootstrap() { // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping" if (!empty($q)) { if (count($args) == 2 && $args[1] == 'ping') { - CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE); - return NULL; // this is pretty wonky but maybe there's some reason I can't see + CRM_Utils_System::loadBootStrap([], FALSE, FALSE); + // this is pretty wonky but maybe there's some reason I can't see + return NULL; } if (count($args) != 3) { return self::error('ERROR: Malformed REST path'); @@ -692,7 +618,7 @@ public function loadCMSBootstrap() { // FIXME: At time of writing, this doesn't actually do anything because // authenticateKey abends, but that's a bad behavior which sends a // malformed response. - CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE); + CRM_Utils_System::loadBootStrap([], FALSE, FALSE); return self::error('Failed to authenticate key'); } @@ -701,7 +627,7 @@ public function loadCMSBootstrap() { $store = NULL; $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST'); if (empty($api_key)) { - CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE); + CRM_Utils_System::loadBootStrap([], FALSE, FALSE); return self::error("FATAL: mandatory param 'api_key' (user key) missing"); } $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key'); @@ -711,17 +637,17 @@ public function loadCMSBootstrap() { } if ($uid && $contact_id) { - CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE); + CRM_Utils_System::loadBootStrap(['uid' => $uid], TRUE, FALSE); $session = CRM_Core_Session::singleton(); $session->set('ufID', $uid); $session->set('userID', $contact_id); CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1', - array(1 => array($contact_id, 'Integer')) + [1 => [$contact_id, 'Integer']] ); return NULL; } else { - CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE); + CRM_Utils_System::loadBootStrap([], FALSE, FALSE); return self::error('ERROR: No CMS user associated with given api-key'); } } diff --git a/CRM/Utils/ReCAPTCHA.php b/CRM/Utils/ReCAPTCHA.php index aa27d26dd6ba..fab82510ce85 100644 --- a/CRM/Utils/ReCAPTCHA.php +++ b/CRM/Utils/ReCAPTCHA.php @@ -1,9 +1,9 @@ recaptchaPublicKey == NULL || $config->recaptchaPublicKey == "") { + return FALSE; + } + return TRUE; + } + + /** + * Check if reCaptcha has to be added on form forcefully. + */ + public static function hasToAddForcefully() { + $config = CRM_Core_Config::singleton(); + if (!$config->forceRecaptcha) { + return FALSE; + } + return TRUE; + } + /** * Add element to form. * @@ -75,11 +97,10 @@ public static function add(&$form) { require_once 'packages/recaptcha/recaptchalib.php'; } - // See if we are using SSL - if (CRM_Utils_System::isSSL()) { - $useSSL = TRUE; - } - $html = recaptcha_get_html($config->recaptchaPublicKey, $error, $useSSL); + // Load the Recaptcha api.js over HTTPS + $useHTTPS = TRUE; + + $html = recaptcha_get_html($config->recaptchaPublicKey, $error, $useHTTPS); $form->assign('recaptchaHTML', $html); $form->assign('recaptchaOptions', $config->recaptchaOptions); @@ -99,4 +120,17 @@ public static function add(&$form) { } } + /** + * Enable ReCAPTCHA on Contribution form + * + * @param CRM_Core_Form $form + */ + public static function enableCaptchaOnForm(&$form) { + $captcha = CRM_Utils_ReCAPTCHA::singleton(); + if ($captcha->hasSettingsAvailable()) { + $captcha->add($form); + $form->assign('isCaptcha', TRUE); + } + } + } diff --git a/CRM/Utils/Recent.php b/CRM/Utils/Recent.php index 7f8e5362727d..55ccf47b4b5c 100644 --- a/CRM/Utils/Recent.php +++ b/CRM/Utils/Recent.php @@ -1,9 +1,9 @@ get(self::STORE_NAME); if (!self::$_recent) { - self::$_recent = array(); + self::$_recent = []; } } } @@ -104,7 +104,7 @@ public static function add( $type, $contactId, $contactName, - $others = array() + $others = [] ) { self::initialize(); @@ -116,7 +116,7 @@ public static function add( // make sure item is not already present in list for ($i = 0; $i < count(self::$_recent); $i++) { - if (self::$_recent[$i]['url'] == $url) { + if (self::$_recent[$i]['type'] === $type && self::$_recent[$i]['id'] == $id) { // delete item from array array_splice(self::$_recent, $i, 1); break; @@ -124,11 +124,11 @@ public static function add( } if (!is_array($others)) { - $others = array(); + $others = []; } array_unshift(self::$_recent, - array( + [ 'title' => $title, 'url' => $url, 'id' => $id, @@ -140,7 +140,7 @@ public static function add( 'image_url' => CRM_Utils_Array::value('imageUrl', $others), 'edit_url' => CRM_Utils_Array::value('editUrl', $others), 'delete_url' => CRM_Utils_Array::value('deleteUrl', $others), - ) + ] ); if (count(self::$_recent) > self::$_maxItems) { @@ -162,7 +162,7 @@ public static function del($recentItem) { self::initialize(); $tempRecent = self::$_recent; - self::$_recent = ''; + self::$_recent = []; // make sure item is not already present in list for ($i = 0; $i < count($tempRecent); $i++) { @@ -174,6 +174,7 @@ public static function del($recentItem) { } } + CRM_Utils_Hook::recent(self::$_recent); $session = CRM_Core_Session::singleton(); $session->set(self::STORE_NAME, self::$_recent); } @@ -189,7 +190,7 @@ public static function delContact($id) { $tempRecent = self::$_recent; - self::$_recent = ''; + self::$_recent = []; // rebuild recent. for ($i = 0; $i < count($tempRecent); $i++) { @@ -200,15 +201,17 @@ public static function delContact($id) { self::$_recent[] = $tempRecent[$i]; } + CRM_Utils_Hook::recent(self::$_recent); $session = CRM_Core_Session::singleton(); $session->set(self::STORE_NAME, self::$_recent); } /** * Check if a provider is allowed to add stuff. - * If correspondig setting is empty, all are allowed + * If corresponding setting is empty, all are allowed * * @param string $providerName + * @return bool */ public static function isProviderEnabled($providerName) { @@ -230,9 +233,11 @@ public static function isProviderEnabled($providerName) { /** * Gets the list of available providers to civi's recent items stack + * + * @return array */ public static function getProviders() { - $providers = array( + $providers = [ 'Contact' => ts('Contacts'), 'Relationship' => ts('Relationships'), 'Activity' => ts('Activities'), @@ -246,7 +251,7 @@ public static function getProviders() { 'Pledge' => ts('Pledges'), 'Event' => ts('Events'), 'Campaign' => ts('Campaigns'), - ); + ]; return $providers; } diff --git a/CRM/Utils/Request.php b/CRM/Utils/Request.php index 2748e07d7df8..95427c78a719 100644 --- a/CRM/Utils/Request.php +++ b/CRM/Utils/Request.php @@ -1,9 +1,9 @@ $name))); + if ($isThrowException) { + throw new CRM_Core_Exception(ts("Could not find valid value for %1", [1 => $name])); + } + CRM_Core_Error::fatal(ts("Could not find valid value for %1", [1 => $name])); } if (!isset($value) && $default) { @@ -125,8 +126,10 @@ public static function retrieve($name, $type, &$store = NULL, $abort = FALSE, $d } // minor hack for action - if ($name == 'action' && is_string($value)) { - $value = CRM_Core_Action::resolve($value); + if ($name == 'action') { + if (!is_numeric($value) && is_string($value)) { + $value = CRM_Core_Action::resolve($value); + } } if (isset($value) && $store) { @@ -143,9 +146,9 @@ public static function retrieve($name, $type, &$store = NULL, $abort = FALSE, $d * @param array $method - '$_GET', '$_POST' or '$_REQUEST'. * * @return mixed - * The value of the variable + * The value of the variable */ - public static function getValue($name, $method) { + protected static function getValue($name, $method) { if (isset($method[$name])) { return $method[$name]; } @@ -165,6 +168,10 @@ public static function getValue($name, $method) { } /** + * @deprecated + * + * We should use a function that checks url values. + * * This is a replacement for $_REQUEST which includes $_GET/$_POST * but excludes $_COOKIE / $_ENV / $_SERVER. * @@ -176,7 +183,7 @@ public static function exportValues() { // http://www.php.net/manual/en/ini.core.php#ini.request-order // http://www.php.net/manual/en/ini.core.php#ini.variables-order - $result = array(); + $result = []; if ($_GET) { $result = array_merge($result, $_GET); } @@ -186,4 +193,64 @@ public static function exportValues() { return $result; } + /** + * Retrieve a variable from the http request. + * + * @param string $name + * Name of the variable to be retrieved. + * @param string $type + * Type of the variable (see CRM_Utils_Type for details). + * Most common options are: + * - 'Integer' + * - 'Positive' + * - 'CommaSeparatedIntegers' + * - 'Boolean' + * - 'String' + * + * @param mixed $defaultValue + * Default value of the variable if not present. + * @param bool $isRequired + * Is the variable required for this function to proceed without an exception. + * @param string $method + * Where to look for the value - GET|POST|REQUEST + * + * @return mixed + * @throws \CRM_Core_Exception + */ + public static function retrieveValue($name, $type, $defaultValue = NULL, $isRequired = FALSE, $method = 'REQUEST') { + $null = NULL; + return CRM_Utils_Request::retrieve((string) $name, (string) $type, $null, (bool) $isRequired, $defaultValue, $method, TRUE); + } + + /** + * Retrieve the component from the action attribute of a form. + * + * Contribution Page forms and Event Management forms detect the value of a + * component (and therefore the desired tab key) by reaching into the "action" + * attribute of a form and reading the final item of the path. In WordPress, + * however, the URL may be urlencoded, and so the URL may need to be decoded + * before parsing it. + * + * @see https://lab.civicrm.org/dev/wordpress/issues/12#note_10699 + * + * @param array $attributes + * The form attributes array. + * + * @return string + * The desired value. + */ + public static function retrieveComponent($attributes) { + $url = CRM_Utils_Array::value('action', $attributes); + // Whilst the following is a fallible universal test for urlencoded URLs, + // thankfully the "action" URL has a limited and predictable form and + // therefore this comparison is sufficient for our purposes. + if (rawurlencode(rawurldecode($url)) !== $url) { + $value = strtolower(basename(rawurldecode($url))); + } + else { + $value = strtolower(basename($url)); + } + return $value; + } + } diff --git a/CRM/Utils/Rule.php b/CRM/Utils/Rule.php index a40286d4b5c1..940128d7156c 100644 --- a/CRM/Utils/Rule.php +++ b/CRM/Utils/Rule.php @@ -1,9 +1,9 @@ + * * @param $value + * @return bool + */ + public static function color($value) { + return (bool) preg_match('/^#([\da-fA-F]{6})$/', $value); + } + + /** + * Strip thousand separator from a money string. + * + * Note that this should be done at the form layer. Once we are processing + * money at the BAO or processor layer we should be working with something that + * is already in a normalised format. + * + * @param string $value * - * @return mixed + * @return string */ public static function cleanMoney($value) { // first remove all white space - $value = str_replace(array(' ', "\t", "\n"), '', $value); + $value = str_replace([' ', "\t", "\n"], '', $value); $config = CRM_Core_Config::singleton(); //CRM-14868 $currencySymbols = CRM_Core_PseudoConstant::get( 'CRM_Contribute_DAO_Contribution', - 'currency', array( + 'currency', [ 'keyColumn' => 'name', 'labelColumn' => 'symbol', - ) + ] ); $value = str_replace($currencySymbols, '', $value); @@ -574,7 +631,10 @@ public static function money($value) { return TRUE; } - return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ? TRUE : FALSE; + // Allow values such as -0, 1.024555, -.1 + // We need to support multiple decimal places here, not just the number allowed by locale + // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here). + return preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value) ? TRUE : FALSE; } /** @@ -790,6 +850,25 @@ public static function xssString($value) { } } + /** + * Validate json string for xss + * + * @param string $value + * + * @return bool + * False if invalid, true if valid / safe. + */ + public static function json($value) { + if (!self::xssString($value)) { + return FALSE; + } + $array = json_decode($value, TRUE); + if (!$array || !is_array($array)) { + return FALSE; + } + return self::arrayValue($array); + } + /** * @param $path * @@ -904,8 +983,39 @@ public static function validDateRange($fields, $fieldName, &$errors, $title) { $highDate = strtotime($fields[$fieldName . '_high']); if ($lowDate > $highDate) { - $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title)); + $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $title]); + } + } + + /** + * @param string $key Extension Key to check + * @return bool + */ + public static function checkExtensionKeyIsValid($key = NULL) { + if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) { + return FALSE; + } + return TRUE; + } + + /** + * Validate array recursively checking keys and values. + * + * @param array $array + * @return bool + */ + protected static function arrayValue($array) { + foreach ($array as $key => $item) { + if (is_array($item)) { + if (!self::xssString($key) || !self::arrayValue($item)) { + return FALSE; + } + } + if (!self::xssString($key) || !self::xssString($item)) { + return FALSE; + } } + return TRUE; } } diff --git a/CRM/Utils/SQL.php b/CRM/Utils/SQL.php index 574b3a6cfeca..d7aab2132bc5 100644 --- a/CRM/Utils/SQL.php +++ b/CRM/Utils/SQL.php @@ -1,9 +1,9 @@ addSelectWhereClause() as $field => $vals) { if ($vals && $field == $joinColumn) { $clauses = array_merge($clauses, (array) $vals); @@ -59,4 +59,102 @@ public static function mergeSubquery($entity, $joinColumn = 'id') { return $clauses; } + /** + * Get current sqlModes of the session + * @return array + */ + public static function getSqlModes() { + $sqlModes = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode')); + return $sqlModes; + } + + /** + * Checks if this system enforce the MYSQL mode ONLY_FULL_GROUP_BY. + * This function should be named supportsAnyValueAndEnforcesFullGroupBY(), + * but should be deprecated instead. + * + * @return mixed + * @deprecated + */ + public static function supportsFullGroupBy() { + // CRM-21455 MariaDB 10.2 does not support ANY_VALUE + $version = self::getDatabaseVersion(); + + if (stripos($version, 'mariadb') !== FALSE) { + return FALSE; + } + + return version_compare($version, '5.7', '>='); + } + + /** + * Disable ONLY_FULL_GROUP_BY for MySQL versions lower then 5.7 + * + * @return bool + */ + public static function disableFullGroupByMode() { + $sqlModes = self::getSqlModes(); + + // Disable only_full_group_by mode for lower sql versions. + if (!self::supportsFullGroupBy() || (!empty($sqlModes) && !in_array('ONLY_FULL_GROUP_BY', $sqlModes))) { + if ($key = array_search('ONLY_FULL_GROUP_BY', $sqlModes)) { + unset($sqlModes[$key]); + CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlModes) . "'"); + } + return TRUE; + } + + return FALSE; + } + + /** + * CHeck if ONLY_FULL_GROUP_BY is in the global sql_modes + * @return bool + */ + public static function isGroupByModeInDefault() { + $sqlModes = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@global.sql_mode')); + if (!in_array('ONLY_FULL_GROUP_BY', $sqlModes)) { + return FALSE; + } + return TRUE; + } + + /** + * Does the DB version support mutliple locks per + * + * https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock + * + * As an interim measure we ALSO require CIVICRM_SUPPORT_MULTIPLE_LOCKS to be defined. + * + * This is a conservative measure to introduce the change which we expect to deprecate later. + * + * @todo we only check mariadb & mysql right now but maybe can add percona. + */ + public static function supportsMultipleLocks() { + if (!defined('CIVICRM_SUPPORT_MULTIPLE_LOCKS')) { + return FALSE; + } + static $isSupportLocks = NULL; + if (!isset($isSupportLocks)) { + $version = self::getDatabaseVersion(); + if (stripos($version, 'mariadb') !== FALSE) { + $isSupportLocks = version_compare($version, '10.0.2', '>='); + } + else { + $isSupportLocks = version_compare($version, '5.7.5', '>='); + } + } + + return $isSupportLocks; + } + + /** + * Get the version string for the database. + * + * @return string + */ + public static function getDatabaseVersion() { + return CRM_Core_DAO::singleValueQuery('SELECT VERSION()'); + } + } diff --git a/CRM/Utils/SQL/BaseParamQuery.php b/CRM/Utils/SQL/BaseParamQuery.php new file mode 100644 index 000000000000..159f56a5fad6 --- /dev/null +++ b/CRM/Utils/SQL/BaseParamQuery.php @@ -0,0 +1,241 @@ +strict = $strict; + return $this; + } + + /** + * Given a string like "field_name = @value", replace "@value" with an escaped SQL string + * + * @param string $expr SQL expression + * @param null|array $args a list of values to insert into the SQL expression; keys are prefix-coded: + * prefix '@' => escape SQL + * prefix '#' => literal number, skip escaping but do validation + * prefix '!' => literal, skip escaping and validation + * if a value is an array, then it will be imploded + * + * PHP NULL's will be treated as SQL NULL's. The PHP string "null" will be treated as a string. + * + * @param string $activeMode + * + * @return string + */ + public function interpolate($expr, $args, $activeMode = self::INTERPOLATE_INPUT) { + if ($args === NULL) { + return $expr; + } + else { + if ($this->mode === self::INTERPOLATE_AUTO) { + $this->mode = $activeMode; + } + elseif ($activeMode !== $this->mode) { + throw new RuntimeException("Cannot mix interpolation modes."); + } + + $select = $this; + return preg_replace_callback('/([#!@])([a-zA-Z0-9_]+)/', function($m) use ($select, $args) { + if (array_key_exists($m[2], $args)) { + $values = $args[$m[2]]; + } + elseif (array_key_exists($m[1] . $m[2], $args)) { + // Backward compat. Keys in $args look like "#myNumber" or "@myString". + $values = $args[$m[1] . $m[2]]; + } + elseif ($select->strict) { + throw new CRM_Core_Exception('Cannot build query. Variable "' . $m[1] . $m[2] . '" is unknown.'); + } + else { + // Unrecognized variables are ignored. Mitigate risk of accidents. + return $m[0]; + } + $values = is_array($values) ? $values : [$values]; + switch ($m[1]) { + case '@': + $parts = array_map([$select, 'escapeString'], $values); + return implode(', ', $parts); + + // TODO: ensure all uses of this un-escaped literal are safe + case '!': + return implode(', ', $values); + + case '#': + foreach ($values as $valueKey => $value) { + if ($value === NULL) { + $values[$valueKey] = 'NULL'; + } + elseif (!is_numeric($value)) { + //throw new API_Exception("Failed encoding non-numeric value" . var_export(array($m[0] => $values), TRUE)); + throw new CRM_Core_Exception("Failed encoding non-numeric value (" . $m[0] . ")"); + } + } + return implode(', ', $values); + + default: + throw new CRM_Core_Exception("Unrecognized prefix"); + } + }, $expr); + } + } + + /** + * @param string|NULL $value + * @return string + * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes) + */ + public function escapeString($value) { + return $value === NULL ? 'NULL' : '"' . CRM_Core_DAO::escapeString($value) . '"'; + } + + /** + * Set one (or multiple) parameters to interpolate into the query. + * + * @param array|string $keys + * Key name, or an array of key-value pairs. + * @param null|mixed $value + * The new value of the parameter. + * Values may be strings, ints, or arrays thereof -- provided that the + * SQL query uses appropriate prefix (e.g. "@", "!", "#"). + * @return $this + */ + public function param($keys, $value = NULL) { + if ($this->mode === self::INTERPOLATE_AUTO) { + $this->mode = self::INTERPOLATE_OUTPUT; + } + elseif ($this->mode !== self::INTERPOLATE_OUTPUT) { + throw new RuntimeException("Select::param() only makes sense when interpolating on output."); + } + + if (is_array($keys)) { + foreach ($keys as $k => $v) { + $this->params[$k] = $v; + } + } + else { + $this->params[$keys] = $value; + } + return $this; + } + + /** + * Has an offset been set. + * + * @param string $offset + * + * @return bool + */ + public function offsetExists($offset) { + return isset($this->params[$offset]); + } + + /** + * Get the value of a SQL parameter. + * + * @code + * $select['cid'] = 123; + * $select->where('contact.id = #cid'); + * echo $select['cid']; + * @endCode + * + * @param string $offset + * @return mixed + * @see param() + * @see ArrayAccess::offsetGet + */ + public function offsetGet($offset) { + return $this->params[$offset]; + } + + /** + * Set the value of a SQL parameter. + * + * @code + * $select['cid'] = 123; + * $select->where('contact.id = #cid'); + * echo $select['cid']; + * @endCode + * + * @param string $offset + * @param mixed $value + * The new value of the parameter. + * Values may be strings, ints, or arrays thereof -- provided that the + * SQL query uses appropriate prefix (e.g. "@", "!", "#"). + * @see param() + * @see ArrayAccess::offsetSet + */ + public function offsetSet($offset, $value) { + $this->param($offset, $value); + } + + /** + * Unset the value of a SQL parameter. + * + * @param string $offset + * @see param() + * @see ArrayAccess::offsetUnset + */ + public function offsetUnset($offset) { + unset($this->params[$offset]); + } + +} diff --git a/CRM/Utils/SQL/Delete.php b/CRM/Utils/SQL/Delete.php new file mode 100644 index 000000000000..24d0f885fbb4 --- /dev/null +++ b/CRM/Utils/SQL/Delete.php @@ -0,0 +1,269 @@ +where('activity_type_id = #type', array('type' => 234)) + * ->where('status_id IN (#statuses)', array('statuses' => array(1,2,3)) + * ->where('subject like @subj', array('subj' => '%hello%')) + * ->where('!dynamicColumn = 1', array('dynamicColumn' => 'coalesce(is_active,0)')) + * ->where('!column = @value', array( + * 'column' => $customField->column_name, + * 'value' => $form['foo'] + * )) + * echo $del->toSQL(); + * @endcode + * + * Design principles: + * - Portable + * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString) + * - No knowledge of the underlying data model + * - SQL clauses correspond to PHP functions ($select->where("foo_id=123")) + * - Variable escaping is concise and controllable based on prefixes, eg + * - similar to Drupal's t() + * - use "@varname" to insert the escaped value + * - use "!varname" to insert raw (unescaped) values + * - use "#varname" to insert a numerical value (these are validated but not escaped) + * - to disable any preprocessing, simply omit the variable list + * - control characters (@!#) are mandatory in expressions but optional in arg-keys + * - Variables may be individual values or arrays; arrays are imploded with commas + * - Conditionals are AND'd; if you need OR's, do it yourself + * - Use classes/functions with documentation (rather than undocumented array-trees) + * - For any given string, interpolation is only performed once. After an interpolation, + * a string may never again be subjected to interpolation. + * + * The "interpolate-once" principle can be enforced by either interpolating on input + * xor output. The notations for input and output interpolation are a bit different, + * and they may not be mixed. + * + * @code + * // Interpolate on input. Set params when using them. + * $select->where('activity_type_id = #type', array( + * 'type' => 234, + * )); + * + * // Interpolate on output. Set params independently. + * $select + * ->where('activity_type_id = #type') + * ->param('type', 234), + * @endcode + * + * @package CRM + * @copyright CiviCRM LLC (c) 2004-2019 + */ +class CRM_Utils_SQL_Delete extends CRM_Utils_SQL_BaseParamQuery { + + private $from; + private $wheres = []; + + /** + * Create a new DELETE query. + * + * @param string $from + * Table-name and optional alias. + * @param array $options + * @return CRM_Utils_SQL_Delete + */ + public static function from($from, $options = []) { + return new self($from, $options); + } + + /** + * Create a new DELETE query. + * + * @param string $from + * Table-name and optional alias. + * @param array $options + */ + public function __construct($from, $options = []) { + $this->from = $from; + $this->mode = isset($options['mode']) ? $options['mode'] : self::INTERPOLATE_AUTO; + } + + /** + * Make a new copy of this query. + * + * @return CRM_Utils_SQL_Delete + */ + public function copy() { + return clone $this; + } + + /** + * Merge something or other. + * + * @param CRM_Utils_SQL_Delete $other + * @param array|NULL $parts + * ex: 'wheres' + * @return CRM_Utils_SQL_Delete + */ + public function merge($other, $parts = NULL) { + if ($other === NULL) { + return $this; + } + + if ($this->mode === self::INTERPOLATE_AUTO) { + $this->mode = $other->mode; + } + elseif ($other->mode === self::INTERPOLATE_AUTO) { + // Noop. + } + elseif ($this->mode !== $other->mode) { + // Mixing modes will lead to someone getting an expected substitution. + throw new RuntimeException("Cannot merge queries that use different interpolation modes ({$this->mode} vs {$other->mode})."); + } + + $arrayFields = ['wheres', 'params']; + foreach ($arrayFields as $f) { + if ($parts === NULL || in_array($f, $parts)) { + $this->{$f} = array_merge($this->{$f}, $other->{$f}); + } + } + + $flatFields = ['from']; + foreach ($flatFields as $f) { + if ($parts === NULL || in_array($f, $parts)) { + if ($other->{$f} !== NULL) { + $this->{$f} = $other->{$f}; + } + } + } + + return $this; + } + + /** + * Limit results by adding extra condition(s) to the WHERE clause + * + * @param string|array $exprs list of SQL expressions + * @param null|array $args use NULL to disable interpolation; use an array of variables to enable + * @return CRM_Utils_SQL_Delete + */ + public function where($exprs, $args = NULL) { + $exprs = (array) $exprs; + foreach ($exprs as $expr) { + $evaluatedExpr = $this->interpolate($expr, $args); + $this->wheres[$evaluatedExpr] = $evaluatedExpr; + } + return $this; + } + + /** + * Set one (or multiple) parameters to interpolate into the query. + * + * @param array|string $keys + * Key name, or an array of key-value pairs. + * @param null|mixed $value + * The new value of the parameter. + * Values may be strings, ints, or arrays thereof -- provided that the + * SQL query uses appropriate prefix (e.g. "@", "!", "#"). + * @return \CRM_Utils_SQL_Delete + */ + public function param($keys, $value = NULL) { + // Why bother with an override? To provide better type-hinting in `@return`. + return parent::param($keys, $value); + } + + /** + * @param array|NULL $parts + * List of fields to check (e.g. 'wheres'). + * Defaults to all. + * @return bool + */ + public function isEmpty($parts = NULL) { + $empty = TRUE; + $fields = [ + 'from', + 'wheres', + ]; + if ($parts !== NULL) { + $fields = array_intersect($fields, $parts); + } + foreach ($fields as $field) { + if (!empty($this->{$field})) { + $empty = FALSE; + } + } + return $empty; + } + + /** + * @return string + * SQL statement + */ + public function toSQL() { + $sql = 'DELETE '; + + if ($this->from !== NULL) { + $sql .= 'FROM ' . $this->from . "\n"; + } + if ($this->wheres) { + $sql .= 'WHERE (' . implode(') AND (', $this->wheres) . ")\n"; + } + if ($this->mode === self::INTERPOLATE_OUTPUT) { + $sql = $this->interpolate($sql, $this->params, self::INTERPOLATE_OUTPUT); + } + return $sql; + } + + /** + * Execute the query. + * + * To examine the results, use a function like `fetch()`, `fetchAll()`, + * `fetchValue()`, or `fetchMap()`. + * + * @param string|NULL $daoName + * The return object should be an instance of this class. + * Ex: 'CRM_Contact_BAO_Contact'. + * @param bool $i18nRewrite + * If the system has multilingual features, should the field/table + * names be rewritten? + * @return CRM_Core_DAO + * @see CRM_Core_DAO::executeQuery + * @see CRM_Core_I18n_Schema::rewriteQuery + */ + public function execute($daoName = NULL, $i18nRewrite = TRUE) { + // Don't pass through $params. toSQL() handles interpolation. + $params = []; + + // Don't pass through $abort, $trapException. Just use straight-up exceptions. + $abort = TRUE; + $trapException = FALSE; + $errorScope = CRM_Core_TemporaryErrorScope::useException(); + + // Don't pass through freeDAO. You can do it yourself. + $freeDAO = FALSE; + + return CRM_Core_DAO::executeQuery($this->toSQL(), $params, $abort, $daoName, + $freeDAO, $i18nRewrite, $trapException); + } + +} diff --git a/CRM/Utils/SQL/Insert.php b/CRM/Utils/SQL/Insert.php index fc8f13635830..816c89f605d0 100644 --- a/CRM/Utils/SQL/Insert.php +++ b/CRM/Utils/SQL/Insert.php @@ -36,6 +36,7 @@ class CRM_Utils_SQL_Insert { /** * Array, @@ -225,6 +228,10 @@ public function fill($format = NULL) { if ($entity == 'activity' && $field == 'details') { $htmlTokens[$entity][$field] = $value; } + elseif (\CRM_Utils_Array::value('data_type', \CRM_Utils_Array::value($field, $entityFields['values'])) == 'Memo') { + // Memo fields aka custom fields of type Note are html. + $htmlTokens[$entity][$field] = CRM_Utils_String::purifyHTML($value); + } else { $htmlTokens[$entity][$field] = htmlentities($value); } @@ -299,8 +306,7 @@ public function __construct($tokenProcessor, $tokenRow) { * @return bool */ public function offsetExists($offset) { - return - isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]) + return isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]) || isset($this->tokenProcessor->context[$offset]); } diff --git a/agpl-3.0.txt b/LICENSE similarity index 100% rename from agpl-3.0.txt rename to LICENSE diff --git a/README.md b/README.md index cf7462f47dba..ee36cd697c9d 100644 --- a/README.md +++ b/README.md @@ -19,13 +19,13 @@ Installation The download URLs and installation instructions are available on our website: https://civicrm.org/download -Detailed installation instructions are [on the wiki](https://wiki.civicrm.org/confluence/display/CRMDOC/Installation+and+Upgrades). +Detailed installation instructions can be found [in our sysadmin guide](https://docs.civicrm.org/sysadmin/en/latest/). Documentation ------------- -Documentation can be found at https://civicrm.org/documentation +Documentation can be found at https://docs.civicrm.org Support @@ -44,7 +44,7 @@ Development and Bugs Developers are highly encouraged to join [chat.civicrm.org](https://chat.civicrm.org) and post questions and ideas in the [Developer Discussion room](https://chat.civicrm.org/civicrm/channels/dev). -Installing the latest developmental code requires some [special steps](http://wiki.civicrm.org/confluence/display/CRMDOC/Contributing+to+CiviCRM+using+GitHub). +Installing the latest developmental code requires some [special steps](https://docs.civicrm.org/dev/en/latest/tools/git/). -Report all issues to CiviCRM via JIRA: -https://issues.civicrm.org +Report all issues to CiviCRM via GitLab: +https://lab.civicrm.org/ diff --git a/ang/angularFileUpload.ang.php b/ang/angularFileUpload.ang.php new file mode 100644 index 000000000000..68f4aa99aa1e --- /dev/null +++ b/ang/angularFileUpload.ang.php @@ -0,0 +1,9 @@ + 'civicrm', + 'js' => ['bower_components/angular-file-upload/angular-file-upload.min.js'], +]; diff --git a/ang/api4.ang.php b/ang/api4.ang.php new file mode 100644 index 000000000000..2c8a85b753be --- /dev/null +++ b/ang/api4.ang.php @@ -0,0 +1,13 @@ + 'civicrm', + 'js' => [ + 'ang/api4.js', + 'ang/api4/*.js', + 'ang/api4/*/*.js', + ], + 'css' => [], + 'partials' => [], + 'requires' => [], +]; diff --git a/ang/api4.js b/ang/api4.js new file mode 100644 index 000000000000..d1116fc45a06 --- /dev/null +++ b/ang/api4.js @@ -0,0 +1,4 @@ +(function(angular, $, _) { + // Declare a list of dependencies. + angular.module('api4', CRM.angRequires('api4')); +})(angular, CRM.$, CRM._); diff --git a/ang/api4/crmApi4.js b/ang/api4/crmApi4.js new file mode 100644 index 000000000000..743b35910bb3 --- /dev/null +++ b/ang/api4/crmApi4.js @@ -0,0 +1,37 @@ +(function(angular, $, _) { + + angular.module('api4').factory('crmApi4', function($q) { + var crmApi4 = function(entity, action, params, index) { + // JSON serialization in CRM.api4 is not aware of Angular metadata like $$hash, so use angular.toJson() + var deferred = $q.defer(); + var p; + var backend = crmApi4.backend || CRM.api4; + if (_.isObject(entity)) { + // eval content is locally generated. + /*jshint -W061 */ + p = backend(eval('('+angular.toJson(entity)+')'), action); + } else { + // eval content is locally generated. + /*jshint -W061 */ + p = backend(entity, action, eval('('+angular.toJson(params)+')'), index); + } + p.then( + function(result) { + deferred.resolve(result); + }, + function(error) { + deferred.reject(error); + } + ); + return deferred.promise; + }; + crmApi4.backend = null; + crmApi4.val = function(value) { + var d = $.Deferred(); + d.resolve(value); + return d.promise(); + }; + return crmApi4; + }); + +})(angular, CRM.$, CRM._); diff --git a/ang/api4Explorer.ang.php b/ang/api4Explorer.ang.php new file mode 100644 index 000000000000..9b974d53bf8d --- /dev/null +++ b/ang/api4Explorer.ang.php @@ -0,0 +1,17 @@ + 'civicrm', + 'js' => [ + 'ang/api4Explorer.js', + 'ang/api4Explorer/Explorer.js', + ], + 'css' => [ + 'css/api4-explorer.css', + ], + 'partials' => [ + 'ang/api4Explorer', + ], + 'basePages' => [], + 'requires' => ['crmUi', 'crmUtil', 'ngRoute', 'crmRouteBinder', 'ui.sortable', 'api4', 'ngSanitize'], +]; diff --git a/ang/api4Explorer.js b/ang/api4Explorer.js new file mode 100644 index 000000000000..85e10c467920 --- /dev/null +++ b/ang/api4Explorer.js @@ -0,0 +1,4 @@ +(function(angular, $, _) { + // Declare a list of dependencies. + angular.module('api4Explorer', CRM.angRequires('api4Explorer')); +})(angular, CRM.$, CRM._); diff --git a/ang/api4Explorer/Chain.html b/ang/api4Explorer/Chain.html new file mode 100644 index 000000000000..257efdeccffd --- /dev/null +++ b/ang/api4Explorer/Chain.html @@ -0,0 +1,4 @@ + + + + diff --git a/ang/api4Explorer/Explorer.html b/ang/api4Explorer/Explorer.html new file mode 100644 index 000000000000..bbfd35b95962 --- /dev/null +++ b/ang/api4Explorer/Explorer.html @@ -0,0 +1,152 @@ +
{{ text }}
++ {{ key }}: {{ item }} +
+{{ codeLabel[type] }} | ++ |
' + _.escape(row.description) + '