diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000000..ce303ed7de8d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# CiviCRM editor configuration normalization +# @see http://editorconfig.org/ + +# This is the top-most .editorconfig file; do not search in parent directories. +root = true + +# All files. +[*] +end_of_line = LF +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9a1e22a5d85f..0e1ed32e174f 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,70 +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 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..95f9b09cd824 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,7 +21,6 @@ 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 @@ -54,3 +42,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..d4cbb1448672 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 - Alok Patel, Francis Whittle, Justin Freeman +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 3d0c090dc9dd..80855ac01b65 100644 --- a/CRM/ACL/API.php +++ b/CRM/ACL/API.php @@ -1,9 +1,9 @@ get('userID'); + $contactID = CRM_Core_Session::getLoggedInContactID(); } if (!$contactID) { @@ -85,6 +84,10 @@ public static function check($str, $contactID = NULL) { * @param bool $skipDeleteClause * Don't add delete clause if this is true,. * this means it is handled by generating query + * @param bool $skipOwnContactClause + * Do not add 'OR contact_id = $userID' to the where clause. + * This is a hideously inefficient query and should be avoided + * wherever possible. * * @return string * the group where clause for this user @@ -95,7 +98,8 @@ public static function whereClause( &$whereTables, $contactID = NULL, $onlyDeleted = FALSE, - $skipDeleteClause = FALSE + $skipDeleteClause = FALSE, + $skipOwnContactClause = FALSE ) { // the default value which is valid for the final AND $deleteClause = ' ( 1 ) '; @@ -109,32 +113,28 @@ public static function whereClause( } } - // first see if the contact has edit / view all contacts - if (CRM_Core_Permission::check('edit all contacts') || - ($type == self::VIEW && CRM_Core_Permission::check('view all contacts')) - ) { - return $deleteClause; - } - if (!$contactID) { $contactID = CRM_Core_Session::getLoggedInContactID(); } $contactID = (int) $contactID; - $where = implode(' AND ', - array( - CRM_ACL_BAO_ACL::whereClause($type, - $tables, - $whereTables, - $contactID - ), - $deleteClause, - ) + // first see if the contact has edit / view all permission + if (CRM_Core_Permission::check('edit all contacts', $contactID) || + ($type == self::VIEW && CRM_Core_Permission::check('view all contacts', $contactID)) + ) { + return $deleteClause; + } + + $whereClause = CRM_ACL_BAO_ACL::whereClause($type, + $tables, + $whereTables, + $contactID ); + $where = implode(' AND ', [$whereClause, $deleteClause]); - // Add permission on self - if ($contactID && (CRM_Core_Permission::check('edit my contact') || - $type == self::VIEW && CRM_Core_Permission::check('view my contact')) + // Add permission on self if we really hate our server or have hardly any contacts. + if (!$skipOwnContactClause && $contactID && (CRM_Core_Permission::check('edit my contact') || + $type == self::VIEW && CRM_Core_Permission::check('view my contact')) ) { $where = "(contact_a.id = $contactID OR ($where))"; } @@ -164,8 +164,7 @@ public static function group( $includedGroups = NULL ) { if ($contactID == NULL) { - $session = CRM_Core_Session::singleton(); - $contactID = $session->get('userID'); + $contactID = CRM_Core_Session::getLoggedInContactID(); } if (!$contactID) { @@ -187,10 +186,8 @@ public static function group( * @param string $tableName * @param null $allGroups * @param null $includedGroups - * @param bool $flush * - * @return array - * the ids of the groups for which the user has permissions + * @return bool */ public static function groupPermission( $type, @@ -198,39 +195,23 @@ public static function groupPermission( $contactID = NULL, $tableName = 'civicrm_saved_search', $allGroups = NULL, - $includedGroups = NULL, - $flush = FALSE + $includedGroups = NULL ) { - static $cache = array(); - $groups = array(); - //@todo this is pretty hacky!!! - //adding a way for unit tests to flush the cache - if ($flush) { - $cache = array(); - return NULL; + if (!isset(Civi::$statics[__CLASS__]) || !isset(Civi::$statics[__CLASS__]['group_permission'])) { + Civi::$statics[__CLASS__]['group_permission'] = []; } + if (!$contactID) { - $session = CRM_Core_Session::singleton(); - $contactID = NULL; - if ($session->get('userID')) { - $contactID = $session->get('userID'); - } + $contactID = CRM_Core_Session::singleton()->getLoggedInContactID(); } $key = "{$tableName}_{$type}_{$contactID}"; - if (array_key_exists($key, $cache)) { - $groups = &$cache[$key]; - } - else { - $groups = self::group($type, $contactID, $tableName, $allGroups, $includedGroups); - $cache[$key] = $groups; - } - if (empty($groups)) { - return FALSE; + if (!array_key_exists($key, Civi::$statics[__CLASS__]['group_permission'])) { + Civi::$statics[__CLASS__]['group_permission'][$key] = self::group($type, $contactID, $tableName, $allGroups, $includedGroups); } - return in_array($groupID, $groups) ? TRUE : FALSE; + return in_array($groupID, Civi::$statics[__CLASS__]['group_permission'][$key]); } } diff --git a/CRM/ACL/BAO/ACL.php b/CRM/ACL/BAO/ACL.php index 205cb0b9ca1b..0051422252ec 100644 --- a/CRM/ACL/BAO/ACL.php +++ b/CRM/ACL/BAO/ACL.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,19 +117,19 @@ 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(), - ); + ]; - $session = CRM_Core_Session::singleton(); - $contact_id = $session->get('userID'); + $contact_id = CRM_Core_Session::getLoggedInContactID(); $where = " {$t['ACL']}.operation = '" . CRM_Utils_Type::escape($operation, 'String') . "'"; @@ -156,7 +158,7 @@ public static function permissionClause( } } - $query = array(); + $query = []; /* Query for permissions granted to all contacts in the domain */ @@ -259,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: @@ -336,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(); @@ -365,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(); @@ -395,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; @@ -503,7 +505,7 @@ public static function &getACLRoles($contact_id = NULL, $group_id = NULL) { } } - $results = array(); + $results = []; $rule->query($query); @@ -533,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 = " @@ -601,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); @@ -642,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); @@ -681,8 +683,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) { // note this also resets any ACL cache @@ -716,65 +718,25 @@ 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; } - /** - * Build a join and where part for a query - * - * @param int $contactId - * @return array - the first key is join part of the query and the second key is the where part of the query - */ - public static function buildAcl($contactId) { - // If there is no $contactId passed return empty ACL join and where clause - if (empty($contactId)) { - return array('', ''); - } - - $tables = array(); - $whereTables = array(); - $whereClause = CRM_ACL_BAO_ACL::whereClause(CRM_Core_Permission::VIEW, $tables, $whereTables, $contactId, TRUE); - if (strlen($whereClause)) { - $whereClause = " AND (" . $whereClause . ")"; - } - - $join = ""; - foreach ($whereTables as $name => $value) { - if (!$value) { - continue; - } - if ($value != 1) { - // if there is already a join statement in value, use value itself - if (strpos($value, 'JOIN')) { - $join .= " $value "; - } - continue; - } - } - - return array( - $join, - $whereClause, - ); - } - /** * @param $type * @param $tables * @param $whereTables * @param int $contactID - * @param bool $strictReturn If there is no where clause build for ACL * * @return null|string */ - public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL, $strictReturn = FALSE) { + public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL) { $acls = CRM_ACL_BAO_Cache::build($contactID); $whereClause = NULL; - $clauses = array(); + $clauses = []; if (!empty($acls)) { $aclKeys = array_keys($acls); @@ -793,12 +755,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; } @@ -815,60 +777,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 + ) + )"; } } } @@ -880,7 +809,7 @@ public static function whereClause($type, &$tables, &$whereTables, $contactID = // call the hook to get additional whereClauses CRM_Utils_Hook::aclWhereClause($type, $tables, $whereTables, $contactID, $whereClause); - if (empty($whereClause) && !$strictReturn) { + if (empty($whereClause)) { $whereClause = ' ( 0 ) '; } @@ -903,18 +832,30 @@ public static function group( $allGroups = NULL, $includedGroups = NULL ) { + $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'] = []; + } + 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_Core_BAO_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 @@ -925,7 +866,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) { @@ -953,9 +894,25 @@ public static function group( ) { $ids = $includedGroups; } + if ($contactID) { + $groupWhere = ''; + if (!empty($allGroups)) { + $groupWhere = " AND id IN (" . implode(',', array_keys($allGroups)) . ")"; + } + // Contacts create hidden groups from search results. They should be able to retrieve their own. + $ownHiddenGroupsList = CRM_Core_DAO::singleValueQuery(" + SELECT GROUP_CONCAT(id) FROM civicrm_group WHERE is_hidden =1 AND created_id = $contactID + $groupWhere + "); + if ($ownHiddenGroupsList) { + $ownHiddenGroups = explode(',', $ownHiddenGroupsList); + $ids = array_merge((array) $ids, $ownHiddenGroups); + } + + } CRM_Utils_Hook::aclGroup($type, $contactID, $tableName, $allGroups, $ids); - + Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey] = $ids; return $ids; } diff --git a/CRM/ACL/BAO/Cache.php b/CRM/ACL/BAO/Cache.php index 11ac3d33f1a0..921adfeaf6c0 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; } @@ -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 89bcc3f440fd..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 e9ff994dcfa6..51791fb5f5af 100644 --- a/CRM/ACL/DAO/ACL.php +++ b/CRM/ACL/DAO/ACL.php @@ -1,278 +1,318 @@ __table = 'civicrm_acl'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'name' => array( + 'title' => ts('ACL ID'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + '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, - 'html' => array( + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + '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, - 'html' => array( + 'title' => ts('Deny ACL?'), + 'description' => ts('Is this ACL entry Allow (0) or Deny (1) ?'), + 'required' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + '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, - ) , - 'entity_id' => array( + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + 'entity_id' => [ 'name' => 'entity_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Entity ID') , - 'description' => 'ID of the object possessing this ACL', - ) , - 'operation' => array( + 'title' => ts('Entity ID'), + 'description' => ts('ID of the object possessing this ACL'), + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + '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, - 'html' => array( + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + '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, - ) , - 'object_id' => array( + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + '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', - ) , - 'acl_table' => array( + 'title' => ts('ACL Object ID'), + 'description' => ts('The ID of the object controlled by this ACL entry'), + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + '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, - ) , - 'acl_id' => array( + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + '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', - ) , - 'is_active' => array( + 'title' => ts('ACL Group ID'), + 'description' => ts('ID of the ACL or ACL group being granted/revoked'), + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('ACL Is Active?') , - 'description' => 'Is this property active?', - 'html' => array( - 'type' => 'Checkbox', - ) , - ) , - ); + 'title' => ts('ACL Is Active?'), + 'description' => ts('Is this property active?'), + 'table_name' => 'civicrm_acl', + 'entity' => 'ACL', + 'bao' => 'CRM_ACL_BAO_ACL', + '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 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 * @@ -280,10 +320,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 * @@ -291,8 +332,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 = [ + 'index_acl_id' => [ + 'name' => 'index_acl_id', + 'field' => [ + 0 => 'acl_id', + ], + '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/Cache.php b/CRM/ACL/DAO/Cache.php index 6e728c509f08..cd74fd01bba4 100644 --- a/CRM/ACL/DAO/Cache.php +++ b/CRM/ACL/DAO/Cache.php @@ -1,171 +1,175 @@ __table = 'civicrm_acl_cache'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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() , 'acl_id', 'civicrm_acl', '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(), '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() { + 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('Cache ID') , - 'description' => 'Unique table ID', - 'required' => true, - ) , - 'contact_id' => array( + 'title' => ts('Cache ID'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_acl_cache', + 'entity' => 'Cache', + 'bao' => 'CRM_ACL_BAO_Cache', + 'localizable' => 0, + ], + 'contact_id' => [ 'name' => 'contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Cache Contact') , - 'description' => 'Foreign Key to Contact', + 'title' => ts('Cache Contact'), + 'description' => ts('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( + ], + 'acl_id' => [ 'name' => 'acl_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => ts('Cache ACL') , - 'description' => 'Foreign Key to ACL', - 'required' => true, + 'title' => ts('Cache ACL'), + 'description' => ts('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( + ], + 'modified_date' => [ 'name' => 'modified_date', 'type' => CRM_Utils_Type::T_TIMESTAMP, - 'title' => ts('Cache Modified Date') , - 'description' => 'When was this cache entry last modified', - 'required' => false, - ) , - ); + 'title' => ts('Cache Modified Date'), + 'description' => ts('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() { + 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 +177,11 @@ function getLog() { * * @return array */ - static function &import($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_cache', $prefix, 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 * @@ -184,8 +189,30 @@ static function &import($prefix = false) { * * @return array */ - static function &export($prefix = false) { - $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_cache', $prefix, 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/EntityRole.php b/CRM/ACL/DAO/EntityRole.php index af50453f9d66..bb0fda29f27a 100644 --- a/CRM/ACL/DAO/EntityRole.php +++ b/CRM/ACL/DAO/EntityRole.php @@ -1,183 +1,192 @@ __table = 'civicrm_acl_entity_role'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'acl_role_id' => array( + 'title' => ts('Entity Role'), + 'description' => ts('Unique table ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_acl_entity_role', + 'entity' => 'EntityRole', + 'bao' => 'CRM_ACL_BAO_EntityRole', + 'localizable' => 0, + ], + '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, - ) , - 'entity_table' => array( + '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, + 'table_name' => 'civicrm_acl_entity_role', + 'entity' => 'EntityRole', + 'bao' => 'CRM_ACL_BAO_EntityRole', + 'localizable' => 0, + ], + '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, - ) , - 'entity_id' => array( + 'table_name' => 'civicrm_acl_entity_role', + 'entity' => 'EntityRole', + 'bao' => 'CRM_ACL_BAO_EntityRole', + 'localizable' => 0, + ], + '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, - ) , - 'is_active' => array( + 'title' => ts('ACL Entity ID'), + 'description' => ts('ID of the group/contact object being joined'), + 'required' => TRUE, + 'table_name' => 'civicrm_acl_entity_role', + 'entity' => 'EntityRole', + 'bao' => 'CRM_ACL_BAO_EntityRole', + 'localizable' => 0, + ], + '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?'), + '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 * @@ -185,10 +194,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 * @@ -196,8 +206,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 = [ + 'index_role' => [ + 'name' => 'index_role', + 'field' => [ + 0 => 'acl_role_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_acl_entity_role::0::acl_role_id', + ], + 'index_entity' => [ + 'name' => 'index_entity', + 'field' => [ + 0 => 'entity_table', + 1 => 'entity_id', + ], + '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 7de87c72d51a..b119f7503aed 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. diff --git a/CRM/ACL/Form/ACLBasic.php b/CRM/ACL/Form/ACLBasic.php index 17a266616362..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 0a76920026e2..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 b9a7c00f32df..9543c059d5b5 100644 --- a/CRM/Campaign/Info.php +++ b/CRM/Campaign/Info.php @@ -1,9 +1,9 @@ 'CiviCampaign', 'translatedName' => ts('CiviCampaign'), - 'title' => 'CiviCRM Campaign Engine', + '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 3de8c6055c1c..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 50580f4cff3e..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 c78e656da6b7..c526df7f0eee 100644 --- a/CRM/Campaign/Page/Petition.php +++ b/CRM/Campaign/Page/Petition.php @@ -1,9 +1,9 @@ '); - $contact_id = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject); - $subscribe_id = CRM_Utils_Request::retrieve('sid', 'Integer', CRM_Core_DAO::$_nullObject); - $hash = CRM_Utils_Request::retrieve('h', 'String', CRM_Core_DAO::$_nullObject); - $activity_id = CRM_Utils_Request::retrieve('a', 'String', CRM_Core_DAO::$_nullObject); - $petition_id = CRM_Utils_Request::retrieve('pid', 'String', CRM_Core_DAO::$_nullObject); + $contact_id = CRM_Utils_Request::retrieve('cid', 'Integer'); + $subscribe_id = CRM_Utils_Request::retrieve('sid', 'Integer'); + $hash = CRM_Utils_Request::retrieve('h', 'String'); + $activity_id = CRM_Utils_Request::retrieve('a', 'String'); + $petition_id = CRM_Utils_Request::retrieve('pid', 'String'); if (!$petition_id) { - $petition_id = CRM_Utils_Request::retrieve('p', 'String', CRM_Core_DAO::$_nullObject); + $petition_id = CRM_Utils_Request::retrieve('p', 'String'); } if (!$contact_id || @@ -71,7 +72,7 @@ public function run() { $this->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 30a3f8c6bcee..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 babf2893f700..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 983a92c28e9c..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 a71ba31db0fe..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)) { @@ -267,34 +267,37 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { */ public function buildPrevNextCache($sort) { //for prev/next pagination - $crmPID = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject); + $crmPID = CRM_Utils_Request::retrieve('crmPID', 'Integer'); 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. + CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey); + } } } @@ -319,40 +322,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 68352f244d36..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 a6c1c64eb3fe..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); - - 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']; + parent::tasks(); } - return $titles; + return self::$_tasks; } /** @@ -122,13 +101,15 @@ 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) { + public static function permissionedTaskTitles($permission, $params = []) { $tasks = self::taskTitles(); + $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params); return $tasks; } @@ -144,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/Case/Audit/Audit.php b/CRM/Case/Audit/Audit.php index 1928fa4e4383..f58660fef31b 100644 --- a/CRM/Case/Audit/Audit.php +++ b/CRM/Case/Audit/Audit.php @@ -22,7 +22,7 @@ public function __construct($xmlString, $confFilename) { * @return array */ public function getActivities($printReport = FALSE) { - $retval = array(); + $retval = []; /* * Loop through the activities in the file and add them to the appropriate region array. @@ -41,16 +41,16 @@ public function getActivities($printReport = FALSE) { $activityindex = 0; $activityList = $doc->getElementsByTagName("Activity"); - $caseActivities = array(); - $activityStatusType = array(); + $caseActivities = []; + $activityStatusType = []; foreach ($activityList as $activity) { - $retval[$activityindex] = array(); + $retval[$activityindex] = []; - $ifBlankReplacements = array(); + $ifBlankReplacements = []; $completed = FALSE; - $sortValues = array('1970-01-01'); + $sortValues = ['1970-01-01']; $category = ''; $fieldindex = 1; $fields = $activity->getElementsByTagName("Field"); @@ -88,7 +88,7 @@ public function getActivities($printReport = FALSE) { } if ($this->auditConfig->includeInRegion($label, $region)) { - $retval[$activityindex][$region][$fieldindex] = array(); + $retval[$activityindex][$region][$fieldindex] = []; $retval[$activityindex][$region][$fieldindex]['label'] = $label; $retval[$activityindex][$region][$fieldindex]['datatype'] = $datatype; $retval[$activityindex][$region][$fieldindex]['value'] = $value; @@ -98,18 +98,18 @@ public function getActivities($printReport = FALSE) { //CRM-4570 if ($printReport) { - if (!in_array($label, array( + if (!in_array($label, [ 'Activity Type', 'Status', - )) + ]) ) { - $caseActivities[$activityindex][$fieldindex] = array(); + $caseActivities[$activityindex][$fieldindex] = []; $caseActivities[$activityindex][$fieldindex]['label'] = $label; $caseActivities[$activityindex][$fieldindex]['datatype'] = $datatype; $caseActivities[$activityindex][$fieldindex]['value'] = $value; } else { - $activityStatusType[$activityindex][$fieldindex] = array(); + $activityStatusType[$activityindex][$fieldindex] = []; $activityStatusType[$activityindex][$fieldindex]['label'] = $label; $activityStatusType[$activityindex][$fieldindex]['datatype'] = $datatype; $activityStatusType[$activityindex][$fieldindex]['value'] = $value; @@ -166,10 +166,10 @@ public function getActivities($printReport = FALSE) { } if ($printReport) { - @uasort($caseActivities, array($this, "compareActivities")); + @uasort($caseActivities, [$this, "compareActivities"]); } else { - @uasort($retval, array($this, "compareActivities")); + @uasort($retval, [$this, "compareActivities"]); } } diff --git a/CRM/Case/Audit/AuditConfig.php b/CRM/Case/Audit/AuditConfig.php index 14bc772ff168..be1ee8a08d47 100644 --- a/CRM/Case/Audit/AuditConfig.php +++ b/CRM/Case/Audit/AuditConfig.php @@ -22,8 +22,8 @@ public function __construct($filename) { // set some defaults $this->completionLabel = "Status"; $this->completionValue = "Completed"; - $this->sortByLabels = array("Actual Date", "Due Date"); - $this->ifBlanks = array(); + $this->sortByLabels = ["Actual Date", "Due Date"]; + $this->ifBlanks = []; $this->loadConfig(); } @@ -57,22 +57,24 @@ public function getIfBlanks() { } public function loadConfig() { - $this->regionFieldList = array(); - $this->includeRules = array(); + $this->regionFieldList = []; + $this->includeRules = []; $doc = new DOMDocument(); - if ($doc->load(dirname(__FILE__) . '/' . $this->filename)) { + $xmlString = file_get_contents(dirname(__FILE__) . '/' . $this->filename); + $load = $doc->loadXML($xmlString); + if ($load) { $regions = $doc->getElementsByTagName("region"); foreach ($regions as $region) { $regionName = $region->getAttribute("name"); - $this->regionFieldList[$regionName] = array(); + $this->regionFieldList[$regionName] = []; // Inclusion/exclusion settings $includeRule = $region->getAttribute("includeRule"); if (empty($includeRule)) { $includeRule = 'include'; } - $this->includeRules[$regionName] = array('rule' => $includeRule); + $this->includeRules[$regionName] = ['rule' => $includeRule]; if ($includeRule == 'exclude') { $altRegion = $region->getAttribute("exclusionCorrespondingRegion"); $this->includeRules[$regionName]['altRegion'] = $altRegion; @@ -122,7 +124,7 @@ public function loadConfig() { $sortElement = $doc->getElementsByTagName("sortByLabels"); if (!empty($sortElement)) { - $this->sortByLabels = array(); + $this->sortByLabels = []; $label_elements = $sortElement->item(0)->getElementsByTagName("label"); foreach ($label_elements as $ele) { $this->sortByLabels[] = $ele->nodeValue; diff --git a/CRM/Case/BAO/Case.php b/CRM/Case/BAO/Case.php index 3af84c56a496..091b4e9f046f 100644 --- a/CRM/Case/BAO/Case.php +++ b/CRM/Case/BAO/Case.php @@ -1,9 +1,9 @@ copyValues($params); - return $caseDAO->save(); + $result = $caseDAO->save(); + // Get other case values (required by XML processor), this adds to $result array + $caseDAO->find(TRUE); + return $result; } /** @@ -87,6 +90,15 @@ public static function add(&$params) { * @return CRM_Case_BAO_Case */ public static function &create(&$params) { + // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps. + unset($params['created_date']); + unset($params['modified_date']); + $caseStatus = CRM_Case_PseudoConstant::caseStatus('name'); + // for resolved case the end date should set to now + if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) { + $params['end_date'] = date("Ymd"); + } + $transaction = new CRM_Core_Transaction(); if (!empty($params['id'])) { @@ -263,15 +275,16 @@ public static function enableDisableCaseRelationships($caseId, $enable) { * ID of the case. * * @param int $contactID + * @param int $startArrayAt This is to support legacy calls to Case.Get API which may rely on the first array index being set to 1 * * @return array */ - public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) { + public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) { $caseContact = new CRM_Case_DAO_CaseContact(); $caseContact->case_id = $caseId; $caseContact->find(); $contactArray = array(); - $count = 1; + $count = $startArrayAt; while ($caseContact->fetch()) { if ($contactID != $caseContact->contact_id) { $contactArray[$count] = $caseContact->contact_id; @@ -329,7 +342,8 @@ public static function getContactNames($caseId) { LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1) LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1) - WHERE civicrm_case_contact.case_id = %1"; + WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1 + ORDER BY civicrm_case_contact.id"; $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($caseId, 'Integer')) @@ -383,7 +397,6 @@ public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = $caseArray[] = $dao->id; } - $dao->free(); return $caseArray; } @@ -394,51 +407,65 @@ public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = * * @return string */ - public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) { - if (!$userID) { - $session = CRM_Core_Session::singleton(); - $userID = $session->get('userID'); - } - - $query = "SELECT -civicrm_case.id as case_id, -civicrm_case.subject as case_subject, -civicrm_contact.id as contact_id, -civicrm_contact.sort_name as sort_name, -civicrm_phone.phone as phone, -civicrm_contact.contact_type as contact_type, -civicrm_contact.contact_sub_type as contact_sub_type, -t_act.activity_type_id, -c_type.title as case_type, -civicrm_case.case_type_id as case_type_id, -cov_status.label as case_status, -cov_status.label as case_status_name, -t_act.status_id, -civicrm_case.start_date as case_start_date, -case_relation_type.label_b_a as case_role, "; + public static function getCaseActivityCountQuery($type = 'upcoming', $userID, $condition = NULL) { + return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self::getCaseActivityQuery($type, $userID, $condition)); + } + + /** + * @param string $type + * @param int $userID + * @param string $condition + * @param string $limit + * @param string $order + * + * @return string + */ + public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) { + $selectClauses = array( + 'civicrm_case.id as case_id', + 'civicrm_case.subject as case_subject', + 'civicrm_contact.id as contact_id', + 'civicrm_contact.sort_name as sort_name', + 'civicrm_phone.phone as phone', + 'civicrm_contact.contact_type as contact_type', + 'civicrm_contact.contact_sub_type as contact_sub_type', + 't_act.activity_type_id', + 'c_type.title as case_type', + 'civicrm_case.case_type_id as case_type_id', + 'cov_status.label as case_status', + 'cov_status.label as case_status_name', + 't_act.status_id', + 'civicrm_case.start_date as case_start_date', + 'case_relation_type.label_b_a as case_role', + ); if ($type == 'upcoming') { - $query .= " -t_act.desired_date as case_scheduled_activity_date, -t_act.id as case_scheduled_activity_id, -t_act.act_type_name as case_scheduled_activity_type_name, -t_act.act_type AS case_scheduled_activity_type "; + $selectClauses = array_merge($selectClauses, array( + 't_act.desired_date as case_scheduled_activity_date', + 't_act.id as case_scheduled_activity_id', + 't_act.act_type_name as case_scheduled_activity_type_name', + 't_act.act_type AS case_scheduled_activity_type', + )); } elseif ($type == 'recent') { - $query .= " -t_act.desired_date as case_recent_activity_date, -t_act.id as case_recent_activity_id, -t_act.act_type_name as case_recent_activity_type_name, -t_act.act_type AS case_recent_activity_type "; + $selectClauses = array_merge($selectClauses, array( + 't_act.desired_date as case_recent_activity_date', + 't_act.id as case_recent_activity_id', + 't_act.act_type_name as case_recent_activity_type_name', + 't_act.act_type AS case_recent_activity_type', + )); } elseif ($type == 'any') { - $query .= " -t_act.desired_date as case_activity_date, -t_act.id as case_activity_id, -t_act.act_type_name as case_activity_type_name, -t_act.act_type AS case_activity_type "; + $selectClauses = array_merge($selectClauses, array( + 't_act.desired_date as case_activity_date', + 't_act.id as case_activity_id', + 't_act.act_type_name as case_activity_type_name', + 't_act.act_type AS case_activity_type', + )); } + $query = CRM_Contact_BAO_Query::appendAnyValueToSelect($selectClauses, 'case_id'); + $query .= " FROM civicrm_case INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id "; @@ -502,9 +529,7 @@ public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, ON t_act.case_id = civicrm_case.id LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1) LEFT JOIN civicrm_relationship case_relationship - ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID} - AND case_relationship.case_id = civicrm_case.id ) - + ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active AND case_relationship.case_id = civicrm_case.id ) LEFT JOIN civicrm_relationship_type case_relation_type ON ( case_relation_type.id = case_relationship.relationship_type_id AND case_relation_type.id = case_relationship.relationship_type_id ) @@ -522,17 +547,27 @@ public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, if ($condition) { // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND" - $query .= " WHERE (1) $condition "; + $query .= " WHERE (1) AND $condition "; } + $query .= " GROUP BY case_id "; - if ($type == 'upcoming') { - $query .= " ORDER BY case_scheduled_activity_date ASC "; + if ($order) { + $query .= $order; } - elseif ($type == 'recent') { - $query .= " ORDER BY case_recent_activity_date ASC "; + else { + if ($type == 'upcoming') { + $query .= " ORDER BY case_scheduled_activity_date ASC "; + } + elseif ($type == 'recent') { + $query .= " ORDER BY case_recent_activity_date ASC "; + } + elseif ($type == 'any') { + $query .= " ORDER BY case_activity_date ASC "; + } } - elseif ($type == 'any') { - $query .= " ORDER BY case_activity_date ASC "; + + if ($limit) { + $query .= $limit; } return $query; @@ -542,92 +577,93 @@ public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab. * * @param bool $allCases - * - * @param int $userID - * - * @param string $type - * /upcoming,recent,all/. - * + * @param array $params * @param string $context + * @param bool $getCount * * @return array * Array of Cases */ - public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') { + public static function getCases($allCases = TRUE, $params = array(), $context = 'dashboard', $getCount = FALSE) { $condition = NULL; $casesList = array(); - //validate access for own cases. + // validate access for own cases. if (!self::accessCiviCase()) { - return $casesList; + return $getCount ? 0 : $casesList; } - if (!$userID) { - $session = CRM_Core_Session::singleton(); - $userID = $session->get('userID'); + // Return cached value instead of re-running query + if (isset(Civi::$statics[__CLASS__]['totalCount']) && $getCount) { + return Civi::$statics[__CLASS__]['totalCount']; } - //validate access for all cases. + $type = CRM_Utils_Array::value('type', $params, 'upcoming'); + $userID = CRM_Core_Session::singleton()->get('userID'); + + $caseActivityTypeColumn = 'case_activity_type_name'; + $caseActivityDateColumn = 'case_activity_date'; + $caseActivityIDColumn = 'case_activity_id'; + if ($type == 'upcoming') { + $caseActivityDateColumn = 'case_scheduled_activity_date'; + $caseActivityTypeColumn = 'case_scheduled_activity_type'; + $caseActivityIDColumn = 'case_scheduled_activity_id'; + } + elseif ($type == 'recent') { + $caseActivityDateColumn = 'case_recent_activity_date'; + $caseActivityTypeColumn = 'case_recent_activity_type'; + $caseActivityIDColumn = 'case_recent_activity_id'; + } + + // validate access for all cases. if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) { $allCases = FALSE; } - $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1"; + $whereClauses = array('civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1'); if (!$allCases) { - $condition .= " AND case_relationship.contact_id_b = {$userID} "; + $whereClauses[] .= " case_relationship.contact_id_b = {$userID} AND case_relationship.is_active "; } - if ($type == 'upcoming' || $type == 'any') { - $closedId = CRM_Core_OptionGroup::getValue('case_status', 'Closed', 'name'); - $condition .= " -AND civicrm_case.status_id != $closedId"; + if (empty($params['status_id']) && ($type == 'upcoming' || $type == 'any')) { + $whereClauses[] = " civicrm_case.status_id != " . CRM_Core_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed'); } - $query = self::getCaseActivityQuery($type, $userID, $condition); - - $queryParams = array(); - $result = CRM_Core_DAO::executeQuery($query, - $queryParams - ); - - $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' "); - - $resultFields = array( - 'contact_id', - 'contact_type', - 'sort_name', - 'phone', - 'case_id', - 'case_subject', - 'case_type', - 'case_type_id', - 'status_id', - 'case_status', - 'case_status_name', - 'activity_type_id', - 'case_start_date', - 'case_role', - ); + foreach (array('case_type_id', 'status_id') as $column) { + if (!empty($params[$column])) { + $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]); + } + } + $condition = implode(' AND ', $whereClauses); - if ($type == 'upcoming') { - $resultFields[] = 'case_scheduled_activity_date'; - $resultFields[] = 'case_scheduled_activity_type_name'; - $resultFields[] = 'case_scheduled_activity_type'; - $resultFields[] = 'case_scheduled_activity_id'; + Civi::$statics[__CLASS__]['totalCount'] = $totalCount = CRM_Core_DAO::singleValueQuery(self::getCaseActivityCountQuery($type, $userID, $condition)); + if ($getCount) { + return $totalCount; } - elseif ($type == 'recent') { - $resultFields[] = 'case_recent_activity_date'; - $resultFields[] = 'case_recent_activity_type_name'; - $resultFields[] = 'case_recent_activity_type'; - $resultFields[] = 'case_recent_activity_id'; + $casesList['total'] = $totalCount; + + $limit = ''; + if (!empty($params['rp'])) { + $params['offset'] = ($params['page'] - 1) * $params['rp']; + $params['rowCount'] = $params['rp']; + if (!empty($params['rowCount']) && $params['rowCount'] > 0) { + $limit = " LIMIT {$params['offset']}, {$params['rowCount']} "; + } } - elseif ($type == 'any') { - $resultFields[] = 'case_activity_date'; - $resultFields[] = 'case_activity_type_name'; - $resultFields[] = 'case_activity_type'; - $resultFields[] = 'case_activity_id'; + + $order = NULL; + if (!empty($params['sortBy'])) { + if (strstr($params['sortBy'], 'date ')) { + $params['sortBy'] = str_replace('date', $caseActivityDateColumn, $params['sortBy']); + } + $order = "ORDER BY " . $params['sortBy']; } + $query = self::getCaseActivityQuery($type, $userID, $condition, $limit, $order); + $result = CRM_Core_DAO::executeQuery($query); + + $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' "); + // we're going to use the usual actions, so doesn't make sense to duplicate definitions $actions = CRM_Case_Selector_Search::links(); @@ -643,68 +679,75 @@ public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcom } $mask = CRM_Core_Action::mask($permissions); - while ($result->fetch()) { - foreach ($resultFields as $donCare => $field) { - $casesList[$result->case_id][$field] = $result->$field; - if ($field == 'contact_type') { - $casesList[$result->case_id]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type - ); - $casesList[$result->case_id]['action'] = CRM_Core_Action::formLink($actions['primaryActions'], $mask, - array( - 'id' => $result->case_id, - 'cid' => $result->contact_id, - 'cxt' => $context, - ), - ts('more'), - FALSE, - 'case.actions.primary', - 'Case', - $result->case_id - ); - $casesList[$result->case_id]['moreActions'] = CRM_Core_Action::formLink($actions['moreActions'], - $mask, - array( - 'id' => $result->case_id, - 'cid' => $result->contact_id, - 'cxt' => $context, - ), - ts('more'), - TRUE, - 'case.actions.more', - 'Case', - $result->case_id - ); - } - elseif ($field == 'case_status') { - if (in_array($result->$field, $caseStatus)) { - $casesList[$result->case_id]['class'] = "status-urgent"; + $caseTypes = CRM_Case_PseudoConstant::caseType('name'); + foreach ($result->fetchAll() as $case) { + $key = $case['case_id']; + $casesList[$key] = array(); + $casesList[$key]['DT_RowId'] = $case['case_id']; + $casesList[$key]['DT_RowAttr'] = array('data-entity' => 'case', 'data-id' => $case['case_id']); + $casesList[$key]['DT_RowClass'] = "crm-entity"; + + $casesList[$key]['activity_list'] = sprintf('', + ts('Activities'), + CRM_Utils_System::url('civicrm/case/details', array('caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type)) + ); + + $phone = empty($case['phone']) ? '' : '{$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']; @@ -2143,4 +2182,107 @@ public static function getContactRelationshipSelector(&$params) { return $relationshipsDT; } + /** + * @inheritdoc + */ + public static function buildOptions($fieldName, $context = NULL, $props = array()) { + 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 = array()) { + $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. + */ + public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) { + $existingTypeID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id'); + $existingTypeName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a'); + $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID; + + if ($existingTypeName !== 'Employer of') { + 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) { + return TRUE; + } + + return FALSE; + } + } diff --git a/CRM/Contact/BAO/RelationshipType.php b/CRM/Contact/BAO/RelationshipType.php index 0e3cc3bf89eb..e229a03ea571 100644 --- a/CRM/Contact/BAO/RelationshipType.php +++ b/CRM/Contact/BAO/RelationshipType.php @@ -1,9 +1,9 @@ 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 +142,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 a635591cee83..049dcaf5170b 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', + 'participant_register_date_low' => 'participant_date_low', + 'participant_register_date_high' => 'participant_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,15 +110,49 @@ 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); $value = CRM_Utils_Array::value(2, $value); if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { - $value = CRM_Utils_Array::value(key($value), $value); + $op = key($value); + $value = CRM_Utils_Array::value($op, $value); + 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); + + // 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 { + $result[$id] = $value; } - $result[$id] = $value; unset($result[$element]); continue; } @@ -153,7 +198,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; @@ -164,6 +209,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; } @@ -227,7 +279,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 )'; @@ -255,10 +307,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 { @@ -270,7 +322,7 @@ 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); + return [$from, $where]; } } @@ -288,7 +340,7 @@ public function buildClause() { } if (!empty($params)) { - $tables = $whereTables = array(); + $tables = $whereTables = []; $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables); if (!empty($tables)) { $this->select_tables = serialize($tables); @@ -370,11 +422,111 @@ 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); } } + /** + * Store relative dates in separate array format + * + * @param array $queryParams + * @param array $formValues + */ + public static function saveRelativeDates(&$queryParams, $formValues) { + $relativeDates = ['relative_dates' => []]; + $specialDateFields = ['event_relative', 'case_from_relative', 'case_to_relative', 'participant_relative']; + foreach ($formValues as $id => $value) { + if ((preg_match('/(_date|custom_[0-9]+)_relative$/', $id) || in_array($id, $specialDateFields)) && !empty($value)) { + $entityName = strstr($id, '_date', TRUE); + if (empty($entityName)) { + $entityName = strstr($id, '_relative', TRUE); + } + $relativeDates['relative_dates'][$entityName] = $value; + } + } + // merge with original queryParams if relative date value(s) found + if (count($relativeDates['relative_dates'])) { + $queryParams = array_merge($queryParams, $relativeDates); + } + } + + /** + * Store search variables in $queryParams which were skipped while processing query params, + * precisely at CRM_Contact_BAO_Query::fixWhereValues(...). But these variable are required in + * building smart group criteria otherwise it will cause issues like CRM-18585,CRM-19571 + * + * @param array $queryParams + * @param array $formValues + */ + public static function saveSkippedElement(&$queryParams, $formValues) { + // these are elements which are skipped in a smart group criteria + $specialElements = [ + 'operator', + 'component_mode', + 'display_relationship_type', + 'uf_group_id', + ]; + foreach ($specialElements as $element) { + if (!empty($formValues[$element])) { + $queryParams[] = [$element, '=', $formValues[$element], 0, 0]; + } + } + } + + /** + * Decode relative custom fields (converted by CRM_Contact_BAO_Query->convertCustomRelativeFields(...)) + * into desired formValues + * + * @param array $formValues + * @param string $fieldName + * @param string $op + * @param array|string|int $value + */ + public static function decodeRelativeFields(&$formValues, $fieldName, $op, $value) { + // check if its a custom date field, if yes then 'searchDate' format the value + $isCustomDateField = CRM_Contact_BAO_Query::isCustomDateField($fieldName); + + // select date range as default + if ($isCustomDateField) { + 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': + if ($isCustomDateField) { + list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date::setDateDefaults($value[0], 'searchDate'); + list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date::setDateDefaults($value[1], 'searchDate'); + } + else { + list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_to']) = $value; + } + break; + + case '>=': + if ($isCustomDateField) { + list($formValues[$fieldName . '_from'], $formValues[$fieldName . '_from_time']) = CRM_Utils_Date::setDateDefaults($value, 'searchDate'); + } + else { + $formValues[$fieldName . '_from'] = $value; + } + break; + + case '<=': + if ($isCustomDateField) { + list($formValues[$fieldName . '_to'], $formValues[$fieldName . '_to_time']) = CRM_Utils_Date::setDateDefaults($value, 'searchDate'); + } + else { + $formValues[$fieldName . '_to'] = $value; + } + break; + } + } + } diff --git a/CRM/Contact/BAO/SearchCustom.php b/CRM/Contact/BAO/SearchCustom.php index 263f648a0917..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(); @@ -96,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]; } /** @@ -139,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)) { @@ -161,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 3fbb10bf7861..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 + * 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, - ) , - 'user_id' => array( + 'title' => ts('ACL Contact Cache ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'table_name' => 'civicrm_acl_contact_cache', + 'entity' => 'ACLContactCache', + 'bao' => 'CRM_Contact_DAO_ACLContactCache', + 'localizable' => 0, + ], + '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)', - 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'contact_id' => array( + 'title' => ts('Contact ID'), + 'description' => ts('FK to civicrm_contact (could be null for anon user)'), + 'table_name' => 'civicrm_acl_contact_cache', + 'entity' => 'ACLContactCache', + 'bao' => 'CRM_Contact_DAO_ACLContactCache', + 'localizable' => 0, + ], + '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, + '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, - 'html' => array( + 'table_name' => 'civicrm_acl_contact_cache', + 'entity' => 'ACLContactCache', + 'bao' => 'CRM_Contact_DAO_ACLContactCache', + 'localizable' => 0, + '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 * @@ -181,10 +183,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 * @@ -192,8 +195,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 = [ + 'UI_user_contact_operation' => [ + 'name' => 'UI_user_contact_operation', + 'field' => [ + 0 => 'user_id', + 1 => 'contact_id', + 2 => 'operation', + ], + '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 b82bc3733089..c5833d27b865 100644 --- a/CRM/Contact/DAO/Contact.php +++ b/CRM/Contact/DAO/Contact.php @@ -1,1184 +1,1457 @@ __table = 'civicrm_contact'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'contact_type' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + ], + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.contact_type', 'headerPattern' => '', 'dataPattern' => '', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.sort_name', 'headerPattern' => '', 'dataPattern' => '', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.display_name', 'headerPattern' => '', 'dataPattern' => '', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.hash', 'headerPattern' => '', 'dataPattern' => '', - ) , - 'api_key' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + ], + '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, - ) , - 'contact_source' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + ], + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.'), + 'export' => TRUE, 'where' => 'civicrm_contact.communication_style_id', 'headerPattern' => '', 'dataPattern' => '', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.', - ) , - 'email_greeting_custom' => array( + 'title' => ts('Email Greeting ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Email Greeting.'), + 'export' => TRUE, + 'where' => 'civicrm_contact.email_greeting_id', + 'headerPattern' => '', + 'dataPattern' => '', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => FALSE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.', - 'html' => array( + 'title' => ts('Postal Greeting ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Postal Greeting.'), + 'export' => TRUE, + 'where' => 'civicrm_contact.postal_greeting_id', + 'headerPattern' => '', + 'dataPattern' => '', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => FALSE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.', - ) , - 'addressee_custom' => array( + 'title' => ts('Addressee ID'), + 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Addressee.'), + 'export' => TRUE, + 'where' => 'civicrm_contact.addressee_id', + 'headerPattern' => '', + 'dataPattern' => '', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => FALSE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + 'html' => [ 'type' => 'Select Date', - ) , - ) , - 'is_deceased' => array( + 'formatType' => 'birth', + ], + ], + '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, - 'html' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + 'html' => [ 'type' => 'Select Date', - ) , - ) , - 'household_name' => array( + 'formatType' => 'birth', + ], + ], + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.'), + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, - 'html' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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', - 'html' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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.'), + 'export' => TRUE, 'where' => 'civicrm_contact.employer_id', 'headerPattern' => '', 'dataPattern' => '', + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.is_deleted', 'headerPattern' => '', 'dataPattern' => '', - 'html' => array( + 'default' => '0', + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.created_date', 'headerPattern' => '', 'dataPattern' => '', 'default' => 'NULL', - ) , - 'modified_date' => array( + 'table_name' => 'civicrm_contact', + 'entity' => 'Contact', + 'bao' => 'CRM_Contact_BAO_Contact', + 'localizable' => 0, + ], + '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, + 'export' => TRUE, 'where' => 'civicrm_contact.modified_date', 'headerPattern' => '', 'dataPattern' => '', '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 * @@ -1186,10 +1459,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 * @@ -1197,8 +1471,161 @@ 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 = [ + 'index_contact_type' => [ + 'name' => 'index_contact_type', + 'field' => [ + 0 => 'contact_type', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::contact_type', + ], + 'index_contact_sub_type' => [ + 'name' => 'index_contact_sub_type', + 'field' => [ + 0 => 'contact_sub_type', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::contact_sub_type', + ], + 'UI_external_identifier' => [ + 'name' => 'UI_external_identifier', + 'field' => [ + 0 => 'external_identifier', + ], + 'localizable' => FALSE, + 'unique' => TRUE, + 'sig' => 'civicrm_contact::1::external_identifier', + ], + 'index_sort_name' => [ + 'name' => 'index_sort_name', + 'field' => [ + 0 => 'sort_name', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::sort_name', + ], + 'index_preferred_communication_method' => [ + 'name' => 'index_preferred_communication_method', + 'field' => [ + 0 => 'preferred_communication_method', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::preferred_communication_method', + ], + 'index_hash' => [ + 'name' => 'index_hash', + 'field' => [ + 0 => 'hash', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::hash', + ], + 'index_api_key' => [ + 'name' => 'index_api_key', + 'field' => [ + 0 => 'api_key', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::api_key', + ], + 'index_first_name' => [ + 'name' => 'index_first_name', + 'field' => [ + 0 => 'first_name', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::first_name', + ], + 'index_last_name' => [ + 'name' => 'index_last_name', + 'field' => [ + 0 => 'last_name', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::last_name', + ], + 'UI_prefix' => [ + 'name' => 'UI_prefix', + 'field' => [ + 0 => 'prefix_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::prefix_id', + ], + 'UI_suffix' => [ + 'name' => 'UI_suffix', + 'field' => [ + 0 => 'suffix_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::suffix_id', + ], + 'index_communication_style_id' => [ + 'name' => 'index_communication_style_id', + 'field' => [ + 0 => 'communication_style_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::communication_style_id', + ], + 'UI_gender' => [ + 'name' => 'UI_gender', + 'field' => [ + 0 => 'gender_id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::gender_id', + ], + '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' => [ + 0 => 'household_name', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::household_name', + ], + 'index_organization_name' => [ + 'name' => 'index_organization_name', + 'field' => [ + 0 => 'organization_name', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::organization_name', + ], + 'index_is_deleted_sort_name' => [ + 'name' => 'index_is_deleted_sort_name', + 'field' => [ + 0 => 'is_deleted', + 1 => 'sort_name', + 2 => 'id', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_contact::0::is_deleted::sort_name::id', + ], + ]; + 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 ac5fb9024aef..db032d503fe6 100644 --- a/CRM/Contact/DAO/ContactType.php +++ b/CRM/Contact/DAO/ContactType.php @@ -1,232 +1,256 @@ __table = 'civicrm_contact_type'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'name' => array( + 'title' => ts('Contact Type ID'), + 'description' => ts('Contact Type ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 0, + ], + '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, - ) , - 'label' => array( + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 0, + ], + '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, - ) , - 'description' => array( + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 1, + ], + '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, - 'html' => array( + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 1, + '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, - ) , - 'parent_id' => array( + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 0, + ], + '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.'), + '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?', - ) , - 'is_reserved' => array( + 'title' => ts('Contact Type Is Active?'), + 'description' => ts('Is this entry active?'), + 'table_name' => 'civicrm_contact_type', + 'entity' => 'ContactType', + 'bao' => 'CRM_Contact_BAO_ContactType', + 'localizable' => 0, + ], + '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'), + '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 * @@ -234,10 +258,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 * @@ -245,8 +270,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 = [ + 'contact_type' => [ + 'name' => 'contact_type', + 'field' => [ + 0 => 'name', + ], + '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 8f366e164c2f..8b354a2bb3d8 100644 --- a/CRM/Contact/DAO/DashboardContact.php +++ b/CRM/Contact/DAO/DashboardContact.php @@ -1,193 +1,209 @@ __table = 'civicrm_dashboard_contact'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'dashboard_id' => array( + 'title' => ts('Dashboard Contact ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_dashboard_contact', + 'entity' => 'DashboardContact', + 'bao' => 'CRM_Contact_BAO_DashboardContact', + 'localizable' => 0, + ], + '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, + '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, + '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', - ) , - 'is_active' => array( + 'title' => ts('Column No'), + 'description' => ts('column no for this widget'), + 'default' => '0', + 'table_name' => 'civicrm_dashboard_contact', + 'entity' => 'DashboardContact', + 'bao' => 'CRM_Contact_BAO_DashboardContact', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Dashlet is Active?') , - 'description' => 'Is this widget active?', - ) , - 'weight' => array( + 'title' => ts('Dashlet is Active?'), + 'description' => ts('Is this widget active?'), + 'default' => '0', + 'table_name' => 'civicrm_dashboard_contact', + 'entity' => 'DashboardContact', + 'bao' => 'CRM_Contact_BAO_DashboardContact', + 'localizable' => 0, + ], + '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.'), + '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 * @@ -195,10 +211,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 * @@ -206,8 +223,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 = [ + 'index_dashboard_id_contact_id' => [ + 'name' => 'index_dashboard_id_contact_id', + 'field' => [ + 0 => 'dashboard_id', + 1 => 'contact_id', + ], + '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 2dd24c632e40..1213b90fc6e9 100644 --- a/CRM/Contact/DAO/Group.php +++ b/CRM/Contact/DAO/Group.php @@ -1,389 +1,481 @@ __table = 'civicrm_group'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'name' => array( + 'title' => ts('Group ID'), + 'description' => ts('Group ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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, - ) , - 'title' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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, - ) , - 'description' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 1, + ], + '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, - 'html' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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, - ) , - 'saved_search_id' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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.'), + '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?', - ) , - 'visibility' => array( + 'title' => ts('Group Enabled'), + 'description' => ts('Is this entry active?'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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, 'default' => 'User and User Admin Only', - 'html' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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', - ) , - 'select_tables' => array( + 'title' => ts('Group Where Clause'), + 'description' => ts('the sql where clause if a saved search acl'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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', - ) , - 'where_tables' => array( + 'title' => ts('Tables For Select Clause'), + 'description' => ts('the tables to be included in a select data'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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', - ) , - 'group_type' => array( + 'title' => ts('Tables For Where Clause'), + 'description' => ts('the tables to be included in the count statement'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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, - 'pseudoconstant' => array( + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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, - ) , - 'refresh_date' => array( + 'title' => ts('Group Cache Date'), + 'description' => ts('Date when we created the cache for a smart group'), + 'required' => FALSE, + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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, - ) , - 'parents' => array( + 'title' => ts('Next Group Refresh Time'), + 'description' => ts('Date and time when we need to refresh the cache next.'), + 'required' => FALSE, + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + 'parents' => [ 'name' => 'parents', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => ts('Group Parents') , - 'description' => 'IDs of the parent(s)', - ) , - 'children' => array( + 'title' => ts('Group Parents'), + 'description' => ts('IDs of the parent(s)'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + '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)', - ) , - 'is_hidden' => array( + 'title' => ts('Group Children'), + 'description' => ts('IDs of the child(ren)'), + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + 'is_hidden' => [ 'name' => 'is_hidden', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Group is Hidden') , - 'description' => 'Is this group hidden?', - ) , - 'is_reserved' => array( + 'title' => ts('Group is Hidden'), + 'description' => ts('Is this group hidden?'), + 'default' => '0', + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + 'is_reserved' => [ 'name' => 'is_reserved', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => ts('Group is Reserved') , - ) , - 'created_id' => array( + 'title' => ts('Group is Reserved'), + 'default' => '0', + 'table_name' => 'civicrm_group', + 'entity' => 'Group', + 'bao' => 'CRM_Contact_BAO_Group', + 'localizable' => 0, + ], + '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.'), + '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.'), + '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 * @@ -391,10 +483,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 * @@ -402,8 +495,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 = [ + 'index_group_type' => [ + 'name' => 'index_group_type', + 'field' => [ + 0 => 'group_type', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_group::0::group_type', + ], + 'UI_title' => [ + 'name' => 'UI_title', + 'field' => [ + 0 => 'title', + ], + 'localizable' => TRUE, + 'unique' => TRUE, + 'sig' => 'civicrm_group::1::title', + ], + 'UI_name' => [ + 'name' => 'UI_name', + 'field' => [ + 0 => 'name', + ], + '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 964b8e737f44..8a259670c63a 100644 --- a/CRM/Contact/DAO/GroupContact.php +++ b/CRM/Contact/DAO/GroupContact.php @@ -1,215 +1,229 @@ __table = 'civicrm_group_contact'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'group_id' => array( + 'title' => ts('Group Contact ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'table_name' => 'civicrm_group_contact', + 'entity' => 'GroupContact', + 'bao' => 'CRM_Contact_BAO_GroupContact', + 'localizable' => 0, + ], + '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, + '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, + '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, - 'html' => array( + 'table_name' => 'civicrm_group_contact', + 'entity' => 'GroupContact', + 'bao' => 'CRM_Contact_BAO_GroupContact', + 'localizable' => 0, + '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'), + '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'), + '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 * @@ -217,10 +231,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 * @@ -228,8 +243,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 = [ + 'UI_contact_group' => [ + 'name' => 'UI_contact_group', + 'field' => [ + 0 => 'contact_id', + 1 => 'group_id', + ], + '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 87a88a4fe231..7e97bd7b867d 100644 --- a/CRM/Contact/DAO/GroupContactCache.php +++ b/CRM/Contact/DAO/GroupContactCache.php @@ -1,167 +1,166 @@ __table = 'civicrm_group_contact_cache'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'group_id' => array( + 'title' => ts('Group Contact Cache ID'), + 'description' => ts('primary key'), + 'required' => TRUE, + 'table_name' => 'civicrm_group_contact_cache', + 'entity' => 'GroupContactCache', + 'bao' => 'CRM_Contact_BAO_GroupContactCache', + 'localizable' => 0, + ], + '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, + '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, + '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 * @@ -169,10 +168,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 * @@ -180,8 +180,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 = [ + 'UI_contact_group' => [ + 'name' => 'UI_contact_group', + 'field' => [ + 0 => 'contact_id', + 1 => 'group_id', + ], + '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 f1dca5b1a6f3..d7a59df69366 100644 --- a/CRM/Contact/DAO/GroupNesting.php +++ b/CRM/Contact/DAO/GroupNesting.php @@ -1,159 +1,158 @@ __table = 'civicrm_group_nesting'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'child_group_id' => array( + 'title' => ts('Group Nesting ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_group_nesting', + 'entity' => 'GroupNesting', + 'bao' => 'CRM_Contact_BAO_GroupNesting', + 'localizable' => 0, + ], + '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, + '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, + '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 * @@ -161,10 +160,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 * @@ -172,8 +172,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 = []; + 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 6de29b76c83c..fd90ae2bfba3 100644 --- a/CRM/Contact/DAO/GroupOrganization.php +++ b/CRM/Contact/DAO/GroupOrganization.php @@ -1,167 +1,166 @@ __table = 'civicrm_group_organization'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'group_id' => array( + 'title' => ts('Group Organization ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_group_organization', + 'entity' => 'GroupOrganization', + 'bao' => 'CRM_Contact_BAO_GroupOrganization', + 'localizable' => 0, + ], + '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, + '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, + '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 * @@ -169,10 +168,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 * @@ -180,8 +180,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 = [ + 'UI_group_organization' => [ + 'name' => 'UI_group_organization', + 'field' => [ + 0 => 'group_id', + 1 => 'organization_id', + ], + '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 c8a926576b4c..c40f42183154 100644 --- a/CRM/Contact/DAO/Relationship.php +++ b/CRM/Contact/DAO/Relationship.php @@ -1,294 +1,339 @@ __table = 'civicrm_relationship'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'contact_id_a' => array( + 'title' => ts('Relationship ID'), + 'description' => ts('Relationship ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + ], + '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, + '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, + '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, + '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', - 'html' => array( + 'title' => ts('Relationship Start Date'), + 'description' => ts('date when the relationship started'), + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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', - 'html' => array( + 'title' => ts('Relationship End Date'), + 'description' => ts('date when the relationship ended'), + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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 ?'), 'default' => '1', - 'html' => array( + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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 ? - ', - 'html' => array( - 'type' => 'CheckBox', - ) , - ) , - 'is_permission_b_a' => array( + '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, + 'default' => '0', + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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 ? - ', - 'html' => array( - 'type' => 'CheckBox', - ) , - ) , - 'case_id' => array( + '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, + 'default' => '0', + 'table_name' => 'civicrm_relationship', + 'entity' => 'Relationship', + 'bao' => 'CRM_Contact_BAO_Relationship', + 'localizable' => 0, + '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'), '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 * @@ -296,10 +341,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 * @@ -307,8 +353,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 = []; + 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 3e72e48b5f03..11bb3d1ba0eb 100644 --- a/CRM/Contact/DAO/RelationshipType.php +++ b/CRM/Contact/DAO/RelationshipType.php @@ -1,306 +1,364 @@ __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, - ) , - 'name_a_b' => array( + 'title' => ts('Relationship Type ID'), + 'description' => ts('Primary key'), + 'required' => TRUE, + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + ], + '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, - ) , - 'label_a_b' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + ], + '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, - ) , - 'name_b_a' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 1, + '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, - ) , - 'label_b_a' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + ], + '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, - ) , - 'description' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 1, + '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, - ) , - 'contact_type_a' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 1, + '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, - 'html' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + '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, - 'html' => array( + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + '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)?', - ) , - 'is_active' => array( + 'title' => ts('Relationship Type is Reserved'), + 'description' => ts('Is this relationship type a predefined system type (can not be changed or de-activated)?'), + 'table_name' => 'civicrm_relationship_type', + 'entity' => 'RelationshipType', + 'bao' => 'CRM_Contact_BAO_RelationshipType', + 'localizable' => 0, + '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)? + '), '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 * @@ -308,10 +366,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 * @@ -319,8 +378,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 = [ + 'UI_name_a_b' => [ + 'name' => 'UI_name_a_b', + 'field' => [ + 0 => 'name_a_b', + ], + 'localizable' => FALSE, + 'unique' => TRUE, + 'sig' => 'civicrm_relationship_type::1::name_a_b', + ], + 'UI_name_b_a' => [ + 'name' => 'UI_name_b_a', + 'field' => [ + 0 => 'name_b_a', + ], + '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 58abf71a950f..e1c75e9bac0e 100644 --- a/CRM/Contact/DAO/SavedSearch.php +++ b/CRM/Contact/DAO/SavedSearch.php @@ -1,208 +1,230 @@ __table = 'civicrm_saved_search'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'form_values' => array( + 'title' => ts('Saved Search ID'), + 'description' => ts('Saved Search ID'), + 'required' => TRUE, + 'table_name' => 'civicrm_saved_search', + 'entity' => 'SavedSearch', + 'bao' => 'CRM_Contact_BAO_SavedSearch', + 'localizable' => 0, + ], + '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, - ) , - 'mapping_id' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_saved_search', + 'entity' => 'SavedSearch', + 'bao' => 'CRM_Contact_BAO_SavedSearch', + 'localizable' => 0, + '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.'), + '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.', - ) , - 'where_clause' => array( + 'title' => ts('Option Value ID'), + 'description' => ts('Foreign key to civicrm_option value table used for saved custom searches.'), + 'table_name' => 'civicrm_saved_search', + 'entity' => 'SavedSearch', + 'bao' => 'CRM_Contact_BAO_SavedSearch', + 'localizable' => 0, + ], + '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', - ) , - 'select_tables' => array( + 'title' => ts('Where Clause'), + 'description' => ts('the sql where clause if a saved search acl'), + 'table_name' => 'civicrm_saved_search', + 'entity' => 'SavedSearch', + 'bao' => 'CRM_Contact_BAO_SavedSearch', + 'localizable' => 0, + ], + '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', - ) , - 'where_tables' => array( + 'title' => ts('Select Tables'), + 'description' => ts('the tables to be included in a select data'), + 'table_name' => 'civicrm_saved_search', + 'entity' => 'SavedSearch', + 'bao' => 'CRM_Contact_BAO_SavedSearch', + 'localizable' => 0, + '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'), + '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 * @@ -210,10 +232,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 * @@ -221,8 +244,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 = []; + 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 5559618bce33..90f7ea3d8f81 100644 --- a/CRM/Contact/DAO/SubscriptionHistory.php +++ b/CRM/Contact/DAO/SubscriptionHistory.php @@ -1,230 +1,250 @@ __table = 'civicrm_subscription_history'; parent::__construct(); } + /** - * Returns foreign keys and entity references + * 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, - ) , - 'contact_id' => array( + 'title' => ts('Group Membership History ID'), + 'description' => ts('Internal Id'), + 'required' => TRUE, + 'table_name' => 'civicrm_subscription_history', + 'entity' => 'SubscriptionHistory', + 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', + 'localizable' => 0, + ], + '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, + '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'), + '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, - ) , - 'method' => array( + 'type' => CRM_Utils_Type::T_TIMESTAMP, + 'title' => ts('Group Membership Action Date'), + 'description' => ts('Date of the (un)subscription'), + 'required' => TRUE, + 'default' => 'CURRENT_TIMESTAMP', + 'table_name' => 'civicrm_subscription_history', + 'entity' => 'SubscriptionHistory', + 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', + 'localizable' => 0, + ], + '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, - 'html' => array( + 'table_name' => 'civicrm_subscription_history', + 'entity' => 'SubscriptionHistory', + 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', + 'localizable' => 0, + '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, - 'pseudoconstant' => array( + 'table_name' => 'civicrm_subscription_history', + 'entity' => 'SubscriptionHistory', + 'bao' => 'CRM_Contact_BAO_SubscriptionHistory', + 'localizable' => 0, + '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, - ) , - ); + '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 * @@ -232,10 +252,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 * @@ -243,8 +264,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 = []; + 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 1c04b66e516b..f275cfa377f4 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); @@ -226,7 +229,7 @@ public function preProcess() { if ($defaults['is_deceased']) { $displayName .= ' (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); @@ -374,7 +377,7 @@ public function preProcess() { $this->assign('paramSubType', $paramSubType); } - if (CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject)) { + if (CRM_Utils_Request::retrieve('type', 'String')) { CRM_Contact_Form_Edit_CustomData::preProcess($this); } else { @@ -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); } @@ -440,13 +443,7 @@ public function setDefaultValues() { CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this); if (!empty($defaults['image_URL'])) { - list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String::unstupifyUrl($defaults['image_URL'])); - list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight); - $this->assign('imageWidth', $imageWidth); - $this->assign('imageHeight', $imageHeight); - $this->assign('imageThumbWidth', $imageThumbWidth); - $this->assign('imageThumbHeight', $imageThumbHeight); - $this->assign('imageURL', $defaults['image_URL']); + $this->assign("imageURL", CRM_Utils_File::getImageURL($defaults['image_URL'])); } //set location type and country to default for each block @@ -567,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); } } @@ -592,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. @@ -621,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) { @@ -635,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; } @@ -644,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]); } } @@ -663,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] ); } } @@ -684,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']]); } } } @@ -699,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']); @@ -714,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; } @@ -734,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', @@ -760,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)) { @@ -767,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 ) @@ -800,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', @@ -816,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, @@ -859,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)) { @@ -868,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); } @@ -887,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) { @@ -902,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); } @@ -918,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']; @@ -945,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)) { @@ -968,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) { @@ -987,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 @@ -998,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); @@ -1017,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) ) { @@ -1046,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; @@ -1083,7 +1105,7 @@ public static function blockDataExists(&$fields) { return FALSE; } - static $skipFields = array( + static $skipFields = [ 'location_type_id', 'is_primary', 'phone_type_id', @@ -1091,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) { @@ -1136,28 +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'])) { - $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $contactType); - $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $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'"; + $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); // 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,16 +243,14 @@ 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 @@ -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); } } } - $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"; - - if ($this->_debug > 0) { - print "-- Include groups query:
"; - print "$sql;"; - print ""; - } + group_names varchar(64)'); - 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,13 +300,7 @@ public function from() { //used only when exclude group is selected if ($xGroups != 0) { - $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null"; - } - - if ($this->_debug > 0) { - print "-- Include groups query:
"; - print "$includeGroup;"; - print ""; + $includeGroup .= " AND {$this->_xgTable}.contact_id IS null"; } CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray); @@ -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} + $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"; + WHERE {$this->_igTable}.contact_id IS NOT NULL + AND {$this->_igTable}.group_names IS NULL"; CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray); - if ($this->_debug > 0) { - print "-- Smart group query:
"; - print "$insertGroupNameQuery;"; - print ""; - } } } } @@ -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; @@ -437,13 +403,13 @@ public function count() { public function __destruct() { //drop the temp. tables if they exist - if (!empty($this->_includeGroups)) { - $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}"; + if ($this->_igTable && !empty($this->_includeGroups)) { + $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_igTable}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); } - if (!empty($this->_excludeGroups)) { - $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}"; + if ($this->_xgTable && !empty($this->_excludeGroups)) { + $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_xgTable}"; CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); } } @@ -455,4 +421,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 e2bb5aa3b76d..441688dab657 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);
+ 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);
}
- $message = implode($newLineOperators['p']['oper'], $htmlMsg);
+ return Civi::$statics[__CLASS__]['token_categories'];
}
}
diff --git a/CRM/Contact/Form/Task/PickProfile.php b/CRM/Contact/Form/Task/PickProfile.php
index 63b1d88de22a..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 8882d123a9d2..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 5bb7418e7401..6f632cb9de6e 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,13 +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
+ if (!CRM_Utils_Array::value('prox_postal_code', $fields) and
!CRM_Utils_Array::value('prox_city', $fields)
) {
$errors["prox_distance"] = ts("City OR Postal Code are required to search by distance.");
@@ -125,8 +125,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 72b41e51382e..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
'; @@ -415,13 +424,13 @@ public static function handleUnhandledException($exception) { CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other)); } $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 @@ -526,29 +535,23 @@ public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, * in the formatting of the output. * * @param string $variable_name + * Variable name. * @param mixed $variable + * Variable value. * @param bool $print - * Should we use print_r ? (else we use var_dump). + * Use print_r (if true) or var_dump (if false). * @param bool $log - * Should we log or return the output. - * @param string $comp - * Variable name. + * Log or return the output? + * @param string $prefix + * Prefix for output logfile. * * @return string - * the generated output - * - * + * The generated output * * @see CRM_Core_Error::debug() * @see CRM_Core_Error::debug_log_message() */ - public static function debug_var( - $variable_name, - $variable, - $print = TRUE, - $log = TRUE, - $comp = '' - ) { + public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '') { // check if variable is set if (!isset($variable)) { $out = "\$$variable_name is not set"; @@ -571,7 +574,7 @@ public static function debug_var( reset($variable); } } - return self::debug_log_message($out, FALSE, $comp); + return self::debug_log_message($out, FALSE, $prefix); } /** @@ -584,17 +587,17 @@ public static function debug_var( * @param bool $out * Should we log or return the output. * - * @param string $comp - * Message to be output. + * @param string $prefix + * Message prefix. * @param string $priority * * @return string * Format of the backtrace */ - public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) { + public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) { $config = CRM_Core_Config::singleton(); - $file_log = self::createDebugLogger($comp); + $file_log = self::createDebugLogger($prefix); $file_log->log("$message\n", $priority); $str = '' . htmlspecialchars($message) . '
';
@@ -603,10 +606,18 @@ public static function debug_log_message($message, $out = FALSE, $comp = '', $pr
}
$file_log->close();
- if (!empty($config->userFrameworkLogging)) {
+ if (!isset(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) {
+ // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
+ // $config->userFrameworkLogging can trigger DB queries & under log mode this
+ // then gets called again.
+ \Civi::$statics[__CLASS__]['userFrameworkLogging'] = FALSE;
+ \Civi::$statics[__CLASS__]['userFrameworkLogging'] = $config->userFrameworkLogging;
+ }
+
+ 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], WATCHDOG_DEBUG);
}
}
@@ -636,7 +647,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]);
}
/**
@@ -653,16 +664,21 @@ public static function createDebugLogger($prefix = '') {
/**
* Generate a hash for the logfile.
+ *
* CRM-13640.
+ *
+ * @param CRM_Core_Config $config
+ *
+ * @return string
*/
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);
@@ -671,7 +687,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
*/
@@ -684,9 +701,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);
@@ -753,9 +770,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']) : '';
@@ -832,13 +849,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 dd28a34b97cc..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
@@ -78,41 +109,12 @@ public function __construct($locale) {
// Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
$this->_nativegettext = TRUE;
-
- $locale .= '.utf8';
- putenv("LANG=$locale");
-
- // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
- setlocale(LC_TIME, $locale);
- setlocale(LC_MESSAGES, $locale);
- setlocale(LC_CTYPE, $locale);
-
- bindtextdomain('civicrm', CRM_Core_I18n::getResourceDir());
- bind_textdomain_codeset('civicrm', 'UTF-8');
- textdomain('civicrm');
-
- $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
- $this->_extensioncache['civicrm'] = 'civicrm';
+ $this->setNativeGettextLocale($locale);
return;
}
// Otherwise, use PHP-gettext
- // we support both the old file hierarchy format and the new:
- // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
- // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
- require_once 'PHPgettext/streams.php';
- require_once 'PHPgettext/gettext.php';
-
- $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
-
- if (!file_exists($mo_file)) {
- // fallback to pre-4.5 mode
- $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
- }
-
- $streamer = new FileReader($mo_file);
- $this->_phpgettext = new gettext_reader($streamer);
- $this->_extensioncache['civicrm'] = $this->_phpgettext;
+ $this->setPhpGettextLocale($locale);
}
}
@@ -126,6 +128,56 @@ public function isNative() {
return $this->_nativegettext;
}
+ /**
+ * Set native locale for getText.
+ *
+ * @param string $locale
+ */
+ protected function setNativeGettextLocale($locale) {
+
+ $locale .= '.utf8';
+ putenv("LANG=$locale");
+
+ // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
+ setlocale(LC_TIME, $locale);
+ setlocale(LC_MESSAGES, $locale);
+ setlocale(LC_CTYPE, $locale);
+
+ bindtextdomain('civicrm', CRM_Core_I18n::getResourceDir());
+ bind_textdomain_codeset('civicrm', 'UTF-8');
+ textdomain('civicrm');
+
+ $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
+ $this->_extensioncache['civicrm'] = 'civicrm';
+
+ }
+
+ /**
+ * Set getText locale.
+ *
+ * @param string $locale
+ */
+ protected function setPhpGettextLocale($locale) {
+
+ // we support both the old file hierarchy format and the new:
+ // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
+ // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
+ require_once 'PHPgettext/streams.php';
+ require_once 'PHPgettext/gettext.php';
+
+ $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
+
+ if (!file_exists($mo_file)) {
+ // fallback to pre-4.5 mode
+ $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
+ }
+
+ $streamer = new FileReader($mo_file);
+ $this->_phpgettext = new gettext_reader($streamer);
+ $this->_extensioncache['civicrm'] = $this->_phpgettext;
+
+ }
+
/**
* Return languages available in this instance of CiviCRM.
*
@@ -142,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];
}
}
}
@@ -165,11 +225,13 @@ public static function languages($justEnabled = FALSE) {
unset($all[$code]);
}
}
+
+ asort($all);
}
if ($enabled === NULL) {
$config = CRM_Core_Config::singleton();
- $enabled = array();
+ $enabled = [];
if (isset($config->languageLimit) and $config->languageLimit) {
foreach ($all as $code => $name) {
if (in_array($code, array_keys($config->languageLimit))) {
@@ -182,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.
*
@@ -192,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);
@@ -208,6 +292,11 @@ public function strarg($str) {
return strtr($str, $tr);
}
+ /**
+ * Get the directory for l10n resources.
+ *
+ * @return string
+ */
public static function getResourceDir() {
static $dir = NULL;
if ($dir === NULL) {
@@ -241,7 +330,7 @@ public static function getResourceDir() {
* @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']);
@@ -253,7 +342,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,7 +404,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)
@@ -355,7 +444,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];
@@ -397,7 +486,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
}
@@ -441,7 +530,7 @@ public function translate($string) {
*/
public function localizeArray(
&$array,
- $params = array()
+ $params = []
) {
$tsLocale = CRM_Core_I18n::getLocale();
@@ -469,7 +558,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']);
}
}
}
@@ -531,7 +620,6 @@ public function setGettextDomain($key) {
return FALSE;
}
-
/**
* Is the CiviCRM in multilingual mode.
*
@@ -563,50 +651,34 @@ public static function isLanguageRTL($language) {
/**
* Change the processing language without changing the current user language
*
- * @param $language
- * Language (for example 'en_US', or 'fr_CA').
+ * @param $locale
+ * Locale (for example 'en_US', or 'fr_CA').
* True if the domain was changed for an extension.
*/
- public function setLocale($language) {
-
- $config = CRM_Core_Config::singleton();
+ public function setLocale($locale) {
// Change the language of the CMS as well, for URLs.
- CRM_Utils_System::setUFLocale($language);
+ CRM_Utils_System::setUFLocale($locale);
// change the gettext ressources
if ($this->_nativegettext) {
- $locale = $language . '.utf8';
- putenv("LANG=$locale");
-
- setlocale(LC_TIME, $locale);
- setlocale(LC_MESSAGES, $locale);
- setlocale(LC_CTYPE, $locale);
-
- bindtextdomain('civicrm', $config->gettextResourceDir);
- bind_textdomain_codeset('civicrm', 'UTF-8');
- textdomain('civicrm');
-
- $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
- $this->_extensioncache['civicrm'] = 'civicrm';
+ $this->setNativeGettextLocale($locale);
}
else {
// phpgettext
- require_once 'PHPgettext/streams.php';
- require_once 'PHPgettext/gettext.php';
-
- $mo_file = $config->gettextResourceDir . $language . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
-
- $streamer = new FileReader($mo_file);
- $this->_phpgettext = new gettext_reader($streamer);
- $this->_extensioncache['civicrm'] = $this->_phpgettext;
-
+ $this->setPhpGettextLocale($locale);
}
- // for sql queries
+ // For sql queries, if running in DB multi-lingual mode.
global $dbLocale;
- $dbLocale = "_{$language}";
+ if ($dbLocale) {
+ $dbLocale = "_{$locale}";
+ }
+
+ // For self::getLocale()
+ global $tsLocale;
+ $tsLocale = $locale;
}
/**
@@ -615,14 +687,15 @@ public function setLocale($language) {
* @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];
}
/**
@@ -632,7 +705,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])) {
@@ -659,10 +732,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();
@@ -678,7 +751,7 @@ public static function getContactDefaultLanguage() {
*/
public static function getLocale() {
global $tsLocale;
- return $tsLocale;
+ return $tsLocale ? $tsLocale : 'en_US';
}
}
@@ -694,9 +767,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 $areSettingsAvailable = FALSE;
+ static $lastLocale = NULL;
static $i18n = NULL;
static $function = NULL;
@@ -704,17 +777,21 @@ function ts($text, $params = array()) {
return '';
}
- if (!$config) {
- $config = CRM_Core_Config::singleton();
+ // When the settings become available, lookup customTranslateFunction.
+ if (!$areSettingsAvailable) {
+ $areSettingsAvailable = (bool) \Civi\Core\Container::getBootService('settings_manager');
+ if ($areSettingsAvailable) {
+ $config = CRM_Core_Config::singleton();
+ if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
+ $function = $config->customTranslateFunction;
+ }
+ }
}
- $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 f2fa0a5838ee..bc8b776af1fa 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'];
}
@@ -123,12 +124,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 c80b244cac04..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 c51bcb07fe13..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])) {
foreach ($indices[$table] as $index) {
- $queries[] = "DROP INDEX {$index['name']} ON {$table}";
+ if (CRM_Core_BAO_SchemaHandler::checkIfIndexExists($table, $index['name'])) {
+ $queries[] = "DROP INDEX {$index['name']} ON {$table}";
+ }
}
}
// deal with columns
foreach ($hash as $column => $type) {
$queries[] = "ALTER TABLE {$table} ADD {$column}_{$locale} {$type}";
- $queries[] = "UPDATE {$table} SET {$column}_{$locale} = {$column}";
- $queries[] = "ALTER TABLE {$table} DROP {$column}";
+ if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists($table, $column)) {
+ $queries[] = "UPDATE {$table} SET {$column}_{$locale} = {$column}";
+ $queries[] = "ALTER TABLE {$table} DROP {$column}";
+ }
}
// add view
@@ -103,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);
}
/**
@@ -160,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);
@@ -173,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) {
@@ -184,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
@@ -251,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}";
@@ -291,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";
@@ -303,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)) {
@@ -333,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);
}
}
@@ -361,7 +372,10 @@ public static function rewriteQuery($query) {
global $dbLocale;
$tables = self::schemaStructureTables();
foreach ($tables as $table) {
- $query = preg_replace("/([^'\"])({$table})([^_'\"])/", "\\1\\2{$dbLocale}\\3", $query);
+ // CRM-19093
+ // should match the civicrm table name such as: civicrm_event
+ // but must not match the table name if it's a substring of another table: civicrm_events_in_cart
+ $query = preg_replace("/([^'\"])({$table})(\z|[^a-z_'\"])/", "\\1\\2{$dbLocale}\\3", $query);
}
// uncomment the below to rewrite the civicrm_value_* queries
// $query = preg_replace("/(civicrm_value_[a-z0-9_]+_\d+)([^_])/", "\\1{$dbLocale}\\2", $query);
@@ -403,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]);
}
@@ -437,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) {
@@ -474,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
@@ -489,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}";
}
@@ -538,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";
@@ -547,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;
}
@@ -560,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) {
@@ -578,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;
}
@@ -591,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..e2468d6e6af7
--- /dev/null
+++ b/CRM/Core/I18n/SchemaStructure.php
@@ -0,0 +1,722 @@
+ [
+ 'display_name' => "varchar(64)",
+ ],
+ 'civicrm_option_group' => [
+ 'title' => "varchar(255)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => "varchar(64)",
+ 'label_b_a' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => "varchar(64)",
+ 'description' => "text",
+ ],
+ 'civicrm_batch' => [
+ 'title' => "varchar(255)",
+ 'description' => "text",
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => "varchar(255)",
+ 'premiums_intro_text' => "text",
+ 'premiums_nothankyou_label' => "varchar(255)",
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => "varchar(128)",
+ ],
+ 'civicrm_survey' => [
+ 'title' => "varchar(255)",
+ 'instructions' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_case_type' => [
+ 'title' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => "varchar(255)",
+ 'intro' => "text",
+ 'suggested_message' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_option_value' => [
+ 'label' => "varchar(512)",
+ 'description' => "text",
+ ],
+ 'civicrm_group' => [
+ 'title' => "varchar(64)",
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => "varchar(255)",
+ 'intro_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer' => "text",
+ 'receipt_from_name' => "varchar(255)",
+ 'receipt_text' => "text",
+ 'footer_text' => "text",
+ ],
+ 'civicrm_product' => [
+ 'name' => "varchar(255)",
+ 'description' => "text",
+ 'options' => "text",
+ ],
+ 'civicrm_payment_processor' => [
+ 'title' => "varchar(127)",
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => "varchar(128)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => "varchar(255)",
+ 'new_text' => "text",
+ 'renewal_title' => "varchar(255)",
+ 'renewal_text' => "text",
+ ],
+ 'civicrm_price_set' => [
+ 'title' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => "varchar(64)",
+ 'frontend_title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ 'cancel_button_text' => "varchar(64)",
+ 'submit_button_text' => "varchar(64)",
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => "text",
+ 'help_pre' => "text",
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_price_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => "varchar(255)",
+ 'description' => "text",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => "varchar(255)",
+ ],
+ 'civicrm_event' => [
+ 'title' => "varchar(255)",
+ 'summary' => "text",
+ 'description' => "text",
+ 'registration_link_text' => "varchar(255)",
+ 'event_full_text' => "text",
+ 'fee_label' => "varchar(255)",
+ 'intro_text' => "text",
+ 'footer_text' => "text",
+ 'confirm_title' => "varchar(255)",
+ 'confirm_text' => "text",
+ 'confirm_footer_text' => "text",
+ 'confirm_email_text' => "text",
+ 'confirm_from_name' => "varchar(255)",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'waitlist_text' => "text",
+ 'approval_req_text' => "text",
+ 'template_title' => "varchar(255)",
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get a table indexed array of the indices for translatable fields.
+ *
+ * @return array
+ * Indices for translatable fields.
+ */
+ public static function &indices() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
+ 'name' => 'UI_title_extends',
+ 'field' => [
+ 'title',
+ 'extends',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
+ 'name' => 'UI_label_custom_group_id',
+ 'field' => [
+ 'label',
+ 'custom_group_id',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
+ 'name' => 'UI_title',
+ 'field' => [
+ 'title',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get tables with translatable fields.
+ *
+ * @return array
+ * Array of names of tables with fields that can be translated.
+ */
+ public static function &tables() {
+ static $result = NULL;
+ if (!$result) {
+ $result = array_keys(self::columns());
+ }
+ return $result;
+ }
+
+ /**
+ * Get a list of widgets for editing translatable fields.
+ *
+ * @return array
+ * Array of the widgets for editing translatable fields.
+ */
+ public static function &widgets() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_location_type' => [
+ 'display_name' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => [
+ 'type' => "Text",
+ ],
+ 'label_b_a' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_batch' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => [
+ 'type' => "Text",
+ ],
+ 'premiums_intro_text' => [
+ 'type' => "Text",
+ ],
+ 'premiums_nothankyou_label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_survey' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'instructions' => [
+ 'type' => "TextArea",
+ 'rows' => "20",
+ 'cols' => "80",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_case_type' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro' => [
+ 'type' => "Text",
+ ],
+ 'suggested_message' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_value' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'thankyou_footer' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'receipt_from_name' => [
+ 'type' => "Text",
+ ],
+ 'receipt_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ ],
+ 'civicrm_product' => [
+ 'name' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ 'options' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_payment_processor' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => [
+ 'type' => "Text",
+ 'label' => "Name",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ 'label' => "Description",
+ ],
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => [
+ 'type' => "Text",
+ ],
+ 'new_text' => [
+ 'type' => "Text",
+ ],
+ 'renewal_title' => [
+ 'type' => "Text",
+ ],
+ 'renewal_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_price_set' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'frontend_title' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'cancel_button_text' => [
+ 'type' => "Text",
+ ],
+ 'submit_button_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ ],
+ 'civicrm_price_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_event' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'summary' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'registration_link_text' => [
+ 'type' => "Text",
+ ],
+ 'event_full_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'fee_label' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_title' => [
+ 'type' => "Text",
+ ],
+ 'confirm_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_email_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "50",
+ ],
+ 'confirm_from_name' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'thankyou_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'waitlist_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'approval_req_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'template_title' => [
+ 'type' => "Text",
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+}
diff --git a/CRM/Core/I18n/SchemaStructure_2_2_0.php b/CRM/Core/I18n/SchemaStructure_2_2_0.php
deleted file mode 100644
index 5213e2c3cff0..000000000000
--- a/CRM/Core/I18n/SchemaStructure_2_2_0.php
+++ /dev/null
@@ -1,69 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'name' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array $result
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_0_beta1.php b/CRM/Core/I18n/SchemaStructure_3_0_beta1.php
deleted file mode 100644
index ae6cafe86d70..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_0_beta1.php
+++ /dev/null
@@ -1,267 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'name' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_0_beta4.php b/CRM/Core/I18n/SchemaStructure_3_0_beta4.php
deleted file mode 100644
index bed38ed66d8e..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_0_beta4.php
+++ /dev/null
@@ -1,280 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_mailing_component' => array(
- 'name' => 'varchar(64)',
- 'subject' => 'varchar(255)',
- 'body_html' => 'text',
- 'body_text' => 'text',
- ),
- 'civicrm_mailing' => array(
- 'name' => 'varchar(128)',
- 'from_name' => 'varchar(128)',
- 'subject' => 'varchar(128)',
- 'body_text' => 'longtext',
- 'body_html' => 'longtext',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'name' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php b/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php
deleted file mode 100644
index e88e501330c3..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php
+++ /dev/null
@@ -1,284 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_contact_type' => array(
- 'label' => 'varchar(64)',
- 'description' => 'text',
- ),
- 'civicrm_mailing_component' => array(
- 'name' => 'varchar(64)',
- 'subject' => 'varchar(255)',
- 'body_html' => 'text',
- 'body_text' => 'text',
- ),
- 'civicrm_mailing' => array(
- 'name' => 'varchar(128)',
- 'from_name' => 'varchar(128)',
- 'subject' => 'varchar(128)',
- 'body_text' => 'longtext',
- 'body_html' => 'longtext',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'name' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_1_beta2.php b/CRM/Core/I18n/SchemaStructure_3_1_beta2.php
deleted file mode 100644
index 87afed611e3d..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_1_beta2.php
+++ /dev/null
@@ -1,287 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_contact_type' => array(
- 'label' => 'varchar(64)',
- 'description' => 'text',
- ),
- 'civicrm_mailing_component' => array(
- 'name' => 'varchar(64)',
- 'subject' => 'varchar(255)',
- 'body_html' => 'text',
- 'body_text' => 'text',
- ),
- 'civicrm_mailing' => array(
- 'name' => 'varchar(128)',
- 'from_name' => 'varchar(128)',
- 'subject' => 'varchar(128)',
- 'body_text' => 'longtext',
- 'body_html' => 'longtext',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'name' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_dashboard' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_2_beta4.php b/CRM/Core/I18n/SchemaStructure_3_2_beta4.php
deleted file mode 100644
index b5a21d9a798a..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_2_beta4.php
+++ /dev/null
@@ -1,288 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_contact_type' => array(
- 'label' => 'varchar(64)',
- 'description' => 'text',
- ),
- 'civicrm_mailing_component' => array(
- 'name' => 'varchar(64)',
- 'subject' => 'varchar(255)',
- 'body_html' => 'text',
- 'body_text' => 'text',
- ),
- 'civicrm_mailing' => array(
- 'name' => 'varchar(128)',
- 'from_name' => 'varchar(128)',
- 'subject' => 'varchar(128)',
- 'body_text' => 'longtext',
- 'body_html' => 'longtext',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'label' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_dashboard' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'help_pre' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_3_beta1.php b/CRM/Core/I18n/SchemaStructure_3_3_beta1.php
deleted file mode 100644
index e3a3d14bcd10..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_3_beta1.php
+++ /dev/null
@@ -1,296 +0,0 @@
- array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contact' => array(
- 'sort_name' => 'varchar(128)',
- 'display_name' => 'varchar(128)',
- 'first_name' => 'varchar(64)',
- 'middle_name' => 'varchar(64)',
- 'last_name' => 'varchar(64)',
- 'email_greeting_display' => 'varchar(255)',
- 'postal_greeting_display' => 'varchar(255)',
- 'addressee_display' => 'varchar(255)',
- 'household_name' => 'varchar(128)',
- 'organization_name' => 'varchar(128)',
- ),
- 'civicrm_contact_type' => array(
- 'label' => 'varchar(64)',
- 'description' => 'text',
- ),
- 'civicrm_mailing_component' => array(
- 'name' => 'varchar(64)',
- 'subject' => 'varchar(255)',
- 'body_html' => 'text',
- 'body_text' => 'text',
- ),
- 'civicrm_mailing' => array(
- 'name' => 'varchar(128)',
- 'from_name' => 'varchar(128)',
- 'subject' => 'varchar(128)',
- 'body_text' => 'longtext',
- 'body_html' => 'longtext',
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => 'varchar(255)',
- 'premiums_intro_text' => 'text',
- ),
- 'civicrm_product' => array(
- 'name' => 'varchar(255)',
- 'description' => 'text',
- 'options' => 'text',
- ),
- 'civicrm_membership_type' => array(
- 'name' => 'varchar(128)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_membership_status' => array(
- 'label' => 'varchar(128)',
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_tell_friend' => array(
- 'title' => 'varchar(255)',
- 'intro' => 'text',
- 'suggested_message' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- ),
- 'civicrm_price_set' => array(
- 'title' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_batch' => array(
- 'label' => 'varchar(64)',
- 'description' => 'text',
- ),
- 'civicrm_custom_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_custom_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_dashboard' => array(
- 'label' => 'varchar(255)',
- ),
- 'civicrm_option_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'varchar(255)',
- ),
- 'civicrm_contribution_page' => array(
- 'title' => 'varchar(255)',
- 'intro_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer' => 'text',
- 'for_organization' => 'text',
- 'receipt_from_name' => 'varchar(255)',
- 'receipt_text' => 'text',
- 'footer_text' => 'text',
- 'honor_block_title' => 'varchar(255)',
- 'honor_block_text' => 'text',
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => 'varchar(255)',
- 'new_text' => 'text',
- 'renewal_title' => 'varchar(255)',
- 'renewal_text' => 'text',
- ),
- 'civicrm_price_field' => array(
- 'label' => 'varchar(255)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_group' => array(
- 'title' => 'varchar(64)',
- 'help_pre' => 'text',
- 'help_post' => 'text',
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => 'text',
- 'help_pre' => 'text',
- 'label' => 'varchar(255)',
- ),
- 'civicrm_address' => array(
- 'street_address' => 'varchar(96)',
- 'supplemental_address_1' => 'varchar(96)',
- 'supplemental_address_2' => 'varchar(96)',
- 'supplemental_address_3' => 'varchar(96)',
- 'city' => 'varchar(64)',
- 'name' => 'varchar(255)',
- ),
- 'civicrm_event' => array(
- 'title' => 'varchar(255)',
- 'summary' => 'text',
- 'description' => 'text',
- 'registration_link_text' => 'varchar(255)',
- 'event_full_text' => 'text',
- 'fee_label' => 'varchar(255)',
- 'intro_text' => 'text',
- 'footer_text' => 'text',
- 'confirm_title' => 'varchar(255)',
- 'confirm_text' => 'text',
- 'confirm_footer_text' => 'text',
- 'confirm_email_text' => 'text',
- 'confirm_from_name' => 'varchar(255)',
- 'thankyou_title' => 'varchar(255)',
- 'thankyou_text' => 'text',
- 'thankyou_footer_text' => 'text',
- 'pay_later_text' => 'text',
- 'pay_later_receipt' => 'text',
- 'waitlist_text' => 'text',
- 'approval_req_text' => 'text',
- 'template_title' => 'varchar(255)',
- ),
- 'civicrm_price_field_value' => array(
- 'label' => 'varchar(255)',
- 'description' => 'text',
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- static public function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- static public function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_4_0.php b/CRM/Core/I18n/SchemaStructure_3_4_0.php
deleted file mode 100644
index e301b46cbffa..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_4_0.php
+++ /dev/null
@@ -1,223 +0,0 @@
- array(
- 'label' => "varchar(255)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => "varchar(255)",
- 'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
- 'name' => "varchar(255)",
- 'description' => "text",
- 'options' => "text",
- ),
- 'civicrm_membership_type' => array(
- 'name' => "varchar(128)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
- 'label' => "varchar(128)",
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
- 'title' => "varchar(255)",
- 'intro' => "text",
- 'suggested_message' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
- 'title' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_batch' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_custom_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_contribution_page' => array(
- 'title' => "varchar(255)",
- 'intro_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer' => "text",
- 'for_organization' => "text",
- 'receipt_from_name' => "varchar(255)",
- 'receipt_text' => "text",
- 'footer_text' => "text",
- 'honor_block_title' => "varchar(255)",
- 'honor_block_text' => "text",
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => "varchar(255)",
- 'new_text' => "text",
- 'renewal_title' => "varchar(255)",
- 'renewal_text' => "text",
- ),
- 'civicrm_price_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_uf_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => "text",
- 'help_pre' => "text",
- 'label' => "varchar(255)",
- ),
- 'civicrm_event' => array(
- 'title' => "varchar(255)",
- 'summary' => "text",
- 'description' => "text",
- 'registration_link_text' => "varchar(255)",
- 'event_full_text' => "text",
- 'fee_label' => "varchar(255)",
- 'intro_text' => "text",
- 'footer_text' => "text",
- 'confirm_title' => "varchar(255)",
- 'confirm_text' => "text",
- 'confirm_footer_text' => "text",
- 'confirm_email_text' => "text",
- 'confirm_from_name' => "varchar(255)",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'waitlist_text' => "text",
- 'approval_req_text' => "text",
- 'template_title' => "varchar(255)",
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_4_beta2.php b/CRM/Core/I18n/SchemaStructure_3_4_beta2.php
deleted file mode 100644
index c86c184ba34c..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_4_beta2.php
+++ /dev/null
@@ -1,296 +0,0 @@
- array(
- 'label' => "varchar(255)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_contact' => array(
- 'sort_name' => "varchar(128)",
- 'display_name' => "varchar(128)",
- 'first_name' => "varchar(64)",
- 'middle_name' => "varchar(64)",
- 'last_name' => "varchar(64)",
- 'email_greeting_display' => "varchar(255)",
- 'postal_greeting_display' => "varchar(255)",
- 'addressee_display' => "varchar(255)",
- 'household_name' => "varchar(128)",
- 'organization_name' => "varchar(128)",
- ),
- 'civicrm_contact_type' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_mailing_component' => array(
- 'name' => "varchar(64)",
- 'subject' => "varchar(255)",
- 'body_html' => "text",
- 'body_text' => "text",
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => "varchar(255)",
- 'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
- 'name' => "varchar(255)",
- 'description' => "text",
- 'options' => "text",
- ),
- 'civicrm_membership_type' => array(
- 'name' => "varchar(128)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
- 'label' => "varchar(128)",
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
- 'title' => "varchar(255)",
- 'intro' => "text",
- 'suggested_message' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
- 'title' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_batch' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_custom_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_mailing' => array(
- 'name' => "varchar(128)",
- 'from_name' => "varchar(128)",
- 'subject' => "varchar(128)",
- 'body_text' => "longtext",
- 'body_html' => "longtext",
- ),
- 'civicrm_contribution_page' => array(
- 'title' => "varchar(255)",
- 'intro_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer' => "text",
- 'for_organization' => "text",
- 'receipt_from_name' => "varchar(255)",
- 'receipt_text' => "text",
- 'footer_text' => "text",
- 'honor_block_title' => "varchar(255)",
- 'honor_block_text' => "text",
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => "varchar(255)",
- 'new_text' => "text",
- 'renewal_title' => "varchar(255)",
- 'renewal_text' => "text",
- ),
- 'civicrm_price_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_uf_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => "text",
- 'help_pre' => "text",
- 'label' => "varchar(255)",
- ),
- 'civicrm_address' => array(
- 'street_address' => "varchar(96)",
- 'supplemental_address_1' => "varchar(96)",
- 'supplemental_address_2' => "varchar(96)",
- 'supplemental_address_3' => "varchar(96)",
- 'city' => "varchar(64)",
- 'name' => "varchar(255)",
- ),
- 'civicrm_event' => array(
- 'title' => "varchar(255)",
- 'summary' => "text",
- 'description' => "text",
- 'registration_link_text' => "varchar(255)",
- 'event_full_text' => "text",
- 'fee_label' => "varchar(255)",
- 'intro_text' => "text",
- 'footer_text' => "text",
- 'confirm_title' => "varchar(255)",
- 'confirm_text' => "text",
- 'confirm_footer_text' => "text",
- 'confirm_email_text' => "text",
- 'confirm_from_name' => "varchar(255)",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'waitlist_text' => "text",
- 'approval_req_text' => "text",
- 'template_title' => "varchar(255)",
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_contact' => array(
- 'index_sort_name' => array(
- 'name' => 'index_sort_name',
- 'field' => array(
- 'sort_name',
- ),
- ),
- 'index_first_name' => array(
- 'name' => 'index_first_name',
- 'field' => array(
- 'first_name',
- ),
- ),
- 'index_last_name' => array(
- 'name' => 'index_last_name',
- 'field' => array(
- 'last_name',
- ),
- ),
- 'index_household_name' => array(
- 'name' => 'index_household_name',
- 'field' => array(
- 'household_name',
- ),
- ),
- 'index_organization_name' => array(
- 'name' => 'index_organization_name',
- 'field' => array(
- 'organization_name',
- ),
- ),
- ),
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_address' => array(
- 'index_city' => array(
- 'name' => 'index_city',
- 'field' => array(
- 'city',
- ),
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_3_4_beta3.php b/CRM/Core/I18n/SchemaStructure_3_4_beta3.php
deleted file mode 100644
index 23dc69bc3c3d..000000000000
--- a/CRM/Core/I18n/SchemaStructure_3_4_beta3.php
+++ /dev/null
@@ -1,223 +0,0 @@
- array(
- 'label' => "varchar(255)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => "varchar(255)",
- 'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
- 'name' => "varchar(255)",
- 'description' => "text",
- 'options' => "text",
- ),
- 'civicrm_membership_type' => array(
- 'name' => "varchar(128)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
- 'label' => "varchar(128)",
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
- 'title' => "varchar(255)",
- 'intro' => "text",
- 'suggested_message' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
- 'title' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_batch' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_custom_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_contribution_page' => array(
- 'title' => "varchar(255)",
- 'intro_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer' => "text",
- 'for_organization' => "text",
- 'receipt_from_name' => "varchar(255)",
- 'receipt_text' => "text",
- 'footer_text' => "text",
- 'honor_block_title' => "varchar(255)",
- 'honor_block_text' => "text",
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => "varchar(255)",
- 'new_text' => "text",
- 'renewal_title' => "varchar(255)",
- 'renewal_text' => "text",
- ),
- 'civicrm_price_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_uf_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => "text",
- 'help_pre' => "text",
- 'label' => "varchar(255)",
- ),
- 'civicrm_event' => array(
- 'title' => "varchar(255)",
- 'summary' => "text",
- 'description' => "text",
- 'registration_link_text' => "varchar(255)",
- 'event_full_text' => "text",
- 'fee_label' => "varchar(255)",
- 'intro_text' => "text",
- 'footer_text' => "text",
- 'confirm_title' => "varchar(255)",
- 'confirm_text' => "text",
- 'confirm_footer_text' => "text",
- 'confirm_email_text' => "text",
- 'confirm_from_name' => "varchar(255)",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'waitlist_text' => "text",
- 'approval_req_text' => "text",
- 'template_title' => "varchar(255)",
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_4_1_0.php b/CRM/Core/I18n/SchemaStructure_4_1_0.php
deleted file mode 100644
index b92715099e6f..000000000000
--- a/CRM/Core/I18n/SchemaStructure_4_1_0.php
+++ /dev/null
@@ -1,229 +0,0 @@
- array(
- 'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
- 'title' => "varchar(255)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => "varchar(255)",
- 'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
- 'name' => "varchar(255)",
- 'description' => "text",
- 'options' => "text",
- ),
- 'civicrm_membership_status' => array(
- 'label' => "varchar(128)",
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
- 'title' => "varchar(255)",
- 'intro' => "text",
- 'suggested_message' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
- 'title' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_batch' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_custom_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_contribution_page' => array(
- 'title' => "varchar(255)",
- 'intro_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer' => "text",
- 'for_organization' => "text",
- 'receipt_from_name' => "varchar(255)",
- 'receipt_text' => "text",
- 'footer_text' => "text",
- 'honor_block_title' => "varchar(255)",
- 'honor_block_text' => "text",
- ),
- 'civicrm_price_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => "text",
- 'help_pre' => "text",
- 'label' => "varchar(255)",
- ),
- 'civicrm_membership_type' => array(
- 'name' => "varchar(128)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => "varchar(255)",
- 'new_text' => "text",
- 'renewal_title' => "varchar(255)",
- 'renewal_text' => "text",
- ),
- 'civicrm_price_field_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
- 'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
- 'title' => "varchar(255)",
- 'summary' => "text",
- 'description' => "text",
- 'registration_link_text' => "varchar(255)",
- 'event_full_text' => "text",
- 'fee_label' => "varchar(255)",
- 'intro_text' => "text",
- 'footer_text' => "text",
- 'confirm_title' => "varchar(255)",
- 'confirm_text' => "text",
- 'confirm_footer_text' => "text",
- 'confirm_email_text' => "text",
- 'confirm_from_name' => "varchar(255)",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'waitlist_text' => "text",
- 'approval_req_text' => "text",
- 'template_title' => "varchar(255)",
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php b/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php
deleted file mode 100644
index 6d311e0e013c..000000000000
--- a/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php
+++ /dev/null
@@ -1,226 +0,0 @@
- array(
- 'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
- 'title' => "varchar(255)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_premiums' => array(
- 'premiums_intro_title' => "varchar(255)",
- 'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
- 'name' => "varchar(255)",
- 'description' => "text",
- 'options' => "text",
- ),
- 'civicrm_membership_status' => array(
- 'label' => "varchar(128)",
- ),
- 'civicrm_participant_status_type' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
- 'title' => "varchar(255)",
- 'intro' => "text",
- 'suggested_message' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
- 'title' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_batch' => array(
- 'label' => "varchar(64)",
- 'description' => "text",
- ),
- 'civicrm_custom_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
- 'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_contribution_page' => array(
- 'title' => "varchar(255)",
- 'intro_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer' => "text",
- 'for_organization' => "text",
- 'receipt_from_name' => "varchar(255)",
- 'receipt_text' => "text",
- 'footer_text' => "text",
- 'honor_block_title' => "varchar(255)",
- 'honor_block_text' => "text",
- ),
- 'civicrm_price_field' => array(
- 'label' => "varchar(255)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_group' => array(
- 'title' => "varchar(64)",
- 'help_pre' => "text",
- 'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
- 'help_post' => "text",
- 'help_pre' => "text",
- 'label' => "varchar(255)",
- ),
- 'civicrm_membership_type' => array(
- 'name' => "varchar(128)",
- 'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
- 'new_title' => "varchar(255)",
- 'new_text' => "text",
- 'renewal_title' => "varchar(255)",
- 'renewal_text' => "text",
- ),
- 'civicrm_price_field_value' => array(
- 'label' => "varchar(255)",
- 'description' => "text",
- ),
- 'civicrm_event' => array(
- 'title' => "varchar(255)",
- 'summary' => "text",
- 'description' => "text",
- 'registration_link_text' => "varchar(255)",
- 'event_full_text' => "text",
- 'fee_label' => "varchar(255)",
- 'intro_text' => "text",
- 'footer_text' => "text",
- 'confirm_title' => "varchar(255)",
- 'confirm_text' => "text",
- 'confirm_footer_text' => "text",
- 'confirm_email_text' => "text",
- 'confirm_from_name' => "varchar(255)",
- 'thankyou_title' => "varchar(255)",
- 'thankyou_text' => "text",
- 'thankyou_footer_text' => "text",
- 'pay_later_text' => "text",
- 'pay_later_receipt' => "text",
- 'waitlist_text' => "text",
- 'approval_req_text' => "text",
- 'template_title' => "varchar(255)",
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &indices() {
- static $result = NULL;
- if (!$result) {
- $result = array(
- 'civicrm_price_set' => array(
- 'UI_title' => array(
- 'name' => 'UI_title',
- 'field' => array(
- 'title',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
- 'name' => 'UI_title_extends',
- 'field' => array(
- 'title',
- 'extends',
- ),
- 'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
- 'name' => 'UI_label_custom_group_id',
- 'field' => array(
- 'label',
- 'custom_group_id',
- ),
- 'unique' => 1,
- ),
- ),
- );
- }
- return $result;
- }
-
- /**
- * @return array
- */
- public static function &tables() {
- static $result = NULL;
- if (!$result) {
- $result = array_keys(self::columns());
- }
- return $result;
- }
-
-}
diff --git a/CRM/Core/I18n/SchemaStructure_4_2_alpha1.php b/CRM/Core/I18n/SchemaStructure_4_2_alpha1.php
index 73a972ca5652..cfb456f973aa 100644
--- a/CRM/Core/I18n/SchemaStructure_4_2_alpha1.php
+++ b/CRM/Core/I18n/SchemaStructure_4_2_alpha1.php
@@ -1,9 +1,9 @@
array(
+ $result = [
+ 'civicrm_location_type' => [
'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
+ ],
+ 'civicrm_option_group' => [
'title' => "varchar(255)",
'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
+ ],
+ 'civicrm_contact_type' => [
'label' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_premiums' => array(
+ ],
+ 'civicrm_premiums' => [
'premiums_intro_title' => "varchar(255)",
'premiums_intro_text' => "text",
- ),
- 'civicrm_product' => array(
+ ],
+ 'civicrm_product' => [
'name' => "varchar(255)",
'description' => "text",
'options' => "text",
- ),
- 'civicrm_membership_status' => array(
+ ],
+ 'civicrm_membership_status' => [
'label' => "varchar(128)",
- ),
- 'civicrm_survey' => array(
+ ],
+ 'civicrm_survey' => [
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_participant_status_type' => array(
+ ],
+ 'civicrm_participant_status_type' => [
'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
+ ],
+ 'civicrm_tell_friend' => [
'title' => "varchar(255)",
'intro' => "text",
'suggested_message' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_price_set' => array(
+ ],
+ 'civicrm_price_set' => [
'title' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_batch' => array(
+ ],
+ 'civicrm_batch' => [
'title' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
+ ],
+ 'civicrm_custom_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
+ ],
+ 'civicrm_dashboard' => [
'label' => "varchar(255)",
- ),
- 'civicrm_option_value' => array(
+ ],
+ 'civicrm_option_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_group' => array(
+ ],
+ 'civicrm_group' => [
'title' => "varchar(64)",
- ),
- 'civicrm_contribution_page' => array(
+ ],
+ 'civicrm_contribution_page' => [
'title' => "varchar(255)",
'intro_text' => "text",
'pay_later_text' => "text",
@@ -120,40 +121,40 @@ public static function &columns() {
'footer_text' => "text",
'honor_block_title' => "varchar(255)",
'honor_block_text' => "text",
- ),
- 'civicrm_price_field' => array(
+ ],
+ 'civicrm_price_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_group' => array(
+ ],
+ 'civicrm_uf_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
+ ],
+ 'civicrm_uf_field' => [
'help_post' => "text",
'help_pre' => "text",
'label' => "varchar(255)",
- ),
- 'civicrm_membership_type' => array(
+ ],
+ 'civicrm_membership_type' => [
'name' => "varchar(128)",
'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
+ ],
+ 'civicrm_membership_block' => [
'new_title' => "varchar(255)",
'new_text' => "text",
'renewal_title' => "varchar(255)",
'renewal_text' => "text",
- ),
- 'civicrm_price_field_value' => array(
+ ],
+ 'civicrm_price_field_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
+ ],
+ 'civicrm_pcp_block' => [
'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
+ ],
+ 'civicrm_event' => [
'title' => "varchar(255)",
'summary' => "text",
'description' => "text",
@@ -175,8 +176,8 @@ public static function &columns() {
'waitlist_text' => "text",
'approval_req_text' => "text",
'template_title' => "varchar(255)",
- ),
- );
+ ],
+ ];
}
return $result;
}
@@ -187,37 +188,37 @@ public static function &columns() {
public static function &indices() {
static $result = NULL;
if (!$result) {
- $result = array(
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
'name' => 'UI_title_extends',
- 'field' => array(
+ 'field' => [
'title',
'extends',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
'name' => 'UI_label_custom_group_id',
- 'field' => array(
+ 'field' => [
'label',
'custom_group_id',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_group' => array(
- 'UI_title' => array(
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
'title',
- ),
+ ],
'unique' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return $result;
}
diff --git a/CRM/Core/I18n/SchemaStructure_4_3_1.php b/CRM/Core/I18n/SchemaStructure_4_3_1.php
index 8b29ef928bfe..69f038d049a9 100644
--- a/CRM/Core/I18n/SchemaStructure_4_3_1.php
+++ b/CRM/Core/I18n/SchemaStructure_4_3_1.php
@@ -1,9 +1,9 @@
array(
+ $result = [
+ 'civicrm_location_type' => [
'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
+ ],
+ 'civicrm_option_group' => [
'title' => "varchar(255)",
'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
+ ],
+ 'civicrm_contact_type' => [
'label' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_batch' => array(
+ ],
+ 'civicrm_batch' => [
'title' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_premiums' => array(
+ ],
+ 'civicrm_premiums' => [
'premiums_intro_title' => "varchar(255)",
'premiums_intro_text' => "text",
'premiums_nothankyou_label' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
+ ],
+ 'civicrm_membership_status' => [
'label' => "varchar(128)",
- ),
- 'civicrm_survey' => array(
+ ],
+ 'civicrm_survey' => [
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_participant_status_type' => array(
+ ],
+ 'civicrm_participant_status_type' => [
'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
+ ],
+ 'civicrm_tell_friend' => [
'title' => "varchar(255)",
'intro' => "text",
'suggested_message' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
+ ],
+ 'civicrm_custom_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_option_value' => array(
+ ],
+ 'civicrm_option_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_group' => array(
+ ],
+ 'civicrm_group' => [
'title' => "varchar(64)",
- ),
- 'civicrm_contribution_page' => array(
+ ],
+ 'civicrm_contribution_page' => [
'title' => "varchar(255)",
'intro_text' => "text",
'pay_later_text' => "text",
@@ -110,53 +111,53 @@ public static function &columns() {
'footer_text' => "text",
'honor_block_title' => "varchar(255)",
'honor_block_text' => "text",
- ),
- 'civicrm_product' => array(
+ ],
+ 'civicrm_product' => [
'name' => "varchar(255)",
'description' => "text",
'options' => "text",
- ),
- 'civicrm_membership_type' => array(
+ ],
+ 'civicrm_membership_type' => [
'name' => "varchar(128)",
'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
+ ],
+ 'civicrm_membership_block' => [
'new_title' => "varchar(255)",
'new_text' => "text",
'renewal_title' => "varchar(255)",
'renewal_text' => "text",
- ),
- 'civicrm_price_set' => array(
+ ],
+ 'civicrm_price_set' => [
'title' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
+ ],
+ 'civicrm_dashboard' => [
'label' => "varchar(255)",
- ),
- 'civicrm_uf_group' => array(
+ ],
+ 'civicrm_uf_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
+ ],
+ 'civicrm_uf_field' => [
'help_post' => "text",
'help_pre' => "text",
'label' => "varchar(255)",
- ),
- 'civicrm_price_field' => array(
+ ],
+ 'civicrm_price_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
+ ],
+ 'civicrm_price_field_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
+ ],
+ 'civicrm_pcp_block' => [
'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
+ ],
+ 'civicrm_event' => [
'title' => "varchar(255)",
'summary' => "text",
'description' => "text",
@@ -180,8 +181,8 @@ public static function &columns() {
'waitlist_text' => "text",
'approval_req_text' => "text",
'template_title' => "varchar(255)",
- ),
- );
+ ],
+ ];
}
return $result;
}
@@ -192,37 +193,37 @@ public static function &columns() {
public static function &indices() {
static $result = NULL;
if (!$result) {
- $result = array(
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
'name' => 'UI_title_extends',
- 'field' => array(
+ 'field' => [
'title',
'extends',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
'name' => 'UI_label_custom_group_id',
- 'field' => array(
+ 'field' => [
'label',
'custom_group_id',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_group' => array(
- 'UI_title' => array(
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
'title',
- ),
+ ],
'unique' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return $result;
}
diff --git a/CRM/Core/I18n/SchemaStructure_4_5_alpha1.php b/CRM/Core/I18n/SchemaStructure_4_5_alpha1.php
index 79b7e0789a00..c5cb4f4431d3 100644
--- a/CRM/Core/I18n/SchemaStructure_4_5_alpha1.php
+++ b/CRM/Core/I18n/SchemaStructure_4_5_alpha1.php
@@ -1,9 +1,9 @@
array(
+ $result = [
+ 'civicrm_location_type' => [
'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
+ ],
+ 'civicrm_option_group' => [
'title' => "varchar(255)",
'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
+ ],
+ 'civicrm_contact_type' => [
'label' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_batch' => array(
+ ],
+ 'civicrm_batch' => [
'title' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_premiums' => array(
+ ],
+ 'civicrm_premiums' => [
'premiums_intro_title' => "varchar(255)",
'premiums_intro_text' => "text",
'premiums_nothankyou_label' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
+ ],
+ 'civicrm_membership_status' => [
'label' => "varchar(128)",
- ),
- 'civicrm_survey' => array(
+ ],
+ 'civicrm_survey' => [
'title' => "varchar(255)",
'instructions' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_participant_status_type' => array(
+ ],
+ 'civicrm_participant_status_type' => [
'label' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
+ ],
+ 'civicrm_tell_friend' => [
'title' => "varchar(255)",
'intro' => "text",
'suggested_message' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
+ ],
+ 'civicrm_custom_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_option_value' => array(
+ ],
+ 'civicrm_option_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_group' => array(
+ ],
+ 'civicrm_group' => [
'title' => "varchar(64)",
- ),
- 'civicrm_contribution_page' => array(
+ ],
+ 'civicrm_contribution_page' => [
'title' => "varchar(255)",
'intro_text' => "text",
'pay_later_text' => "text",
@@ -111,53 +112,53 @@ public static function &columns() {
'receipt_from_name' => "varchar(255)",
'receipt_text' => "text",
'footer_text' => "text",
- ),
- 'civicrm_product' => array(
+ ],
+ 'civicrm_product' => [
'name' => "varchar(255)",
'description' => "text",
'options' => "text",
- ),
- 'civicrm_membership_type' => array(
+ ],
+ 'civicrm_membership_type' => [
'name' => "varchar(128)",
'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
+ ],
+ 'civicrm_membership_block' => [
'new_title' => "varchar(255)",
'new_text' => "text",
'renewal_title' => "varchar(255)",
'renewal_text' => "text",
- ),
- 'civicrm_price_set' => array(
+ ],
+ 'civicrm_price_set' => [
'title' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
+ ],
+ 'civicrm_dashboard' => [
'label' => "varchar(255)",
- ),
- 'civicrm_uf_group' => array(
+ ],
+ 'civicrm_uf_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
+ ],
+ 'civicrm_uf_field' => [
'help_post' => "text",
'help_pre' => "text",
'label' => "varchar(255)",
- ),
- 'civicrm_price_field' => array(
+ ],
+ 'civicrm_price_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
+ ],
+ 'civicrm_price_field_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
+ ],
+ 'civicrm_pcp_block' => [
'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
+ ],
+ 'civicrm_event' => [
'title' => "varchar(255)",
'summary' => "text",
'description' => "text",
@@ -181,8 +182,8 @@ public static function &columns() {
'waitlist_text' => "text",
'approval_req_text' => "text",
'template_title' => "varchar(255)",
- ),
- );
+ ],
+ ];
}
return $result;
}
@@ -193,37 +194,37 @@ public static function &columns() {
public static function &indices() {
static $result = NULL;
if (!$result) {
- $result = array(
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
'name' => 'UI_title_extends',
- 'field' => array(
+ 'field' => [
'title',
'extends',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
'name' => 'UI_label_custom_group_id',
- 'field' => array(
+ 'field' => [
'label',
'custom_group_id',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_group' => array(
- 'UI_title' => array(
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
'title',
- ),
+ ],
'unique' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return $result;
}
diff --git a/CRM/Core/I18n/SchemaStructure_4_5_beta2.php b/CRM/Core/I18n/SchemaStructure_4_5_beta2.php
index 8a95563d323a..125b6f8030b7 100644
--- a/CRM/Core/I18n/SchemaStructure_4_5_beta2.php
+++ b/CRM/Core/I18n/SchemaStructure_4_5_beta2.php
@@ -1,9 +1,9 @@
array(
+ $result = [
+ 'civicrm_location_type' => [
'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
+ ],
+ 'civicrm_option_group' => [
'title' => "varchar(255)",
'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
+ ],
+ 'civicrm_contact_type' => [
'label' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_batch' => array(
+ ],
+ 'civicrm_batch' => [
'title' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_premiums' => array(
+ ],
+ 'civicrm_premiums' => [
'premiums_intro_title' => "varchar(255)",
'premiums_intro_text' => "text",
'premiums_nothankyou_label' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
+ ],
+ 'civicrm_membership_status' => [
'label' => "varchar(128)",
- ),
- 'civicrm_survey' => array(
+ ],
+ 'civicrm_survey' => [
'title' => "varchar(255)",
'instructions' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_participant_status_type' => array(
+ ],
+ 'civicrm_participant_status_type' => [
'label' => "varchar(255)",
- ),
- 'civicrm_case_type' => array(
+ ],
+ 'civicrm_case_type' => [
'title' => "varchar(64)",
'description' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
+ ],
+ 'civicrm_tell_friend' => [
'title' => "varchar(255)",
'intro' => "text",
'suggested_message' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
+ ],
+ 'civicrm_custom_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_option_value' => array(
+ ],
+ 'civicrm_option_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_group' => array(
+ ],
+ 'civicrm_group' => [
'title' => "varchar(64)",
- ),
- 'civicrm_contribution_page' => array(
+ ],
+ 'civicrm_contribution_page' => [
'title' => "varchar(255)",
'intro_text' => "text",
'pay_later_text' => "text",
@@ -116,53 +116,53 @@ public static function &columns() {
'receipt_from_name' => "varchar(255)",
'receipt_text' => "text",
'footer_text' => "text",
- ),
- 'civicrm_product' => array(
+ ],
+ 'civicrm_product' => [
'name' => "varchar(255)",
'description' => "text",
'options' => "text",
- ),
- 'civicrm_membership_type' => array(
+ ],
+ 'civicrm_membership_type' => [
'name' => "varchar(128)",
'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
+ ],
+ 'civicrm_membership_block' => [
'new_title' => "varchar(255)",
'new_text' => "text",
'renewal_title' => "varchar(255)",
'renewal_text' => "text",
- ),
- 'civicrm_price_set' => array(
+ ],
+ 'civicrm_price_set' => [
'title' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
+ ],
+ 'civicrm_dashboard' => [
'label' => "varchar(255)",
- ),
- 'civicrm_uf_group' => array(
+ ],
+ 'civicrm_uf_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
+ ],
+ 'civicrm_uf_field' => [
'help_post' => "text",
'help_pre' => "text",
'label' => "varchar(255)",
- ),
- 'civicrm_price_field' => array(
+ ],
+ 'civicrm_price_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
+ ],
+ 'civicrm_price_field_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
+ ],
+ 'civicrm_pcp_block' => [
'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
+ ],
+ 'civicrm_event' => [
'title' => "varchar(255)",
'summary' => "text",
'description' => "text",
@@ -186,8 +186,8 @@ public static function &columns() {
'waitlist_text' => "text",
'approval_req_text' => "text",
'template_title' => "varchar(255)",
- ),
- );
+ ],
+ ];
}
return $result;
}
@@ -200,37 +200,37 @@ public static function &columns() {
public static function &indices() {
static $result = NULL;
if (!$result) {
- $result = array(
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
'name' => 'UI_title_extends',
- 'field' => array(
+ 'field' => [
'title',
'extends',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
'name' => 'UI_label_custom_group_id',
- 'field' => array(
+ 'field' => [
'label',
'custom_group_id',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_group' => array(
- 'UI_title' => array(
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
'title',
- ),
+ ],
'unique' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return $result;
}
diff --git a/CRM/Core/I18n/SchemaStructure_4_7_31.php b/CRM/Core/I18n/SchemaStructure_4_7_31.php
new file mode 100644
index 000000000000..7e81bf7a4ea3
--- /dev/null
+++ b/CRM/Core/I18n/SchemaStructure_4_7_31.php
@@ -0,0 +1,712 @@
+ [
+ 'display_name' => "varchar(64)",
+ ],
+ 'civicrm_option_group' => [
+ 'title' => "varchar(255)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => "varchar(64)",
+ 'label_b_a' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => "varchar(64)",
+ 'description' => "text",
+ ],
+ 'civicrm_batch' => [
+ 'title' => "varchar(255)",
+ 'description' => "text",
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => "varchar(255)",
+ 'premiums_intro_text' => "text",
+ 'premiums_nothankyou_label' => "varchar(255)",
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => "varchar(128)",
+ ],
+ 'civicrm_survey' => [
+ 'title' => "varchar(255)",
+ 'instructions' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_case_type' => [
+ 'title' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => "varchar(255)",
+ 'intro' => "text",
+ 'suggested_message' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_option_value' => [
+ 'label' => "varchar(512)",
+ 'description' => "text",
+ ],
+ 'civicrm_group' => [
+ 'title' => "varchar(64)",
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => "varchar(255)",
+ 'intro_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer' => "text",
+ 'receipt_from_name' => "varchar(255)",
+ 'receipt_text' => "text",
+ 'footer_text' => "text",
+ ],
+ 'civicrm_product' => [
+ 'name' => "varchar(255)",
+ 'description' => "text",
+ 'options' => "text",
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => "varchar(128)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => "varchar(255)",
+ 'new_text' => "text",
+ 'renewal_title' => "varchar(255)",
+ 'renewal_text' => "text",
+ ],
+ 'civicrm_price_set' => [
+ 'title' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => "varchar(64)",
+ 'frontend_title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ 'cancel_button_text' => "varchar(64)",
+ 'submit_button_text' => "varchar(64)",
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => "text",
+ 'help_pre' => "text",
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_price_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => "varchar(255)",
+ 'description' => "text",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => "varchar(255)",
+ ],
+ 'civicrm_event' => [
+ 'title' => "varchar(255)",
+ 'summary' => "text",
+ 'description' => "text",
+ 'registration_link_text' => "varchar(255)",
+ 'event_full_text' => "text",
+ 'fee_label' => "varchar(255)",
+ 'intro_text' => "text",
+ 'footer_text' => "text",
+ 'confirm_title' => "varchar(255)",
+ 'confirm_text' => "text",
+ 'confirm_footer_text' => "text",
+ 'confirm_email_text' => "text",
+ 'confirm_from_name' => "varchar(255)",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'waitlist_text' => "text",
+ 'approval_req_text' => "text",
+ 'template_title' => "varchar(255)",
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get a table indexed array of the indices for translatable fields.
+ *
+ * @return array
+ * Indices for translatable fields.
+ */
+ public static function &indices() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
+ 'name' => 'UI_title_extends',
+ 'field' => [
+ 'title',
+ 'extends',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
+ 'name' => 'UI_label_custom_group_id',
+ 'field' => [
+ 'label',
+ 'custom_group_id',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
+ 'name' => 'UI_title',
+ 'field' => [
+ 'title',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get tables with translatable fields.
+ *
+ * @return array
+ * Array of names of tables with fields that can be translated.
+ */
+ public static function &tables() {
+ static $result = NULL;
+ if (!$result) {
+ $result = array_keys(self::columns());
+ }
+ return $result;
+ }
+
+ /**
+ * Get a list of widgets for editing translatable fields.
+ *
+ * @return array
+ * Array of the widgets for editing translatable fields.
+ */
+ public static function &widgets() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_location_type' => [
+ 'display_name' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => [
+ 'type' => "Text",
+ ],
+ 'label_b_a' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_batch' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => [
+ 'type' => "Text",
+ ],
+ 'premiums_intro_text' => [
+ 'type' => "Text",
+ ],
+ 'premiums_nothankyou_label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_survey' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'instructions' => [
+ 'type' => "TextArea",
+ 'rows' => "20",
+ 'cols' => "80",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_case_type' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro' => [
+ 'type' => "Text",
+ ],
+ 'suggested_message' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_value' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'thankyou_footer' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'receipt_from_name' => [
+ 'type' => "Text",
+ ],
+ 'receipt_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ ],
+ 'civicrm_product' => [
+ 'name' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ 'options' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => [
+ 'type' => "Text",
+ ],
+ 'new_text' => [
+ 'type' => "Text",
+ ],
+ 'renewal_title' => [
+ 'type' => "Text",
+ ],
+ 'renewal_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_price_set' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'frontend_title' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'cancel_button_text' => [
+ 'type' => "Text",
+ ],
+ 'submit_button_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ ],
+ 'civicrm_price_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_event' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'summary' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'registration_link_text' => [
+ 'type' => "Text",
+ ],
+ 'event_full_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'fee_label' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_title' => [
+ 'type' => "Text",
+ ],
+ 'confirm_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_email_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "50",
+ ],
+ 'confirm_from_name' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'thankyou_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'waitlist_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'approval_req_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'template_title' => [
+ 'type' => "Text",
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+}
diff --git a/CRM/Core/I18n/SchemaStructure_4_7_alpha1.php b/CRM/Core/I18n/SchemaStructure_4_7_alpha1.php
index f69a1951a5d2..3b14ff6a0a61 100644
--- a/CRM/Core/I18n/SchemaStructure_4_7_alpha1.php
+++ b/CRM/Core/I18n/SchemaStructure_4_7_alpha1.php
@@ -1,9 +1,9 @@
array(
+ $result = [
+ 'civicrm_location_type' => [
'display_name' => "varchar(64)",
- ),
- 'civicrm_option_group' => array(
+ ],
+ 'civicrm_option_group' => [
'title' => "varchar(255)",
'description' => "varchar(255)",
- ),
- 'civicrm_contact_type' => array(
+ ],
+ 'civicrm_contact_type' => [
'label' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_batch' => array(
+ ],
+ 'civicrm_batch' => [
'title' => "varchar(64)",
'description' => "text",
- ),
- 'civicrm_premiums' => array(
+ ],
+ 'civicrm_premiums' => [
'premiums_intro_title' => "varchar(255)",
'premiums_intro_text' => "text",
'premiums_nothankyou_label' => "varchar(255)",
- ),
- 'civicrm_membership_status' => array(
+ ],
+ 'civicrm_membership_status' => [
'label' => "varchar(128)",
- ),
- 'civicrm_survey' => array(
+ ],
+ 'civicrm_survey' => [
'title' => "varchar(255)",
'instructions' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_participant_status_type' => array(
+ ],
+ 'civicrm_participant_status_type' => [
'label' => "varchar(255)",
- ),
- 'civicrm_case_type' => array(
+ ],
+ 'civicrm_case_type' => [
'title' => "varchar(64)",
'description' => "varchar(255)",
- ),
- 'civicrm_tell_friend' => array(
+ ],
+ 'civicrm_tell_friend' => [
'title' => "varchar(255)",
'intro' => "text",
'suggested_message' => "text",
'thankyou_title' => "varchar(255)",
'thankyou_text' => "text",
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_custom_field' => array(
+ ],
+ 'civicrm_custom_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_option_value' => array(
+ ],
+ 'civicrm_option_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_group' => array(
+ ],
+ 'civicrm_group' => [
'title' => "varchar(64)",
- ),
- 'civicrm_contribution_page' => array(
+ ],
+ 'civicrm_contribution_page' => [
'title' => "varchar(255)",
'intro_text' => "text",
'pay_later_text' => "text",
@@ -115,53 +115,53 @@ public static function &columns() {
'receipt_from_name' => "varchar(255)",
'receipt_text' => "text",
'footer_text' => "text",
- ),
- 'civicrm_product' => array(
+ ],
+ 'civicrm_product' => [
'name' => "varchar(255)",
'description' => "text",
'options' => "text",
- ),
- 'civicrm_membership_type' => array(
+ ],
+ 'civicrm_membership_type' => [
'name' => "varchar(128)",
'description' => "varchar(255)",
- ),
- 'civicrm_membership_block' => array(
+ ],
+ 'civicrm_membership_block' => [
'new_title' => "varchar(255)",
'new_text' => "text",
'renewal_title' => "varchar(255)",
'renewal_text' => "text",
- ),
- 'civicrm_price_set' => array(
+ ],
+ 'civicrm_price_set' => [
'title' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_dashboard' => array(
+ ],
+ 'civicrm_dashboard' => [
'label' => "varchar(255)",
- ),
- 'civicrm_uf_group' => array(
+ ],
+ 'civicrm_uf_group' => [
'title' => "varchar(64)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_uf_field' => array(
+ ],
+ 'civicrm_uf_field' => [
'help_post' => "text",
'help_pre' => "text",
'label' => "varchar(255)",
- ),
- 'civicrm_price_field' => array(
+ ],
+ 'civicrm_price_field' => [
'label' => "varchar(255)",
'help_pre' => "text",
'help_post' => "text",
- ),
- 'civicrm_price_field_value' => array(
+ ],
+ 'civicrm_price_field_value' => [
'label' => "varchar(255)",
'description' => "text",
- ),
- 'civicrm_pcp_block' => array(
+ ],
+ 'civicrm_pcp_block' => [
'link_text' => "varchar(255)",
- ),
- 'civicrm_event' => array(
+ ],
+ 'civicrm_event' => [
'title' => "varchar(255)",
'summary' => "text",
'description' => "text",
@@ -185,13 +185,13 @@ public static function &columns() {
'waitlist_text' => "text",
'approval_req_text' => "text",
'template_title' => "varchar(255)",
- ),
- 'civicrm_relationship_type' => array(
+ ],
+ 'civicrm_relationship_type' => [
'label_a_b' => "varchar(64)",
'label_b_a' => "varchar(64)",
'description' => "varchar(255)",
- ),
- );
+ ],
+ ];
}
return $result;
}
@@ -204,37 +204,37 @@ public static function &columns() {
public static function &indices() {
static $result = NULL;
if (!$result) {
- $result = array(
- 'civicrm_custom_group' => array(
- 'UI_title_extends' => array(
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
'name' => 'UI_title_extends',
- 'field' => array(
+ 'field' => [
'title',
'extends',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_custom_field' => array(
- 'UI_label_custom_group_id' => array(
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
'name' => 'UI_label_custom_group_id',
- 'field' => array(
+ 'field' => [
'label',
'custom_group_id',
- ),
+ ],
'unique' => 1,
- ),
- ),
- 'civicrm_group' => array(
- 'UI_title' => array(
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
'title',
- ),
+ ],
'unique' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return $result;
}
diff --git a/CRM/Core/I18n/SchemaStructure_5_13_alpha1.php b/CRM/Core/I18n/SchemaStructure_5_13_alpha1.php
new file mode 100644
index 000000000000..2daed955688b
--- /dev/null
+++ b/CRM/Core/I18n/SchemaStructure_5_13_alpha1.php
@@ -0,0 +1,722 @@
+ [
+ 'display_name' => "varchar(64)",
+ ],
+ 'civicrm_option_group' => [
+ 'title' => "varchar(255)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => "varchar(64)",
+ 'label_b_a' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => "varchar(64)",
+ 'description' => "text",
+ ],
+ 'civicrm_batch' => [
+ 'title' => "varchar(255)",
+ 'description' => "text",
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => "varchar(255)",
+ 'premiums_intro_text' => "text",
+ 'premiums_nothankyou_label' => "varchar(255)",
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => "varchar(128)",
+ ],
+ 'civicrm_survey' => [
+ 'title' => "varchar(255)",
+ 'instructions' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_case_type' => [
+ 'title' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => "varchar(255)",
+ 'intro' => "text",
+ 'suggested_message' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_option_value' => [
+ 'label' => "varchar(512)",
+ 'description' => "text",
+ ],
+ 'civicrm_group' => [
+ 'title' => "varchar(64)",
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => "varchar(255)",
+ 'intro_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer' => "text",
+ 'receipt_from_name' => "varchar(255)",
+ 'receipt_text' => "text",
+ 'footer_text' => "text",
+ ],
+ 'civicrm_product' => [
+ 'name' => "varchar(255)",
+ 'description' => "text",
+ 'options' => "text",
+ ],
+ 'civicrm_payment_processor' => [
+ 'title' => "varchar(127)",
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => "varchar(128)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => "varchar(255)",
+ 'new_text' => "text",
+ 'renewal_title' => "varchar(255)",
+ 'renewal_text' => "text",
+ ],
+ 'civicrm_price_set' => [
+ 'title' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => "varchar(64)",
+ 'frontend_title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ 'cancel_button_text' => "varchar(64)",
+ 'submit_button_text' => "varchar(64)",
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => "text",
+ 'help_pre' => "text",
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_price_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => "varchar(255)",
+ 'description' => "text",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => "varchar(255)",
+ ],
+ 'civicrm_event' => [
+ 'title' => "varchar(255)",
+ 'summary' => "text",
+ 'description' => "text",
+ 'registration_link_text' => "varchar(255)",
+ 'event_full_text' => "text",
+ 'fee_label' => "varchar(255)",
+ 'intro_text' => "text",
+ 'footer_text' => "text",
+ 'confirm_title' => "varchar(255)",
+ 'confirm_text' => "text",
+ 'confirm_footer_text' => "text",
+ 'confirm_email_text' => "text",
+ 'confirm_from_name' => "varchar(255)",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'waitlist_text' => "text",
+ 'approval_req_text' => "text",
+ 'template_title' => "varchar(255)",
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get a table indexed array of the indices for translatable fields.
+ *
+ * @return array
+ * Indices for translatable fields.
+ */
+ public static function &indices() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
+ 'name' => 'UI_title_extends',
+ 'field' => [
+ 'title',
+ 'extends',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
+ 'name' => 'UI_label_custom_group_id',
+ 'field' => [
+ 'label',
+ 'custom_group_id',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
+ 'name' => 'UI_title',
+ 'field' => [
+ 'title',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get tables with translatable fields.
+ *
+ * @return array
+ * Array of names of tables with fields that can be translated.
+ */
+ public static function &tables() {
+ static $result = NULL;
+ if (!$result) {
+ $result = array_keys(self::columns());
+ }
+ return $result;
+ }
+
+ /**
+ * Get a list of widgets for editing translatable fields.
+ *
+ * @return array
+ * Array of the widgets for editing translatable fields.
+ */
+ public static function &widgets() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_location_type' => [
+ 'display_name' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => [
+ 'type' => "Text",
+ ],
+ 'label_b_a' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_batch' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => [
+ 'type' => "Text",
+ ],
+ 'premiums_intro_text' => [
+ 'type' => "Text",
+ ],
+ 'premiums_nothankyou_label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_survey' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'instructions' => [
+ 'type' => "TextArea",
+ 'rows' => "20",
+ 'cols' => "80",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_case_type' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro' => [
+ 'type' => "Text",
+ ],
+ 'suggested_message' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_value' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'thankyou_footer' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'receipt_from_name' => [
+ 'type' => "Text",
+ ],
+ 'receipt_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ ],
+ 'civicrm_product' => [
+ 'name' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ 'options' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_payment_processor' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => [
+ 'type' => "Text",
+ 'label' => "Name",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ 'label' => "Description",
+ ],
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => [
+ 'type' => "Text",
+ ],
+ 'new_text' => [
+ 'type' => "Text",
+ ],
+ 'renewal_title' => [
+ 'type' => "Text",
+ ],
+ 'renewal_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_price_set' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'frontend_title' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'cancel_button_text' => [
+ 'type' => "Text",
+ ],
+ 'submit_button_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ ],
+ 'civicrm_price_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_event' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'summary' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'registration_link_text' => [
+ 'type' => "Text",
+ ],
+ 'event_full_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'fee_label' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_title' => [
+ 'type' => "Text",
+ ],
+ 'confirm_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_email_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "50",
+ ],
+ 'confirm_from_name' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'thankyou_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'waitlist_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'approval_req_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'template_title' => [
+ 'type' => "Text",
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+}
diff --git a/CRM/Core/I18n/SchemaStructure_5_4_alpha1.php b/CRM/Core/I18n/SchemaStructure_5_4_alpha1.php
new file mode 100644
index 000000000000..939f56b336b2
--- /dev/null
+++ b/CRM/Core/I18n/SchemaStructure_5_4_alpha1.php
@@ -0,0 +1,714 @@
+ [
+ 'display_name' => "varchar(64)",
+ ],
+ 'civicrm_option_group' => [
+ 'title' => "varchar(255)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => "varchar(64)",
+ 'label_b_a' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => "varchar(64)",
+ 'description' => "text",
+ ],
+ 'civicrm_batch' => [
+ 'title' => "varchar(255)",
+ 'description' => "text",
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => "varchar(255)",
+ 'premiums_intro_text' => "text",
+ 'premiums_nothankyou_label' => "varchar(255)",
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => "varchar(128)",
+ ],
+ 'civicrm_survey' => [
+ 'title' => "varchar(255)",
+ 'instructions' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_case_type' => [
+ 'title' => "varchar(64)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => "varchar(255)",
+ 'intro' => "text",
+ 'suggested_message' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_option_value' => [
+ 'label' => "varchar(512)",
+ 'description' => "text",
+ ],
+ 'civicrm_group' => [
+ 'title' => "varchar(64)",
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => "varchar(255)",
+ 'intro_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer' => "text",
+ 'receipt_from_name' => "varchar(255)",
+ 'receipt_text' => "text",
+ 'footer_text' => "text",
+ ],
+ 'civicrm_product' => [
+ 'name' => "varchar(255)",
+ 'description' => "text",
+ 'options' => "text",
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => "varchar(128)",
+ 'description' => "varchar(255)",
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => "varchar(255)",
+ 'new_text' => "text",
+ 'renewal_title' => "varchar(255)",
+ 'renewal_text' => "text",
+ ],
+ 'civicrm_price_set' => [
+ 'title' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => "varchar(64)",
+ 'frontend_title' => "varchar(64)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ 'cancel_button_text' => "varchar(64)",
+ 'submit_button_text' => "varchar(64)",
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => "text",
+ 'help_pre' => "text",
+ 'label' => "varchar(255)",
+ ],
+ 'civicrm_price_field' => [
+ 'label' => "varchar(255)",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => "varchar(255)",
+ 'description' => "text",
+ 'help_pre' => "text",
+ 'help_post' => "text",
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => "varchar(255)",
+ ],
+ 'civicrm_event' => [
+ 'title' => "varchar(255)",
+ 'summary' => "text",
+ 'description' => "text",
+ 'registration_link_text' => "varchar(255)",
+ 'event_full_text' => "text",
+ 'fee_label' => "varchar(255)",
+ 'intro_text' => "text",
+ 'footer_text' => "text",
+ 'confirm_title' => "varchar(255)",
+ 'confirm_text' => "text",
+ 'confirm_footer_text' => "text",
+ 'confirm_email_text' => "text",
+ 'confirm_from_name' => "varchar(255)",
+ 'thankyou_title' => "varchar(255)",
+ 'thankyou_text' => "text",
+ 'thankyou_footer_text' => "text",
+ 'pay_later_text' => "text",
+ 'pay_later_receipt' => "text",
+ 'initial_amount_label' => "varchar(255)",
+ 'initial_amount_help_text' => "text",
+ 'waitlist_text' => "text",
+ 'approval_req_text' => "text",
+ 'template_title' => "varchar(255)",
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get a table indexed array of the indices for translatable fields.
+ *
+ * @return array
+ * Indices for translatable fields.
+ */
+ public static function indices() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_custom_group' => [
+ 'UI_title_extends' => [
+ 'name' => 'UI_title_extends',
+ 'field' => [
+ 'title',
+ 'extends',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'UI_label_custom_group_id' => [
+ 'name' => 'UI_label_custom_group_id',
+ 'field' => [
+ 'label',
+ 'custom_group_id',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ 'civicrm_group' => [
+ 'UI_title' => [
+ 'name' => 'UI_title',
+ 'field' => [
+ 'title',
+ ],
+ 'unique' => 1,
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * Get tables with translatable fields.
+ *
+ * @return array
+ * Array of names of tables with fields that can be translated.
+ */
+ public static function tables() {
+ static $result = NULL;
+ if (!$result) {
+ $result = array_keys(self::columns());
+ }
+ return $result;
+ }
+
+ /**
+ * Get a list of widgets for editing translatable fields.
+ *
+ * @return array
+ * Array of the widgets for editing translatable fields.
+ */
+ public static function widgets() {
+ static $result = NULL;
+ if (!$result) {
+ $result = [
+ 'civicrm_location_type' => [
+ 'display_name' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_relationship_type' => [
+ 'label_a_b' => [
+ 'type' => "Text",
+ ],
+ 'label_b_a' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contact_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_batch' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_premiums' => [
+ 'premiums_intro_title' => [
+ 'type' => "Text",
+ ],
+ 'premiums_intro_text' => [
+ 'type' => "Text",
+ ],
+ 'premiums_nothankyou_label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_status' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_survey' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'instructions' => [
+ 'type' => "TextArea",
+ 'rows' => "20",
+ 'cols' => "80",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_participant_status_type' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_case_type' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_tell_friend' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro' => [
+ 'type' => "Text",
+ ],
+ 'suggested_message' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_custom_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_custom_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_option_value' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_group' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_contribution_page' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'thankyou_footer' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'receipt_from_name' => [
+ 'type' => "Text",
+ ],
+ 'receipt_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "RichTextEditor",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ ],
+ 'civicrm_product' => [
+ 'name' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'description' => [
+ 'type' => "Text",
+ ],
+ 'options' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_membership_type' => [
+ 'name' => [
+ 'type' => "Text",
+ 'label' => "Name",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ 'label' => "Description",
+ ],
+ ],
+ 'civicrm_membership_block' => [
+ 'new_title' => [
+ 'type' => "Text",
+ ],
+ 'new_text' => [
+ 'type' => "Text",
+ ],
+ 'renewal_title' => [
+ 'type' => "Text",
+ ],
+ 'renewal_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_price_set' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_dashboard' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_group' => [
+ 'title' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'frontend_title' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'cancel_button_text' => [
+ 'type' => "Text",
+ ],
+ 'submit_button_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_uf_field' => [
+ 'help_post' => [
+ 'type' => "Text",
+ ],
+ 'help_pre' => [
+ 'type' => "Text",
+ ],
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ ],
+ 'civicrm_price_field' => [
+ 'label' => [
+ 'type' => "Text",
+ 'required' => "true",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "80",
+ ],
+ ],
+ 'civicrm_price_field_value' => [
+ 'label' => [
+ 'type' => "Text",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_pre' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ 'help_post' => [
+ 'type' => "TextArea",
+ 'rows' => "2",
+ 'cols' => "60",
+ ],
+ ],
+ 'civicrm_pcp_block' => [
+ 'link_text' => [
+ 'type' => "Text",
+ ],
+ ],
+ 'civicrm_event' => [
+ 'title' => [
+ 'type' => "Text",
+ ],
+ 'summary' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'description' => [
+ 'type' => "TextArea",
+ 'rows' => "8",
+ 'cols' => "60",
+ ],
+ 'registration_link_text' => [
+ 'type' => "Text",
+ ],
+ 'event_full_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'fee_label' => [
+ 'type' => "Text",
+ ],
+ 'intro_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_title' => [
+ 'type' => "Text",
+ ],
+ 'confirm_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'confirm_email_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "50",
+ ],
+ 'confirm_from_name' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_title' => [
+ 'type' => "Text",
+ ],
+ 'thankyou_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'thankyou_footer_text' => [
+ 'type' => "TextArea",
+ 'rows' => "6",
+ 'cols' => "50",
+ ],
+ 'pay_later_text' => [
+ 'type' => "Text",
+ ],
+ 'pay_later_receipt' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_label' => [
+ 'type' => "Text",
+ ],
+ 'initial_amount_help_text' => [
+ 'type' => "Text",
+ ],
+ 'waitlist_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'approval_req_text' => [
+ 'type' => "TextArea",
+ 'rows' => "4",
+ 'cols' => "60",
+ ],
+ 'template_title' => [
+ 'type' => "Text",
+ ],
+ ],
+ ];
+ }
+ return $result;
+ }
+
+}
diff --git a/CRM/Core/IDS.php b/CRM/Core/IDS.php
index 9cc0fb02c11a..4d0d513e2c01 100644
--- a/CRM/Core/IDS.php
+++ b/CRM/Core/IDS.php
@@ -1,9 +1,9 @@
25,
'warn' => 50,
'kick' => 75,
- );
+ ];
/**
* @var string
@@ -52,41 +53,33 @@ class CRM_Core_IDS {
* This function includes the IDS vendor parts and runs the
* detection routines on the request array.
*
- * @param array $args
- * List of path parts.
+ * @param array $route
*
* @return bool
*/
- public function check($args) {
+ public function check($route) {
+ if (CRM_Core_Permission::check('skip IDS check')) {
+ return NULL;
+ }
+
// lets bypass a few civicrm urls from this check
- $skip = array('civicrm/admin/setting/updateConfigBackend', 'civicrm/admin/messageTemplates');
+ $skip = ['civicrm/admin/setting/updateConfigBackend', 'civicrm/admin/messageTemplates'];
CRM_Utils_Hook::idsException($skip);
- $this->path = implode('/', $args);
+ $this->path = $route['path'];
if (in_array($this->path, $skip)) {
return NULL;
}
+ $init = self::create(self::createRouteConfig($route));
+
// Add request url and user agent.
$_REQUEST['IDS_request_uri'] = $_SERVER['REQUEST_URI'];
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$_REQUEST['IDS_user_agent'] = $_SERVER['HTTP_USER_AGENT'];
}
- $configFile = self::createConfigFile(FALSE);
-
- // init the PHPIDS and pass the REQUEST array
- require_once 'IDS/Init.php';
- try {
- $init = IDS_Init::init($configFile);
- $ids = new IDS_Monitor($_REQUEST, $init);
- }
- catch (Exception $e) {
- // might be an old stale copy of Config.IDS.ini
- // lets try to rebuild it again and see if it works
- $configFile = self::createConfigFile(TRUE);
- $init = IDS_Init::init($configFile);
- $ids = new IDS_Monitor($_REQUEST, $init);
- }
+ require_once 'IDS/Monitor.php';
+ $ids = new \IDS_Monitor($_REQUEST, $init);
$result = $ids->run();
if (!$result->isEmpty()) {
@@ -97,79 +90,120 @@ public function check($args) {
}
/**
- * Create the default config file for the IDS system.
- *
- * @param bool $force
- * Should we recreate it irrespective if it exists or not.
+ * Create a new PHPIDS configuration object.
*
- * @return string
- * the full path to the config file
+ * @param array $config
+ * PHPIDS configuration array (per INI format).
+ * @return \IDS_Init
*/
- public static function createConfigFile($force = FALSE) {
- $config = CRM_Core_Config::singleton();
- $configFile = $config->configAndLogDir . 'Config.IDS.ini';
- if (!$force && file_exists($configFile)) {
- return $configFile;
- }
+ protected static function create($config) {
+ require_once 'IDS/Init.php';
+ $init = \IDS_Init::init(NULL);
+ $init->setConfig($config, TRUE);
- $tmpDir = empty($config->uploadDir) ? CIVICRM_TEMPLATE_COMPILEDIR : $config->uploadDir;
+ // Cleanup
+ $reflection = new \ReflectionProperty('IDS_Init', 'instances');
+ $reflection->setAccessible(TRUE);
+ $value = $reflection->getValue(NULL);
+ unset($value[NULL]);
+ $reflection->setValue(NULL, $value);
- // also clear the stat cache in case we are upgrading
- clearstatcache();
+ return $init;
+ }
+ /**
+ * Create conservative, minimalist IDS configuration.
+ *
+ * @return array
+ */
+ public static function createBaseConfig() {
+ $config = \CRM_Core_Config::singleton();
+ $tmpDir = empty($config->uploadDir) ? CIVICRM_TEMPLATE_COMPILEDIR : $config->uploadDir;
global $civicrm_root;
- $contents = "
-[General]
- filter_type = xml
- filter_path = {$civicrm_root}/packages/IDS/default_filter.xml
- tmp_path = $tmpDir
- HTML_Purifier_Path = IDS/vendors/htmlpurifier/HTMLPurifier.auto.php
- HTML_Purifier_Cache = $tmpDir
- scan_keys = false
- exceptions[] = __utmz
- exceptions[] = __utmc
- exceptions[] = widget_code
- exceptions[] = html_message
- exceptions[] = text_message
- exceptions[] = body_html
- exceptions[] = msg_html
- exceptions[] = msg_text
- exceptions[] = msg_subject
- exceptions[] = description
- exceptions[] = intro
- exceptions[] = thankyou_text
- exceptions[] = intro_text
- exceptions[] = body_text
- exceptions[] = footer_text
- exceptions[] = thankyou_text
- exceptions[] = tf_thankyou_text
- exceptions[] = thankyou_footer
- exceptions[] = thankyou_footer_text
- exceptions[] = new_text
- exceptions[] = renewal_text
- exceptions[] = help_pre
- exceptions[] = help_post
- exceptions[] = confirm_title
- exceptions[] = confirm_text
- exceptions[] = confirm_footer_text
- exceptions[] = confirm_email_text
- exceptions[] = report_header
- exceptions[] = report_footer
- exceptions[] = data
- exceptions[] = json
- exceptions[] = instructions
- exceptions[] = suggested_message
- exceptions[] = page_text
-";
- if (file_put_contents($configFile, $contents) === FALSE) {
- CRM_Core_Error::movedSiteError($configFile);
- }
- // also create the .htaccess file so we prevent the reading of the log and ini files
- // via a browser, CRM-3875
- CRM_Utils_File::restrictAccess($config->configAndLogDir);
+ return [
+ 'General' => [
+ 'filter_type' => 'xml',
+ 'filter_path' => "{$civicrm_root}/packages/IDS/default_filter.xml",
+ 'tmp_path' => $tmpDir,
+ 'HTML_Purifier_Path' => $civicrm_root . 'packages/IDS/vendors/htmlpurifer/HTMLPurifier.auto.php',
+ 'HTML_Purifier_Cache' => $tmpDir,
+ 'scan_keys' => '',
+ 'exceptions' => ['__utmz', '__utmc'],
+ ],
+ ];
+ }
+
+ /**
+ * Create the standard, general-purpose IDS configuration used by many pages.
+ *
+ * @return array
+ */
+ public static function createStandardConfig() {
+ $excs = [
+ 'widget_code',
+ 'html_message',
+ 'text_message',
+ 'body_html',
+ 'msg_html',
+ 'msg_text',
+ 'msg_subject',
+ 'description',
+ 'intro',
+ 'thankyou_text',
+ 'intro_text',
+ 'body_text',
+ 'footer_text',
+ 'thankyou_text',
+ 'tf_thankyou_text',
+ 'thankyou_footer',
+ 'thankyou_footer_text',
+ 'new_text',
+ 'renewal_text',
+ 'help_pre',
+ 'help_post',
+ 'confirm_title',
+ 'confirm_text',
+ 'confirm_footer_text',
+ 'confirm_email_text',
+ 'report_header',
+ 'report_footer',
+ 'data',
+ 'json',
+ 'instructions',
+ 'suggested_message',
+ 'page_text',
+ 'details',
+ ];
+
+ $result = self::createBaseConfig();
+
+ $result['General']['exceptions'] = array_merge(
+ $result['General']['exceptions'],
+ $excs
+ );
- return $configFile;
+ return $result;
+ }
+
+ /**
+ * @param array $route
+ * @return array
+ */
+ public static function createRouteConfig($route) {
+ $config = \CRM_Core_IDS::createStandardConfig();
+ foreach (['json', 'html', 'exceptions'] as $section) {
+ if (isset($route['ids_arguments'][$section])) {
+ if (!isset($config['General'][$section])) {
+ $config['General'][$section] = [];
+ }
+ foreach ($route['ids_arguments'][$section] as $v) {
+ $config['General'][$section][] = $v;
+ }
+ $config['General'][$section] = array_unique($config['General'][$section]);
+ }
+ }
+ return $config;
}
/**
@@ -182,7 +216,7 @@ public static function createConfigFile($force = FALSE) {
*
* @return bool
*/
- private function react(IDS_Report $result) {
+ public function react(IDS_Report $result) {
$impact = $result->getImpact();
if ($impact >= $this->threshold['kick']) {
@@ -218,10 +252,10 @@ private function log($result, $reaction = 0) {
isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '127.0.0.1'
);
- $data = array();
+ $data = [];
$session = CRM_Core_Session::singleton();
foreach ($result as $event) {
- $data[] = array(
+ $data[] = [
'name' => $event->getName(),
'value' => stripslashes($event->getValue()),
'page' => $_SERVER['REQUEST_URI'],
@@ -230,7 +264,7 @@ private function log($result, $reaction = 0) {
'ip' => $ip,
'reaction' => $reaction,
'impact' => $result->getImpact(),
- );
+ ];
}
CRM_Core_Error::debug_var('IDS Detector Details', $data);
@@ -261,18 +295,18 @@ private function kick() {
if (in_array(
$this->path,
- array("civicrm/ajax/rest", "civicrm/api/json")
+ ["civicrm/ajax/rest", "civicrm/api/json"]
)) {
require_once "api/v3/utils.php";
$error = civicrm_api3_create_error(
$msg,
- array(
+ [
'IP' => $_SERVER['REMOTE_ADDR'],
'error_code' => 'IDS_KICK',
'level' => 'security',
'referer' => $_SERVER['HTTP_REFERER'],
'reason' => 'XSS suspected',
- )
+ ]
);
CRM_Utils_JSON::output($error);
}
diff --git a/CRM/Core/InnoDBIndexer.php b/CRM/Core/InnoDBIndexer.php
index 88d9195ae025..bdf45c9885fb 100644
--- a/CRM/Core/InnoDBIndexer.php
+++ b/CRM/Core/InnoDBIndexer.php
@@ -1,9 +1,9 @@
array(
- array('street_address', 'city', 'postal_code'),
- ),
- 'civicrm_activity' => array(
- array('subject', 'details'),
- ),
- 'civicrm_contact' => array(
- array('sort_name', 'nick_name', 'display_name'),
- ),
- 'civicrm_contribution' => array(
- array('source', 'amount_level', 'trxn_Id', 'invoice_id'),
- ),
- 'civicrm_email' => array(
- array('email'),
- ),
- 'civicrm_membership' => array(
- array('source'),
- ),
- 'civicrm_note' => array(
- array('subject', 'note'),
- ),
- 'civicrm_participant' => array(
- array('source', 'fee_level'),
- ),
- 'civicrm_phone' => array(
- array('phone'),
- ),
- 'civicrm_tag' => array(
- array('name'),
- ),
- );
+ $indices = [
+ 'civicrm_address' => [
+ ['street_address', 'city', 'postal_code'],
+ ],
+ 'civicrm_activity' => [
+ ['subject', 'details'],
+ ],
+ 'civicrm_contact' => [
+ ['sort_name', 'nick_name', 'display_name'],
+ ],
+ 'civicrm_contribution' => [
+ ['source', 'amount_level', 'trxn_Id', 'invoice_id'],
+ ],
+ 'civicrm_email' => [
+ ['email'],
+ ],
+ 'civicrm_membership' => [
+ ['source'],
+ ],
+ 'civicrm_note' => [
+ ['subject', 'note'],
+ ],
+ 'civicrm_participant' => [
+ ['source', 'fee_level'],
+ ],
+ 'civicrm_phone' => [
+ ['phone'],
+ ],
+ 'civicrm_tag' => [
+ ['name'],
+ ],
+ ];
$active = Civi::settings()->get('enable_innodb_fts');
self::$singleton = new self($active, $indices);
}
@@ -91,6 +91,10 @@ public static function singleton($fresh = FALSE) {
* Specification of the setting (per *.settings.php).
*/
public static function onToggleFts($oldValue, $newValue, $metadata) {
+ if (empty($oldValue) && empty($newValue)) {
+ return;
+ }
+
$indexer = CRM_Core_InnoDBIndexer::singleton();
$indexer->setActive($newValue);
$indexer->fixSchemaDifferences();
@@ -152,7 +156,7 @@ public function hasDeclaredIndex($table, $fields) {
foreach ($this->indices[$table] as $idxFields) {
// TODO determine if $idxFields must be exact match or merely a subset
// if (sort($fields) == sort($idxFields)) {
- if (array_diff($fields, $idxFields) == array()) {
+ if (array_diff($fields, $idxFields) == []) {
return TRUE;
}
}
@@ -173,7 +177,7 @@ public function findActualFtsIndexNames($table) {
if (version_compare($mysqlVersion, '5.6', '<')) {
// If we're not on 5.6+, then there cannot be any InnoDB FTS indices!
// Also: information_schema.innodb_sys_indexes is only available on 5.6+.
- return array();
+ return [];
}
// Note: this only works in MySQL 5.6, but this whole system is intended to only work in MySQL 5.6
@@ -185,7 +189,7 @@ public function findActualFtsIndexNames($table) {
AND i.name like '" . self::IDX_PREFIX . "%'
";
$dao = CRM_Core_DAO::executeQuery($sql);
- $indexNames = array();
+ $indexNames = [];
while ($dao->fetch()) {
$indexNames[$dao->index_name] = $dao->index_name;
}
@@ -202,7 +206,8 @@ public function findActualFtsIndexNames($table) {
* (string $indexName => string $sql)
*/
public function buildIndexSql($table) {
- $sqls = array(); // array (string $idxName => string $sql)
+ // array (string $idxName => string $sql)
+ $sqls = [];
if ($this->isActive && isset($this->indices[$table])) {
foreach ($this->indices[$table] as $fields) {
$name = self::IDX_PREFIX . md5($table . '::' . implode(',', $fields));
@@ -221,7 +226,7 @@ public function buildIndexSql($table) {
* (string $idxName => string $sql)
*/
public function dropIndexSql($table) {
- $sqls = array();
+ $sqls = [];
$names = $this->findActualFtsIndexNames($table);
foreach ($names as $name) {
$sqls[$name] = sprintf("DROP INDEX %s ON %s", $name, $table);
@@ -246,7 +251,7 @@ public function reconcileIndexSqls($table) {
array_keys($buildIndexSqls)
));
- $todoSqls = array();
+ $todoSqls = [];
foreach ($allIndexNames as $indexName) {
if (isset($buildIndexSqls[$indexName]) && isset($dropIndexSqls[$indexName])) {
// already exists
@@ -268,7 +273,7 @@ public function reconcileIndexSqls($table) {
* @return array
*/
public function normalizeIndices($indices) {
- $result = array();
+ $result = [];
foreach ($indices as $table => $indicesByTable) {
foreach ($indicesByTable as $k => $fields) {
sort($fields);
diff --git a/CRM/Core/Invoke.php b/CRM/Core/Invoke.php
index 35158067b8b5..9a9e04a9327b 100644
--- a/CRM/Core/Invoke.php
+++ b/CRM/Core/Invoke.php
@@ -1,9 +1,9 @@
check($args);
- }
// also initialize the i18n framework
require_once 'CRM/Core/I18n.php';
@@ -151,7 +147,7 @@ static public function init($args) {
* List of path parts.
* @void
*/
- static public function hackStandalone($args) {
+ public static function hackStandalone($args) {
$config = CRM_Core_Config::singleton();
if ($config->userFramework == 'Standalone') {
$session = CRM_Core_Session::singleton();
@@ -171,7 +167,7 @@ static public function hackStandalone($args) {
* List of path parts.
* @return array; see CRM_Core_Menu
*/
- static public function getItem($args) {
+ public static function getItem($args) {
if (is_array($args)) {
// get the menu items
$path = implode('/', $args);
@@ -198,7 +194,10 @@ static public function getItem($args) {
* See CRM_Core_Menu.
* @return string, HTML
*/
- static public function runItem($item) {
+ public static function runItem($item) {
+ $ids = new CRM_Core_IDS();
+ $ids->check($item);
+
$config = CRM_Core_Config::singleton();
if ($config->userFramework == 'Joomla' && $item) {
$config->userFrameworkURLVar = 'task';
@@ -331,12 +330,12 @@ static public function runItem($item) {
*
*/
public static function form($action, $contact_type, $contact_sub_type) {
- CRM_Utils_System::setUserContext(array('civicrm/contact/search/basic', 'civicrm/contact/view'));
+ CRM_Utils_System::setUserContext(['civicrm/contact/search/basic', 'civicrm/contact/view']);
$wrapper = new CRM_Utils_Wrapper();
$properties = CRM_Core_Component::contactSubTypeProperties($contact_sub_type, 'Edit');
if ($properties) {
- $wrapper->run($properties['class'], ts('New %1', array(1 => $contact_sub_type)), $action, TRUE);
+ $wrapper->run($properties['class'], ts('New %1', [1 => $contact_sub_type]), $action, TRUE);
}
else {
$wrapper->run('CRM_Contact_Form_Contact', ts('New Contact'), $action, TRUE);
@@ -353,7 +352,7 @@ public static function statusCheck($template) {
return;
}
// always use cached results - they will be refreshed by the session timer
- $status = Civi::settings()->get('systemStatusCheckResult');
+ $status = Civi::cache('checks')->get('systemStatusCheckResult');
$template->assign('footer_status_severity', $status);
$template->assign('footer_status_message', CRM_Utils_Check::toStatusLabel($status));
}
@@ -396,9 +395,6 @@ public static function rebuildMenuAndCaches($triggerRebuild = FALSE, $sessionRes
}
CRM_Core_DAO_AllCoreTables::reinitializeCache(TRUE);
CRM_Core_ManagedEntities::singleton(TRUE)->reconcile();
-
- //CRM-16257 update Config.IDS.ini might be an old copy
- CRM_Core_IDS::createConfigFile(TRUE);
}
}
diff --git a/CRM/Core/JobManager.php b/CRM/Core/JobManager.php
index c9853d5b1922..d583a1c9516a 100644
--- a/CRM/Core/JobManager.php
+++ b/CRM/Core/JobManager.php
@@ -1,9 +1,9 @@
CRM_Core_ScheduledJob)
*/
- var $jobs = NULL;
+ public $jobs = NULL;
/**
* @var CRM_Core_ScheduledJob
*/
- var $currentJob = NULL;
+ public $currentJob = NULL;
- var $singleRunParams = array();
-
- var $_source = NULL;
+ public $singleRunParams = [];
+ public $_source = NULL;
/**
* Class constructor.
@@ -83,10 +82,10 @@ public function execute($auth = TRUE) {
$this->logEntry('Finishing scheduled jobs execution.');
// Set last cron date for the status check
- $statusPref = array(
+ $statusPref = [
'name' => 'checkLastCron',
'check_info' => gmdate('U'),
- );
+ ];
CRM_Core_BAO_StatusPreference::create($statusPref);
}
@@ -118,6 +117,17 @@ public function executeJobById($id) {
*/
public function executeJob($job) {
$this->currentJob = $job;
+
+ // CRM-18231 check if non-production environment.
+ try {
+ CRM_Core_BAO_Setting::isAPIJobAllowedToRun($job->apiParams);
+ }
+ catch (Exception $e) {
+ $this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
+ $this->currentJob = FALSE;
+ return FALSE;
+ }
+
$this->logEntry('Starting execution of ' . $job->name);
$job->saveLastRun();
@@ -130,14 +140,23 @@ public function executeJob($job) {
$params = $job->apiParams;
}
+ CRM_Utils_Hook::preJob($job, $params);
try {
$result = civicrm_api($job->api_entity, $job->api_action, $params);
}
catch (Exception$e) {
$this->logEntry('Error while executing ' . $job->name . ': ' . $e->getMessage());
+ $result = $e;
}
+ CRM_Utils_Hook::postJob($job, $params, $result);
$this->logEntry('Finished execution of ' . $job->name . ' with result: ' . $this->_apiResultToMessage($result));
$this->currentJob = FALSE;
+
+ //Disable outBound option after executing the job.
+ $environment = CRM_Core_Config::environment(NULL, TRUE);
+ if ($environment != 'Production' && !empty($job->apiParams['runInNonProductionEnvironment'])) {
+ Civi::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED]);
+ }
}
/**
@@ -148,13 +167,13 @@ public function executeJob($job) {
* ($id => CRM_Core_ScheduledJob)
*/
private function _getJobs() {
- $jobs = array();
+ $jobs = [];
$dao = new CRM_Core_DAO_Job();
$dao->orderBy('name');
$dao->domain_id = CRM_Core_Config::domainID();
$dao->find();
while ($dao->fetch()) {
- $temp = array();
+ $temp = [];
CRM_Core_DAO::storeValues($dao, $temp);
$jobs[$dao->id] = new CRM_Core_ScheduledJob($temp);
}
@@ -209,10 +228,21 @@ public function logEntry($message) {
$dao = new CRM_Core_DAO_JobLog();
$dao->domain_id = $domainID;
- $dao->description = substr($message, 0, 235);
- if (strlen($message) > 235) {
- $dao->description .= " (...)";
+
+ /*
+ * The description is a summary of the message.
+ * HTML tags are stripped from the message.
+ * The description is limited to 240 characters
+ * and has an ellipsis added if it is truncated.
+ */
+ $maxDescription = 240;
+ $ellipsis = " (...)";
+ $description = strip_tags($message);
+ if (strlen($description) > $maxDescription) {
+ $description = substr($description, 0, $maxDescription - strlen($ellipsis)) . $ellipsis;
}
+ $dao->description = $description;
+
if ($this->currentJob) {
$dao->job_id = $this->currentJob->id;
$dao->name = $this->currentJob->name;
diff --git a/CRM/Core/Joomla.php b/CRM/Core/Joomla.php
index 3919a213f902..8305fa224166 100644
--- a/CRM/Core/Joomla.php
+++ b/CRM/Core/Joomla.php
@@ -1,9 +1,9 @@
_hasLock) {
- if (self::$jobLog && CRM_Core_DAO::singleValueQuery("SELECT IS_USED_LOCK( '" . self::$jobLog . "')")) {
+ if (!CRM_Utils_SQL::supportsMultipleLocks() && self::$jobLog && CRM_Core_DAO::singleValueQuery("SELECT IS_USED_LOCK( '" . self::$jobLog . "')")) {
return $this->hackyHandleBrokenCode(self::$jobLog);
}
$query = "SELECT GET_LOCK( %1, %2 )";
- $params = array(
- 1 => array($this->_id, 'String'),
- 2 => array($timeout ? $timeout : $this->_timeout, 'Integer'),
- );
+ $params = [
+ 1 => [$this->_id, 'String'],
+ 2 => [$timeout ? $timeout : $this->_timeout, 'Integer'],
+ ];
$res = CRM_Core_DAO::singleValueQuery($query, $params);
if ($res) {
if (defined('CIVICRM_LOCK_DEBUG')) {
@@ -220,7 +225,7 @@ public function release() {
}
$query = "SELECT RELEASE_LOCK( %1 )";
- $params = array(1 => array($this->_id, 'String'));
+ $params = [1 => [$this->_id, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
}
@@ -230,7 +235,7 @@ public function release() {
*/
public function isFree() {
$query = "SELECT IS_FREE_LOCK( %1 )";
- $params = array(1 => array($this->_id, 'String'));
+ $params = [1 => [$this->_id, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
diff --git a/CRM/Core/ManagedEntities.php b/CRM/Core/ManagedEntities.php
index 4de184a28c1b..a3883286963a 100644
--- a/CRM/Core/ManagedEntities.php
+++ b/CRM/Core/ManagedEntities.php
@@ -13,11 +13,11 @@ class CRM_Core_ManagedEntities {
* @return array
*/
public static function getCleanupOptions() {
- return array(
+ return [
'always' => ts('Always'),
'never' => ts('Never'),
'unused' => ts('If Unused'),
- );
+ ];
}
/**
@@ -55,7 +55,7 @@ public static function scheduleReconciliation() {
function () {
CRM_Core_ManagedEntities::singleton(TRUE)->reconcile();
},
- array(),
+ [],
'ManagedEntities::reconcile'
);
}
@@ -92,9 +92,9 @@ public function get($moduleName, $name) {
$dao->module = $moduleName;
$dao->name = $name;
if ($dao->find(TRUE)) {
- $params = array(
+ $params = [
'id' => $dao->entity_id,
- );
+ ];
$result = NULL;
try {
$result = civicrm_api3($dao->entity_type, 'getsingle', $params);
@@ -191,6 +191,7 @@ public function reconcileDisabledModules() {
$in = CRM_Core_DAO::escapeStrings(array_keys($this->moduleIndex[FALSE]));
$dao = new CRM_Core_DAO_Managed();
$dao->whereAdd("module in ($in)");
+ $dao->orderBy('id DESC');
$dao->find();
while ($dao->fetch()) {
$this->disableEntity($dao);
@@ -203,7 +204,7 @@ public function reconcileDisabledModules() {
* unknown modules.
*/
public function reconcileUnknownModules() {
- $knownModules = array();
+ $knownModules = [];
if (array_key_exists(0, $this->moduleIndex) && is_array($this->moduleIndex[0])) {
$knownModules = array_merge($knownModules, array_keys($this->moduleIndex[0]));
}
@@ -215,6 +216,7 @@ public function reconcileUnknownModules() {
if (!empty($knownModules)) {
$in = CRM_Core_DAO::escapeStrings($knownModules);
$dao->whereAdd("module NOT IN ($in)");
+ $dao->orderBy('id DESC');
}
$dao->find();
while ($dao->fetch()) {
@@ -255,10 +257,11 @@ public function updateExistingEntity($dao, $todo) {
$doUpdate = ($policy == 'always');
if ($doUpdate) {
- $defaults = array(
+ $defaults = [
'id' => $dao->entity_id,
- 'is_active' => 1, // FIXME: test whether is_active is valid
- );
+ // FIXME: test whether is_active is valid
+ 'is_active' => 1,
+ ];
$params = array_merge($defaults, $todo['params']);
$result = civicrm_api($dao->entity_type, 'create', $params);
if ($result['is_error']) {
@@ -282,11 +285,11 @@ public function disableEntity($dao) {
// FIXME: if ($dao->entity_type supports is_active) {
if (TRUE) {
// FIXME cascading for payproc types?
- $params = array(
+ $params = [
'version' => 3,
'id' => $dao->entity_id,
'is_active' => 0,
- );
+ ];
$result = civicrm_api($dao->entity_type, 'create', $params);
if ($result['is_error']) {
$this->onApiError($dao->entity_type, 'create', $params, $result);
@@ -312,10 +315,10 @@ public function removeStaleEntity($dao) {
break;
case 'unused':
- $getRefCount = civicrm_api3($dao->entity_type, 'getrefcount', array(
+ $getRefCount = civicrm_api3($dao->entity_type, 'getrefcount', [
'debug' => 1,
'id' => $dao->entity_id,
- ));
+ ]);
$total = 0;
foreach ($getRefCount['values'] as $refCount) {
@@ -330,18 +333,20 @@ public function removeStaleEntity($dao) {
}
if ($doDelete) {
- $params = array(
+ $params = [
'version' => 3,
'id' => $dao->entity_id,
- );
- $result = civicrm_api($dao->entity_type, 'delete', $params);
- if ($result['is_error']) {
- $this->onApiError($dao->entity_type, 'delete', $params, $result);
+ ];
+ $check = civicrm_api3($dao->entity_type, 'get', $params);
+ if ((bool) $check['count']) {
+ $result = civicrm_api($dao->entity_type, 'delete', $params);
+ if ($result['is_error']) {
+ $this->onApiError($dao->entity_type, 'delete', $params, $result);
+ }
}
-
- CRM_Core_DAO::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', array(
- 1 => array($dao->id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', [
+ 1 => [$dao->id, 'Integer'],
+ ]);
}
}
@@ -352,7 +357,7 @@ public function removeStaleEntity($dao) {
*/
public function getDeclarations() {
if ($this->declarations === NULL) {
- $this->declarations = array();
+ $this->declarations = [];
foreach (CRM_Core_Component::getEnabledComponents() as $component) {
/** @var CRM_Core_Component_Info $component */
$this->declarations = array_merge($this->declarations, $component->getManagedEntities());
@@ -371,7 +376,7 @@ public function getDeclarations() {
* indexed by is_active,name
*/
protected static function createModuleIndex($modules) {
- $result = array();
+ $result = [];
foreach ($modules as $module) {
$result[$module->is_active][$module->name] = $module;
}
@@ -386,14 +391,14 @@ protected static function createModuleIndex($modules) {
* indexed by module,name
*/
protected static function createDeclarationIndex($moduleIndex, $declarations) {
- $result = array();
+ $result = [];
if (!isset($moduleIndex[TRUE])) {
return $result;
}
foreach ($moduleIndex[TRUE] as $moduleName => $module) {
if ($module->is_active) {
// need an empty array() for all active modules, even if there are no current $declarations
- $result[$moduleName] = array();
+ $result[$moduleName] = [];
}
}
foreach ($declarations as $declaration) {
@@ -410,7 +415,7 @@ protected static function createDeclarationIndex($moduleIndex, $declarations) {
*/
protected static function validate($declarations) {
foreach ($declarations as $declare) {
- foreach (array('name', 'module', 'entity', 'params') as $key) {
+ foreach (['name', 'module', 'entity', 'params'] as $key) {
if (empty($declare[$key])) {
$str = print_r($declare, TRUE);
return ("Managed Entity is missing field \"$key\": $str");
@@ -444,12 +449,12 @@ protected static function cleanDeclarations($declarations) {
* @throws Exception
*/
protected function onApiError($entity, $action, $params, $result) {
- CRM_Core_Error::debug_var('ManagedEntities_failed', array(
+ CRM_Core_Error::debug_var('ManagedEntities_failed', [
'entity' => $entity,
'action' => $action,
'params' => $params,
'result' => $result,
- ));
+ ]);
throw new Exception('API error: ' . $result['error_message']);
}
diff --git a/CRM/Core/Menu.php b/CRM/Core/Menu.php
index 588bac05dbd4..796491120402 100644
--- a/CRM/Core/Menu.php
+++ b/CRM/Core/Menu.php
@@ -1,9 +1,9 @@
item as $item) {
if (!(string ) $item->path) {
CRM_Core_Error::debug('i', $item);
@@ -122,6 +132,19 @@ public static function read($name, &$menu) {
$path = (string ) $item->path;
$menu[$path] = array();
unset($item->path);
+
+ if ($item->ids_arguments) {
+ $ids = array();
+ foreach (array('json' => 'json', 'html' => 'html', 'exception' => 'exceptions') as $tag => $attr) {
+ $ids[$attr] = array();
+ foreach ($item->ids_arguments->{$tag} as $value) {
+ $ids[$attr][] = (string) $value;
+ }
+ }
+ $menu[$path]['ids_arguments'] = $ids;
+ unset($item->ids_arguments);
+ }
+
foreach ($item as $key => $value) {
$key = (string ) $key;
$value = (string ) $value;
@@ -284,7 +307,7 @@ public static function store($truncate = TRUE) {
self::build($menuArray);
- $config = CRM_Core_Config::singleton();
+ $daoFields = CRM_Core_DAO_Menu::fields();
foreach ($menuArray as $path => $item) {
$menu = new CRM_Core_DAO_Menu();
@@ -293,6 +316,21 @@ public static function store($truncate = TRUE) {
$menu->find(TRUE);
+ if (!CRM_Core_Config::isUpgradeMode() ||
+ CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
+ ) {
+ // Move unrecognized fields to $module_data.
+ $module_data = array();
+ foreach (array_keys($item) as $key) {
+ if (!isset($daoFields[$key])) {
+ $module_data[$key] = $item[$key];
+ unset($item[$key]);
+ }
+ }
+
+ $menu->module_data = serialize($module_data);
+ }
+
$menu->copyValues($item);
foreach (self::$_serializedElements as $element) {
@@ -329,13 +367,12 @@ public static function buildAdminLinks(&$menu) {
'title' => $item['title'],
'desc' => CRM_Utils_Array::value('desc', $item),
'id' => strtr($item['title'], array(
- '(' => '_',
- ')' => '',
- ' ' => '',
- ',' => '_',
- '/' => '_',
- )
- ),
+ '(' => '_',
+ ')' => '',
+ ' ' => '',
+ ',' => '_',
+ '/' => '_',
+ )),
'url' => CRM_Utils_System::url($path, $query,
FALSE,
NULL,
@@ -532,11 +569,16 @@ public static function buildBreadcrumb(&$menu, $path) {
'title' => $menu[$currentPath]['title'],
'url' => CRM_Utils_System::url($currentPath,
'reset=1' . $urlVar,
- FALSE, // absolute
- NULL, // fragment
- TRUE, // htmlize
- FALSE, // frontend
- TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
+ // absolute
+ FALSE,
+ // fragment
+ NULL,
+ // htmlize
+ TRUE,
+ // frontend
+ FALSE,
+ // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
+ TRUE
),
);
}
@@ -624,16 +666,16 @@ public static function fillComponentIds(&$menu, $path) {
}
/**
- * @param $path
+ * @param $path string
+ * Path of menu item to retrieve.
*
- * @return null
+ * @return array
+ * Menu entry array.
*/
public static function get($path) {
// return null if menu rebuild
$config = CRM_Core_Config::singleton();
- $params = array();
-
$args = explode('/', $path);
$elements = array();
@@ -646,22 +688,13 @@ public static function get($path) {
$queryString = implode(', ', $elements);
$domainID = CRM_Core_Config::domainID();
- $domainWhereClause = " AND domain_id = $domainID ";
- if ($config->isUpgradeMode() &&
- !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')
- ) {
- //domain_id wouldn't be available for earlier version of
- //3.0 and therefore can't be used as part of query for
- //upgrade case
- $domainWhereClause = "";
- }
$query = "
(
SELECT *
FROM civicrm_menu
WHERE path in ( $queryString )
- $domainWhereClause
+ AND domain_id = $domainID
ORDER BY length(path) DESC
LIMIT 1
)
@@ -673,7 +706,7 @@ public static function get($path) {
SELECT *
FROM civicrm_menu
WHERE path IN ( 'navigation' )
- $domainWhereClause
+ AND domain_id = $domainID
)
";
}
@@ -687,6 +720,14 @@ public static function get($path) {
self::$_menuCache[$menu->path] = array();
CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
+ // Move module_data into main item.
+ if (isset(self::$_menuCache[$menu->path]['module_data'])) {
+ CRM_Utils_Array::extend(self::$_menuCache[$menu->path],
+ unserialize(self::$_menuCache[$menu->path]['module_data']));
+ unset(self::$_menuCache[$menu->path]['module_data']);
+ }
+
+ // Unserialize other elements.
foreach (self::$_serializedElements as $element) {
self::$_menuCache[$menu->path][$element] = unserialize($menu->$element);
@@ -703,12 +744,6 @@ public static function get($path) {
}
}
- // *FIXME* : hack for 2.1 -> 2.2 upgrades.
- if ($path == 'civicrm/upgrade') {
- $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
- $menuPath['access_arguments'][0][] = 'administer CiviCRM';
- $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
- }
// *FIXME* : hack for 4.1 -> 4.2 upgrades.
if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
CRM_Queue_Menu::alter($path, $menuPath);
diff --git a/CRM/Core/Module.php b/CRM/Core/Module.php
index 9b824f8720be..f3976d1c8c78 100644
--- a/CRM/Core/Module.php
+++ b/CRM/Core/Module.php
@@ -1,9 +1,9 @@
getMapper()->getModules();
- $result[] = new CRM_Core_Module('civicrm', TRUE); // pseudo-module for core
+ // pseudo-module for core
+ $result[] = new CRM_Core_Module('civicrm', TRUE);
$config = CRM_Core_Config::singleton();
$result = array_merge($result, $config->userSystem->getModules());
@@ -87,7 +88,7 @@ public static function getAll($fresh = FALSE) {
* @see CRM_Extension_Manager::STATUS_DISABLED
*/
public static function collectStatuses($modules) {
- $statuses = array();
+ $statuses = [];
foreach ($modules as $module) {
$statuses[$module->name] = $module->is_active ? CRM_Extension_Manager::STATUS_INSTALLED : CRM_Extension_Manager::STATUS_DISABLED;
diff --git a/CRM/Core/OptionGroup.php b/CRM/Core/OptionGroup.php
index f4be86c75d36..913f874d50b6 100644
--- a/CRM/Core/OptionGroup.php
+++ b/CRM/Core/OptionGroup.php
@@ -1,9 +1,9 @@
fetch()) {
if ($flip) {
@@ -108,10 +109,11 @@ public static function &valuesCommon(
* ignore cache entries and go back to DB.
* @param string $keyColumnName
* the column to use for 'key'.
+ * @param string $orderBy
+ * the column to use for ordering.
*
* @return array
- * the values as specified by the above params
- * @void
+ * The values as specified by the params
*/
public static function &values(
$name, $flip = FALSE, $grouping = FALSE,
@@ -120,7 +122,7 @@ public static function &values(
$orderBy = 'weight'
) {
$cache = CRM_Utils_Cache::singleton();
- $cacheKey = self::createCacheKey($name, $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName);
+ $cacheKey = self::createCacheKey($name, $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName, $orderBy);
if (!$fresh) {
// Fetch from static var
@@ -128,9 +130,9 @@ public static function &values(
return self::$_cache[$cacheKey];
}
// Fetch from main cache
- $var = $cache->get($cacheKey);
- if ($var) {
- return $var;
+ self::$_cache[$cacheKey] = $cache->get($cacheKey);
+ if (self::$_cache[$cacheKey] !== NULL) {
+ return self::$_cache[$cacheKey];
}
}
@@ -144,6 +146,14 @@ public static function &values(
if ($onlyActive) {
$query .= " AND v.is_active = 1 ";
+ // Only show options for enabled components
+ $componentClause = ' v.component_id IS NULL ';
+ $enabledComponents = CRM_Core_Config::singleton()->enableComponents;
+ if ($enabledComponents) {
+ $enabledComponents = '"' . implode('","', $enabledComponents) . '"';
+ $componentClause .= " OR v.component_id IN (SELECT id FROM civicrm_component WHERE name IN ($enabledComponents)) ";
+ }
+ $query .= " AND ($componentClause) ";
}
if (in_array($name, self::$_domainIDGroups)) {
$query .= " AND v.domain_id = " . CRM_Core_Config::domainID();
@@ -155,7 +165,7 @@ public static function &values(
$query .= " ORDER BY v.{$orderBy}";
- $p = array(1 => array($name, 'String'));
+ $p = [1 => [$name, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $p);
$var = self::valuesCommon($dao, $flip, $grouping, $localize, $labelColumnName);
@@ -191,8 +201,8 @@ protected static function flushValues($name, $flip, $grouping, $localize, $condi
/**
* @return string
*/
- protected static function createCacheKey() {
- $cacheKey = "CRM_OG_" . serialize(func_get_args());
+ protected static function createCacheKey($id) {
+ $cacheKey = "CRM_OG_" . preg_replace('/[^a-zA-Z0-9]/', '', $id) . '_' . md5(serialize(func_get_args()));
return $cacheKey;
}
@@ -225,9 +235,9 @@ public static function &valuesByID($id, $flip = FALSE, $grouping = FALSE, $local
$cache = CRM_Utils_Cache::singleton();
if (!$fresh) {
- $var = $cache->get($cacheKey);
- if ($var) {
- return $var;
+ self::$_cache[$cacheKey] = $cache->get($cacheKey);
+ if (self::$_cache[$cacheKey] !== NULL) {
+ return self::$_cache[$cacheKey];
}
}
$query = "
@@ -243,7 +253,7 @@ public static function &valuesByID($id, $flip = FALSE, $grouping = FALSE, $local
}
$query .= " ORDER BY v.weight, v.label";
- $p = array(1 => array($id, 'Integer'));
+ $p = [1 => [$id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $p);
$var = self::valuesCommon($dao, $flip, $grouping, $localize, $labelColumnName);
@@ -253,9 +263,9 @@ public static function &valuesByID($id, $flip = FALSE, $grouping = FALSE, $local
}
/**
- * Lookup titles OR ids for a set of option_value populated fields. The retrieved value
- * is assigned a new fieldname by id or id's by title
- * (each within a specificied option_group)
+ * Lookup titles OR ids for a set of option_value populated fields. The
+ * retrieved value is assigned a new field name by id or id's by title
+ * (each within a specified option_group).
*
* @param array $params
* Reference array of values submitted by the form. Based on.
@@ -265,18 +275,17 @@ public static function &valuesByID($id, $flip = FALSE, $grouping = FALSE, $local
* If $flip = true, adds actual field name => id
*
* @param array $names
- * Reference array of fieldnames we want transformed.
+ * Array of field names we want transformed.
* Array key = 'postName' (field name submitted by form in $params).
* Array value = array('newName' => $newName, 'groupName' => $groupName).
*
- *
* @param bool $flip
*/
- public static function lookupValues(&$params, &$names, $flip = FALSE) {
+ public static function lookupValues(&$params, $names, $flip = FALSE) {
foreach ($names as $postName => $value) {
// See if $params field is in $names array (i.e. is a value that we need to lookup)
if ($postalName = CRM_Utils_Array::value($postName, $params)) {
- $postValues = array();
+ $postValues = [];
// params[$postName] may be a Ctrl+A separated value list
if (is_string($postalName) &&
strpos($postalName, CRM_Core_DAO::VALUE_SEPARATOR) == FALSE
@@ -290,24 +299,24 @@ public static function lookupValues(&$params, &$names, $flip = FALSE) {
elseif (is_array($postalName)) {
$postValues = $postalName;
}
- $newValue = array();
+ $newValue = [];
foreach ($postValues as $postValue) {
if (!$postValue) {
continue;
}
if ($flip) {
- $p = array(1 => array($postValue, 'String'));
+ $p = [1 => [$postValue, 'String']];
$lookupBy = 'v.label= %1';
$select = "v.value";
}
else {
- $p = array(1 => array($postValue, 'Integer'));
+ $p = [1 => [$postValue, 'Integer']];
$lookupBy = 'v.value = %1';
$select = "v.label";
}
- $p[2] = array($value['groupName'], 'String');
+ $p[2] = [$value['groupName'], 'String'];
$query = "
SELECT $select
FROM civicrm_option_value v,
@@ -334,6 +343,7 @@ public static function lookupValues(&$params, &$names, $flip = FALSE) {
* @return null
*/
public static function getLabel($groupName, $value, $onlyActiveValue = TRUE) {
+ CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_PseudoConstant::getLabel');
if (empty($groupName) ||
empty($value)
) {
@@ -352,10 +362,10 @@ public static function getLabel($groupName, $value, $onlyActiveValue = TRUE) {
if ($onlyActiveValue) {
$query .= " AND v.is_active = 1 ";
}
- $p = array(
- 1 => array($groupName, 'String'),
- 2 => array($value, 'Integer'),
- );
+ $p = [
+ 1 => [$groupName, 'String'],
+ 2 => [$value, 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $p);
if ($dao->fetch()) {
return $dao->label;
@@ -387,6 +397,8 @@ public static function getValue(
return NULL;
}
+ CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_PseudoConstant::getKey');
+
$query = "
SELECT v.label as label ,v.{$valueField} as value
FROM civicrm_option_value v,
@@ -398,10 +410,10 @@ public static function getValue(
AND v.$labelField = %2
";
- $p = array(
- 1 => array($groupName, 'String'),
- 2 => array($label, $labelType),
- );
+ $p = [
+ 1 => [$groupName, 'String'],
+ 2 => [$label, $labelType],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $p);
if ($dao->fetch()) {
$dao->free();
@@ -439,7 +451,7 @@ public static function getDefaultValue($groupName) {
$query .= " AND v.domain_id = " . CRM_Core_Config::domainID();
}
- $p = array(1 => array($groupName, 'String'));
+ $p = [1 => [$groupName, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $p);
}
@@ -518,23 +530,23 @@ public static function getAssoc($groupName, &$values, $flip = FALSE, $field = 'n
AND g.$field = %1
ORDER BY v.weight
";
- $params = array(1 => array($groupName, 'String'));
+ $params = [1 => [$groupName, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $fields = array('value', 'label', 'name', 'description', 'amount_id', 'weight');
+ $fields = ['value', 'label', 'name', 'description', 'amount_id', 'weight'];
if ($flip) {
- $values = array();
+ $values = [];
}
else {
foreach ($fields as $field) {
- $values[$field] = array();
+ $values[$field] = [];
}
}
$index = 1;
while ($dao->fetch()) {
if ($flip) {
- $value = array();
+ $value = [];
foreach ($fields as $field) {
$value[$field] = $dao->$field;
}
@@ -561,7 +573,7 @@ public static function deleteAssoc($groupName, $operator = "=") {
WHERE g.id = v.option_group_id
AND g.name {$operator} %1";
- $params = array(1 => array($groupName, 'String'));
+ $params = [1 => [$groupName, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
}
@@ -595,24 +607,24 @@ public static function getRowValues(
$query .= " AND v.is_active = 1";
}
- $p = array(
- 1 => array($groupName, 'String'),
- 2 => array($fieldValue, $fieldType),
- );
+ $p = [
+ 1 => [$groupName, 'String'],
+ 2 => [$fieldValue, $fieldType],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $p);
- $row = array();
+ $row = [];
if ($dao->fetch()) {
- foreach (array(
- 'id',
- 'name',
- 'value',
- 'label',
- 'weight',
- 'description',
- ) as $fld) {
+ foreach ([
+ 'id',
+ 'name',
+ 'value',
+ 'label',
+ 'weight',
+ 'description',
+ ] as $fld) {
$row[$fld] = $dao->$fld;
- if ($localize && in_array($fld, array('label', 'description'))) {
+ if ($localize && in_array($fld, ['label', 'description'])) {
$row[$fld] = ts($row[$fld]);
}
}
@@ -633,14 +645,14 @@ public static function getRowValues(
* @param string $name
* @param array $params
*/
- public static function flush($name, $params = array()) {
- $defaults = array(
+ public static function flush($name, $params = []) {
+ $defaults = [
'flip' => FALSE,
'grouping' => FALSE,
'localize' => FALSE,
'condition' => NULL,
'labelColumnName' => 'label',
- );
+ ];
$params = array_merge($defaults, $params);
self::flushValues(
@@ -665,9 +677,15 @@ public static function flush($name, $params = array()) {
);
}
+ /**
+ * Flush all the places where option values are cached.
+ *
+ * Note that this is called from CRM_Core_PseudoConstant::flush() so we should resist
+ * the intuitive urge to flush that class.
+ */
public static function flushAll() {
- self::$_values = array();
- self::$_cache = array();
+ self::$_values = [];
+ self::$_cache = [];
CRM_Utils_Cache::singleton()->flush();
}
diff --git a/CRM/Core/OptionValue.php b/CRM/Core/OptionValue.php
index df4a386029b7..ed649405cd60 100644
--- a/CRM/Core/OptionValue.php
+++ b/CRM/Core/OptionValue.php
@@ -1,9 +1,9 @@
id;
+ $isGroupLocked = (bool) $optionGroup->is_locked;
}
}
else {
@@ -116,7 +116,7 @@ public static function getRows($groupParams, $links, $orderBy = 'weight', $skipE
$componentNames = CRM_Core_Component::getNames();
$visibilityLabels = CRM_Core_PseudoConstant::visibility();
while ($dao->fetch()) {
- $optionValue[$dao->id] = array();
+ $optionValue[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $optionValue[$dao->id]);
if (!empty($optionValue[$dao->id]['component_id']) &&
empty($componentNames[$optionValue[$dao->id]['component_id']]) &&
@@ -146,14 +146,20 @@ public static function getRows($groupParams, $links, $orderBy = 'weight', $skipE
}
}
+ // disallow deletion of option values for locked groups
+ if (($action & CRM_Core_Action::DELETE) && $isGroupLocked) {
+ $action -= CRM_Core_Action::DELETE;
+ }
+
$optionValue[$dao->id]['label'] = htmlspecialchars($optionValue[$dao->id]['label']);
$optionValue[$dao->id]['order'] = $optionValue[$dao->id]['weight'];
+ $optionValue[$dao->id]['icon'] = CRM_Utils_Array::value('icon', $optionValue[$dao->id], '');
$optionValue[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
- array(
+ [
'id' => $dao->id,
'gid' => $optionGroupID,
'value' => $dao->value,
- ),
+ ],
ts('more'),
FALSE,
'optionValue.row.actions',
@@ -181,7 +187,7 @@ public static function getRows($groupParams, $links, $orderBy = 'weight', $skipE
*
* @param array $params
* Array containing exported values from the invoking form.
- * @param array $groupParams
+ * @param string $optionGroupName
* Array containing group fields whose option-values is to retrieved/saved.
* @param $action
* @param int $optionValueID Has the id of the optionValue being edited, disabled ..etc.
@@ -190,23 +196,17 @@ public static function getRows($groupParams, $links, $orderBy = 'weight', $skipE
* @return CRM_Core_DAO_OptionValue
*
*/
- public static function addOptionValue(&$params, &$groupParams, &$action, &$optionValueID) {
- $ids = array();
+ public static function addOptionValue(&$params, $optionGroupName, $action, $optionValueID) {
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
// checking if the group name with the given id or name (in $groupParams) exists
- if (!empty($groupParams)) {
- $config = CRM_Core_Config::singleton();
- $groupParams['is_active'] = 1;
- $optionGroup = CRM_Core_BAO_OptionGroup::retrieve($groupParams, $defaults);
- }
+ $groupParams = ['name' => $optionGroupName, 'is_active' => 1];
+ $optionGroup = CRM_Core_BAO_OptionGroup::retrieve($groupParams, $defaults);
- // if the corresponding group doesn't exist, create one, provided $groupParams has 'name' in it.
+ // if the corresponding group doesn't exist, create one.
if (!$optionGroup->id) {
- if ($groupParams['name']) {
- $newOptionGroup = CRM_Core_BAO_OptionGroup::add($groupParams, $defaults);
- $params['weight'] = 1;
- $optionGroupID = $newOptionGroup->id;
- }
+ $newOptionGroup = CRM_Core_BAO_OptionGroup::add($groupParams);
+ $params['weight'] = 1;
+ $optionGroupID = $newOptionGroup->id;
}
else {
$optionGroupID = $optionGroup->id;
@@ -214,13 +214,13 @@ public static function addOptionValue(&$params, &$groupParams, &$action, &$optio
if ($optionValueID) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'weight', 'id');
}
- $fieldValues = array('option_group_id' => $optionGroupID);
+ $fieldValues = ['option_group_id' => $optionGroupID];
$params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues);
}
$params['option_group_id'] = $optionGroupID;
- if (($action & CRM_Core_Action::ADD) && empty($params['value'])) {
- $fieldValues = array('option_group_id' => $optionGroupID);
+ if (($action & CRM_Core_Action::ADD) && !isset($params['value'])) {
+ $fieldValues = ['option_group_id' => $optionGroupID];
// use the next available value
/* CONVERT(value, DECIMAL) is used to convert varchar
field 'value' to decimal->integer */
@@ -239,9 +239,9 @@ public static function addOptionValue(&$params, &$groupParams, &$action, &$optio
$params['name'] = $params['label'];
}
if ($action & CRM_Core_Action::UPDATE) {
- $ids['optionValue'] = $optionValueID;
+ $params['id'] = $optionValueID;
}
- $optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
+ $optionValue = CRM_Core_BAO_OptionValue::add($params);
return $optionValue;
}
@@ -258,15 +258,24 @@ public static function addOptionValue(&$params, &$groupParams, &$action, &$optio
* @param int $optionGroupID
* @param string $fieldName
* The name of the field in the DAO.
+ * @param bool $domainSpecific
+ * Filter this check to the current domain.
+ * Some optionGroups allow for same labels or same names but
+ * they must be in different domains, so filter the check to
+ * the current domain.
*
* @return bool
* true if object exists
*/
- public static function optionExists($value, $daoName, $daoID, $optionGroupID, $fieldName = 'name') {
+ public static function optionExists($value, $daoName, $daoID, $optionGroupID, $fieldName = 'name', $domainSpecific) {
$object = new $daoName();
$object->$fieldName = $value;
$object->option_group_id = $optionGroupID;
+ if ($domainSpecific) {
+ $object->domain_id = CRM_Core_Config::domainID();
+ }
+
if ($object->find(TRUE)) {
return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
}
@@ -286,7 +295,7 @@ public static function optionExists($value, $daoName, $daoID, $optionGroupID, $f
public static function getFields($mode = '', $contactType = 'Individual') {
$key = "$mode $contactType";
if (empty(self::$_fields[$key]) || !self::$_fields[$key]) {
- self::$_fields[$key] = array();
+ self::$_fields[$key] = [];
$option = CRM_Core_DAO_OptionValue::import();
@@ -294,44 +303,48 @@ public static function getFields($mode = '', $contactType = 'Individual') {
$optionName = $option[$id];
}
- $nameTitle = array();
+ $nameTitle = [];
if ($mode == 'contribute') {
- $nameTitle = array(
- 'payment_instrument' => array(
+ // This is part of a move towards standardising option values but we
+ // should derive them from the fields array so am deprecating it again...
+ // note that the reason this was needed was that payment_instrument_id was
+ // not set to exportable.
+ $nameTitle = [
+ 'payment_instrument' => [
'name' => 'payment_instrument',
'title' => ts('Payment Method'),
'headerPattern' => '/^payment|(p(ayment\s)?instrument)$/i',
- ),
- );
+ ],
+ ];
}
elseif ($mode == '') {
//the fields email greeting and postal greeting are meant only for Individual and Household
//the field addressee is meant for all contact types, CRM-4575
- if (in_array($contactType, array(
+ if (in_array($contactType, [
'Individual',
'Household',
'Organization',
'All',
- ))) {
- $nameTitle = array(
- 'addressee' => array(
+ ])) {
+ $nameTitle = [
+ 'addressee' => [
'name' => 'addressee',
'title' => ts('Addressee'),
'headerPattern' => '/^addressee$/i',
- ),
- );
- $title = array(
- 'email_greeting' => array(
+ ],
+ ];
+ $title = [
+ 'email_greeting' => [
'name' => 'email_greeting',
'title' => ts('Email Greeting'),
'headerPattern' => '/^email_greeting$/i',
- ),
- 'postal_greeting' => array(
+ ],
+ 'postal_greeting' => [
'name' => 'postal_greeting',
'title' => ts('Postal Greeting'),
'headerPattern' => '/^postal_greeting$/i',
- ),
- );
+ ],
+ ];
$nameTitle = array_merge($nameTitle, $title);
}
}
@@ -426,7 +439,7 @@ public static function getValues($groupParams, &$values, $orderBy = 'weight', $i
if ($groupId) {
$where .= " AND option_group.id = %1";
- $params[1] = array($groupId, 'Integer');
+ $params[1] = [$groupId, 'Integer'];
if (!$groupName) {
$groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
$groupId, 'name', 'id'
@@ -436,7 +449,7 @@ public static function getValues($groupParams, &$values, $orderBy = 'weight', $i
if ($groupName) {
$where .= " AND option_group.name = %2";
- $params[2] = array($groupName, 'String');
+ $params[2] = [$groupName, 'String'];
}
if (in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups)) {
@@ -448,7 +461,7 @@ public static function getValues($groupParams, &$values, $orderBy = 'weight', $i
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
- $values[$dao->id] = array(
+ $values[$dao->id] = [
'id' => $dao->id,
'label' => $dao->label,
'value' => $dao->value,
@@ -457,7 +470,7 @@ public static function getValues($groupParams, &$values, $orderBy = 'weight', $i
'weight' => $dao->weight,
'is_active' => $dao->is_active,
'is_default' => $dao->is_default,
- );
+ ];
}
}
diff --git a/CRM/Core/Page.php b/CRM/Core/Page.php
index a60d276c5187..e8908fea50f1 100644
--- a/CRM/Core/Page.php
+++ b/CRM/Core/Page.php
@@ -1,9 +1,9 @@
_print = CRM_Core_Smarty::PRINT_NOFORM;
}
// Support 'json' as well as legacy value '6'
- elseif (in_array($_REQUEST['snippet'], array(CRM_Core_Smarty::PRINT_JSON, 6))) {
+ elseif (in_array($_REQUEST['snippet'], [CRM_Core_Smarty::PRINT_JSON, 6])) {
$this->_print = CRM_Core_Smarty::PRINT_JSON;
}
else {
@@ -177,12 +177,12 @@ public function run() {
CRM_Utils_Hook::pageRun($this);
if ($this->_print) {
- if (in_array($this->_print, array(
+ if (in_array($this->_print, [
CRM_Core_Smarty::PRINT_SNIPPET,
CRM_Core_Smarty::PRINT_PDF,
CRM_Core_Smarty::PRINT_NOFORM,
CRM_Core_Smarty::PRINT_JSON,
- ))) {
+ ])) {
$content = self::$_template->fetch('CRM/common/snippet.tpl');
}
else {
@@ -199,7 +199,7 @@ public function run() {
if ($this->_print == CRM_Core_Smarty::PRINT_PDF) {
CRM_Utils_PDF_Utils::html2pdf($content, "{$this->_name}.pdf", FALSE,
- array('paper_size' => 'a3', 'orientation' => 'landscape')
+ ['paper_size' => 'a3', 'orientation' => 'landscape']
);
}
elseif ($this->_print == CRM_Core_Smarty::PRINT_JSON) {
@@ -317,10 +317,10 @@ public function reset() {
public function getTemplateFileName() {
return strtr(
CRM_Utils_System::getClassName($this),
- array(
+ [
'_' => DIRECTORY_SEPARATOR,
'\\' => DIRECTORY_SEPARATOR,
- )
+ ]
) . '.tpl';
}
@@ -406,4 +406,28 @@ public function setVar($name, $value) {
$this->$name = $value;
}
+ /**
+ * Assign metadata about fields to the template.
+ *
+ * In order to allow the template to format fields we assign information about them to the template.
+ *
+ * At this stage only date field metadata is assigned as that is the only use-case in play and
+ * we don't want to assign a lot of unneeded data.
+ *
+ * @param string $entity
+ * The entity being queried.
+ *
+ * @throws \CiviCRM_API3_Exception
+ */
+ protected function assignFieldMetadataToTemplate($entity) {
+ $fields = civicrm_api3($entity, 'getfields', ['action' => 'get']);
+ $dateFields = [];
+ foreach ($fields['values'] as $fieldName => $fieldMetaData) {
+ if (isset($fieldMetaData['html']) && CRM_Utils_Array::value('type', $fieldMetaData['html']) == 'Select Date') {
+ $dateFields[$fieldName] = CRM_Utils_Date::addDateMetadataToField($fieldMetaData, $fieldMetaData);
+ }
+ }
+ $this->assign('fields', $dateFields);
+ }
+
}
diff --git a/CRM/Core/Page/AJAX.php b/CRM/Core/Page/AJAX.php
index 5830a624cf5f..2f11ee1c9d6f 100644
--- a/CRM/Core/Page/AJAX.php
+++ b/CRM/Core/Page/AJAX.php
@@ -1,9 +1,9 @@
$className)));
+ CRM_Core_Error::fatal(ts('Invalid className: %1', [1 => $className]));
}
$fnName = NULL;
@@ -64,7 +64,7 @@ public static function run() {
switch ($type) {
case 'method':
- call_user_func(array($className, $fnName));
+ call_user_func([$className, $fnName]);
break;
case 'page':
@@ -98,31 +98,28 @@ public static function setIsQuickConfig() {
$id = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
}
- if (!empty($_REQUEST['context'])) {
- $context = CRM_Utils_Type::escape($_REQUEST['context'], 'String');
- }
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
+
// return false if $id is null and
// $context is not civicrm_event or civicrm_contribution_page
- if (!$id || !in_array($context, array('civicrm_event', 'civicrm_contribution_page'))) {
+ if (!$id || !in_array($context, ['civicrm_event', 'civicrm_contribution_page'])) {
return FALSE;
}
$priceSetId = CRM_Price_BAO_PriceSet::getFor($context, $id, NULL);
if ($priceSetId) {
- $result = CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetId, 0);
+ $sql = "UPDATE
+ civicrm_price_set cps
+ INNER JOIN civicrm_price_set_entity cpse ON cps.id = cpse.price_set_id
+ INNER JOIN {$context} ce ON cpse.entity_id = ce.id AND ce.id = %1
+ SET cps.is_quick_config = 0, cps.financial_type_id = IF(cps.financial_type_id IS NULL, ce.financial_type_id, cps.financial_type_id)
+ ";
+ CRM_Core_DAO::executeQuery($sql, [1 => [$id, 'Integer']]);
+
if ($context == 'civicrm_event') {
- $sql = "UPDATE
- civicrm_price_set cps
- INNER JOIN civicrm_discount cd ON cd.price_set_id = cps.id
- SET cps.is_quick_config = 0
- WHERE cd.entity_id = (%1) AND cd.entity_table = 'civicrm_event' ";
- $params = array(1 => array($id, 'Integer'));
- CRM_Core_DAO::executeQuery($sql, $params);
CRM_Core_BAO_Discount::del($id, $context);
}
}
- if (!$result) {
- $priceSetId = NULL;
- }
+
CRM_Utils_JSON::output($priceSetId);
}
@@ -171,15 +168,15 @@ public static function checkAuthz($type, $className, $fnName = NULL) {
public static function returnJsonResponse($response) {
// Allow lazy callers to not wrap content in an array
if (is_string($response)) {
- $response = array('content' => $response);
+ $response = ['content' => $response];
}
// Add session variables to response
$session = CRM_Core_Session::singleton();
- $response += array(
+ $response += [
'status' => 'success',
'userContext' => htmlspecialchars_decode($session->readUserContext()),
'title' => CRM_Utils_System::$title,
- );
+ ];
// crmMessages will be automatically handled by our ajax preprocessor
// @see js/Common.js
if ($session->getStatus(FALSE)) {
@@ -214,12 +211,22 @@ public static function setJsHeaders($ttl = NULL) {
CRM_Utils_System::setHttpHeader('Cache-Control', "max-age=$ttl, public");
}
+ /**
+ * Set defaults for sort and pager.
+ *
+ * @param int $defaultOffset
+ * @param int $defaultRowCount
+ * @param string $defaultSort
+ * @param string $defaultsortOrder
+ *
+ * @return array
+ */
public static function defaultSortAndPagerParams($defaultOffset = 0, $defaultRowCount = 25, $defaultSort = NULL, $defaultsortOrder = 'asc') {
- $params = array(
- '_raw_values' => array(),
- );
+ $params = [
+ '_raw_values' => [],
+ ];
- $sortMapper = array();
+ $sortMapper = [];
if (isset($_GET['columns'])) {
foreach ($_GET['columns'] as $key => $value) {
$sortMapper[$key] = CRM_Utils_Type::validate($value['data'], 'MysqlColumnNameOrAlias');
@@ -246,8 +253,16 @@ public static function defaultSortAndPagerParams($defaultOffset = 0, $defaultRow
return $params;
}
- public static function validateParams($requiredParams = array(), $optionalParams = array()) {
- $params = array();
+ /**
+ * Validate ajax input parameters.
+ *
+ * @param array $requiredParams
+ * @param array $optionalParams
+ *
+ * @return array
+ */
+ public static function validateParams($requiredParams = [], $optionalParams = []) {
+ $params = [];
foreach ($requiredParams as $param => $type) {
$params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type);
@@ -255,7 +270,14 @@ public static function validateParams($requiredParams = array(), $optionalParams
foreach ($optionalParams as $param => $type) {
if (CRM_Utils_Array::value($param, $_GET)) {
- $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type);
+ if (!is_array($_GET[$param])) {
+ $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type);
+ }
+ else {
+ foreach ($_GET[$param] as $index => $value) {
+ $params[$param][$index] = CRM_Utils_Type::validate($value, $type);
+ }
+ }
}
}
diff --git a/CRM/Core/Page/AJAX/Attachment.php b/CRM/Core/Page/AJAX/Attachment.php
index 169cb5159a1d..69b9c3c397b7 100644
--- a/CRM/Core/Page/AJAX/Attachment.php
+++ b/CRM/Core/Page/AJAX/Attachment.php
@@ -1,9 +1,9 @@
$file) {
if (!$config->debug && !self::checkToken($post['crm_attachment_token'])) {
require_once 'api/v3/utils.php';
$results[$key] = civicrm_api3_create_error("SECURITY ALERT: Attaching files via AJAX requires a recent, valid token.",
- array(
+ [
'IP' => $server['REMOTE_ADDR'],
'level' => 'security',
'referer' => $server['HTTP_REFERER'],
'reason' => 'CSRF suspected',
- )
+ ]
);
}
elseif ($file['error']) {
@@ -85,14 +86,14 @@ public static function _attachFile($post, $files, $server) {
// We want check_permissions=1 while creating the DB record and check_permissions=0 while moving upload,
// so split the work across two api calls.
- $params = array();
+ $params = [];
if (isset($file['name'])) {
$params['name'] = $file['name'];
}
if (isset($file['type'])) {
$params['mime_type'] = $file['type'];
}
- foreach (array('entity_table', 'entity_id', 'description') as $field) {
+ foreach (['entity_table', 'entity_id', 'description'] as $field) {
if (isset($post[$field])) {
$params[$field] = $post[$field];
}
@@ -103,12 +104,12 @@ public static function _attachFile($post, $files, $server) {
$results[$key] = civicrm_api('Attachment', 'create', $params);
if (!$results[$key]['is_error']) {
- $moveParams = array(
+ $moveParams = [
'id' => $results[$key]['id'],
'version' => 3,
'options.move-file' => $file['tmp_name'],
// note: in this second call, check_permissions==false
- );
+ ];
$moveResult = civicrm_api('Attachment', 'create', $moveParams);
if ($moveResult['is_error']) {
$results[$key] = $moveResult;
@@ -149,12 +150,12 @@ public static function sendResponse($result) {
* @return string
*/
public static function createToken() {
- $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
+ $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), ['for', 'ts']);
$ts = CRM_Utils_Time::getTimeRaw();
- return $signer->sign(array(
+ return $signer->sign([
'for' => 'crmAttachment',
'ts' => $ts,
- )) . ';;;' . $ts;
+ ]) . ';;;' . $ts;
}
/**
@@ -166,14 +167,14 @@ public static function createToken() {
*/
public static function checkToken($token) {
list ($signature, $ts) = explode(';;;', $token);
- $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
+ $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), ['for', 'ts']);
if (!is_numeric($ts) || CRM_Utils_Time::getTimeRaw() > $ts + self::ATTACHMENT_TOKEN_TTL) {
return FALSE;
}
- return $signer->validate($signature, array(
+ return $signer->validate($signature, [
'for' => 'crmAttachment',
'ts' => $ts,
- ));
+ ]);
}
}
diff --git a/CRM/Core/Page/AJAX/Location.php b/CRM/Core/Page/AJAX/Location.php
index 4d128c122886..7a998fe2a523 100644
--- a/CRM/Core/Page/AJAX/Location.php
+++ b/CRM/Core/Page/AJAX/Location.php
@@ -1,9 +1,9 @@
get('userID'));
+ ->get('userID'));
if (empty($user) || (CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE) && !CRM_Contact_BAO_Contact_Permission::validateChecksumContact($user, CRM_Core_DAO::$_nullObject, FALSE))
) {
CRM_Utils_System::civiExit();
@@ -63,8 +63,8 @@ public static function getPermissionedLocation() {
CRM_Utils_System::civiExit();
}
- $values = array();
- $entityBlock = array('contact_id' => $cid);
+ $values = [];
+ $entityBlock = ['contact_id' => $cid];
$location = CRM_Core_BAO_Location::getValues($entityBlock);
$config = CRM_Core_Config::singleton();
@@ -79,30 +79,30 @@ public static function getPermissionedLocation() {
if (is_array($values) && !empty($values)) {
$locType = $values[1]['location_type_id'];
if ($fld == 'email') {
- $elements["onbehalf_{$fld}-{$locType}"] = array(
+ $elements["onbehalf_{$fld}-{$locType}"] = [
'type' => 'Text',
'value' => $location[$fld][1][$fld],
- );
+ ];
unset($profileFields["{$fld}-{$locType}"]);
}
elseif ($fld == 'phone') {
$phoneTypeId = $values[1]['phone_type_id'];
- $elements["onbehalf_{$fld}-{$locType}-{$phoneTypeId}"] = array(
+ $elements["onbehalf_{$fld}-{$locType}-{$phoneTypeId}"] = [
'type' => 'Text',
'value' => $location[$fld][1][$fld],
- );
+ ];
unset($profileFields["{$fld}-{$locType}-{$phoneTypeId}"]);
}
elseif ($fld == 'im') {
$providerId = $values[1]['provider_id'];
- $elements["onbehalf_{$fld}-{$locType}"] = array(
+ $elements["onbehalf_{$fld}-{$locType}"] = [
'type' => 'Text',
'value' => $location[$fld][1][$fld],
- );
- $elements["onbehalf_{$fld}-{$locType}provider_id"] = array(
+ ];
+ $elements["onbehalf_{$fld}-{$locType}provider_id"] = [
'type' => 'Select',
'value' => $location[$fld][1]['provider_id'],
- );
+ ];
unset($profileFields["{$fld}-{$locType}-{$providerId}"]);
}
}
@@ -111,49 +111,50 @@ public static function getPermissionedLocation() {
if (!empty($website)) {
foreach ($website as $key => $val) {
$websiteTypeId = $values[1]['website_type_id'];
- $elements["onbehalf_url-1"] = array(
+ $elements["onbehalf_url-1"] = [
'type' => 'Text',
'value' => $website[1]['url'],
- );
- $elements["onbehalf_url-1-website_type_id"] = array(
+ ];
+ $elements["onbehalf_url-1-website_type_id"] = [
'type' => 'Select',
'value' => $website[1]['website_type_id'],
- );
+ ];
unset($profileFields["url-1"]);
}
}
$locTypeId = isset($location['address'][1]) ? $location['address'][1]['location_type_id'] : NULL;
- $addressFields = array(
+ $addressFields = [
'street_address',
'supplemental_address_1',
'supplemental_address_2',
+ 'supplemental_address_3',
'city',
'postal_code',
'county',
'state_province',
'country',
- );
+ ];
foreach ($addressFields as $field) {
if (array_key_exists($field, $addressSequence)) {
$addField = $field;
$type = 'Text';
- if (in_array($field, array('state_province', 'country', 'county'))) {
+ if (in_array($field, ['state_province', 'country', 'county'])) {
$addField = "{$field}_id";
$type = 'Select';
}
- $elements["onbehalf_{$field}-{$locTypeId}"] = array(
+ $elements["onbehalf_{$field}-{$locTypeId}"] = [
'type' => $type,
'value' => isset($location['address'][1]) ? CRM_Utils_Array::value($addField,
$location['address'][1]) : NULL,
- );
+ ];
unset($profileFields["{$field}-{$locTypeId}"]);
}
}
//set custom field defaults
- $defaults = array();
+ $defaults = [];
CRM_Core_BAO_UFGroup::setProfileDefaults($cid, $profileFields, $defaults, TRUE, NULL, NULL, TRUE);
if (!empty($defaults)) {
@@ -170,7 +171,7 @@ public static function getPermissionedLocation() {
$elements["onbehalf_{$key}"]['value'][$k] = $v;
}
}
- elseif (strstr($htmlType, 'Multi-Select') && $htmlType != 'AdvMulti-Select') {
+ elseif (strstr($htmlType, 'Multi-Select')) {
$elements["onbehalf_{$key}"]['type'] = 'Multi-Select';
$elements["onbehalf_{$key}"]['value'] = array_values($defaults[$key]);
}
@@ -209,32 +210,31 @@ public static function getLocBlock() {
// i wish i could retrieve loc block info based on loc_block_id,
// Anyway, lets retrieve an event which has loc_block_id set to 'lbid'.
if ($_REQUEST['lbid']) {
- $params = array('1' => array($_REQUEST['lbid'], 'Integer'));
+ $params = ['1' => [$_REQUEST['lbid'], 'Integer']];
$eventId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_event WHERE loc_block_id=%1 LIMIT 1', $params);
}
// now lets use the event-id obtained above, to retrieve loc block information.
if ($eventId) {
- $params = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
// second parameter is of no use, but since required, lets use the same variable.
$location = CRM_Core_BAO_Location::getValues($params, $params);
}
- $result = array();
+ $result = [];
$addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'address_options', TRUE, NULL, TRUE
);
// lets output only required fields.
foreach ($addressOptions as $element => $isSet) {
- if ($isSet && (!in_array($element, array(
- 'im',
- 'openid',
- )))
- ) {
- if (in_array($element, array(
+ if ($isSet && (!in_array($element, [
+ 'im',
+ 'openid',
+ ]))) {
+ if (in_array($element, [
'country',
'state_province',
'county',
- ))) {
+ ])) {
$element .= '_id';
}
elseif ($element == 'address_name') {
@@ -243,29 +243,29 @@ public static function getLocBlock() {
$fld = "address[1][{$element}]";
$value = CRM_Utils_Array::value($element, $location['address'][1]);
$value = $value ? $value : "";
- $result[str_replace(array(
+ $result[str_replace([
'][',
'[',
"]",
- ), array('_', '_', ''), $fld)] = $value;
+ ], ['_', '_', ''], $fld)] = $value;
}
}
- foreach (array(
- 'email',
- 'phone_type_id',
- 'phone',
- ) as $element) {
+ foreach ([
+ 'email',
+ 'phone_type_id',
+ 'phone',
+ ] as $element) {
$block = ($element == 'phone_type_id') ? 'phone' : $element;
for ($i = 1; $i < 3; $i++) {
$fld = "{$block}[{$i}][{$element}]";
$value = CRM_Utils_Array::value($element, $location[$block][$i]);
$value = $value ? $value : "";
- $result[str_replace(array(
+ $result[str_replace([
'][',
'[',
"]",
- ), array('_', '_', ''), $fld)] = $value;
+ ], ['_', '_', ''], $fld)] = $value;
}
}
diff --git a/CRM/Core/Page/AJAX/RecurringEntity.php b/CRM/Core/Page/AJAX/RecurringEntity.php
index 7265eeda26c6..198b22c33ed0 100644
--- a/CRM/Core/Page/AJAX/RecurringEntity.php
+++ b/CRM/Core/Page/AJAX/RecurringEntity.php
@@ -13,35 +13,24 @@
class CRM_Core_Page_AJAX_RecurringEntity {
public static function updateMode() {
- $finalResult = array();
+ $finalResult = [];
if (CRM_Utils_Array::value('mode', $_REQUEST) && CRM_Utils_Array::value('entityId', $_REQUEST) && CRM_Utils_Array::value('entityTable', $_REQUEST)) {
-
$mode = CRM_Utils_Type::escape($_REQUEST['mode'], 'Integer');
$entityId = CRM_Utils_Type::escape($_REQUEST['entityId'], 'Integer');
$entityTable = CRM_Utils_Type::escape($_REQUEST['entityTable'], 'String');
+ $priceSet = CRM_Utils_Type::escape($_REQUEST['priceSet'], 'String');
- if (!empty($_REQUEST['linkedEntityTable'])) {
- $result = CRM_Core_BAO_RecurringEntity::updateModeLinkedEntity($entityId, $_REQUEST['linkedEntityTable'], $entityTable);
- }
-
- $dao = new CRM_Core_DAO_RecurringEntity();
- if (!empty($result)) {
- $dao->entity_id = $result['entityId'];
- $dao->entity_table = $result['entityTable'];
- }
- else {
- $dao->entity_id = $entityId;
- $dao->entity_table = $entityTable;
- }
-
- if ($dao->find(TRUE)) {
- $dao->mode = $mode;
- $dao->save();
- $finalResult['status'] = 'Done';
- }
- else {
- $finalResult['status'] = 'Error';
+ // CRM-21764 fix
+ // Retrieving existing priceset if price set id is not passed
+ if ($priceSet == "") {
+ $priceSetEntity = new CRM_Price_DAO_PriceSetEntity();
+ $priceSetEntity->entity_id = $entityId;
+ $priceSetEntity->entity_table = $entityTable;
+ $priceSetEntity->find(TRUE);
+ $priceSet = $priceSetEntity->price_set_id;
}
+ $linkedEntityTable = $_REQUEST['linkedEntityTable'];
+ $finalResult = CRM_Core_BAO_RecurringEntity::updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet);
}
CRM_Utils_JSON::output($finalResult);
}
diff --git a/CRM/Core/Page/Basic.php b/CRM/Core/Page/Basic.php
index 886167b9c1c4..aeeaa199f3e6 100644
--- a/CRM/Core/Page/Basic.php
+++ b/CRM/Core/Page/Basic.php
@@ -1,9 +1,9 @@
2) ? func_get_arg(2) : NULL;
// what action do we want to perform ? (store it for smarty too.. :)
- $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
- $this->assign('action', $this->_action);
-
- // get 'id' if present
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
-
- require_once str_replace('_', DIRECTORY_SEPARATOR, $this->getBAOName()) . ".php";
-
- if ($id) {
- if (!$this->checkPermission($id, NULL)) {
- CRM_Core_Error::fatal(ts('You do not have permission to make changes to the record'));
- }
- }
+ $id = $this->getIdAndAction();
if ($this->_action & (CRM_Core_Action::VIEW |
CRM_Core_Action::ADD |
@@ -175,6 +163,36 @@ public function run() {
return parent::run();
}
+ /**
+ * Retrieve the action and ID from the request.
+ *
+ * Action is assigned to the template while we're at it. This is pulled from
+ * the `run()` method above.
+ *
+ * @return int
+ * The ID if present, or 0.
+ * @throws \CRM_Core_Exception
+ */
+ public function getIdAndAction() {
+ $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
+ $this->assign('action', $this->_action);
+
+ $this->assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'Alphanumeric', $this));
+
+ // get 'id' if present
+ $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
+
+ require_once str_replace('_', DIRECTORY_SEPARATOR, $this->getBAOName()) . ".php";
+
+ if ($id) {
+ if (!$this->checkPermission($id, NULL)) {
+ CRM_Core_Error::fatal(ts('You do not have permission to make changes to the record'));
+ }
+ }
+
+ return $id;
+ }
+
/**
* @return string
*/
@@ -204,7 +222,7 @@ public function browse() {
$baoString = $this->getBAOName();
$object = new $baoString();
- $values = array();
+ $values = [];
// lets make sure we get the stuff sorted by name if it exists
$fields = &$object->fields();
@@ -239,7 +257,7 @@ public function browse() {
$permission = $this->checkPermission($object->id, $object->$key);
}
if ($permission) {
- $values[$object->id] = array();
+ $values[$object->id] = [];
CRM_Core_DAO::storeValues($object, $values[$object->id]);
if (is_a($object, 'CRM_Contact_DAO_RelationshipType')) {
@@ -287,12 +305,11 @@ public function action(&$object, $action, &$values, &$links, $permission, $force
$newAction = $action;
$hasDelete = $hasDisable = TRUE;
- if (!empty($values['name']) && in_array($values['name'], array(
- 'encounter_medium',
- 'case_type',
- 'case_status',
- ))
- ) {
+ if (!empty($values['name']) && in_array($values['name'], [
+ 'encounter_medium',
+ 'case_type',
+ 'case_status',
+ ])) {
static $caseCount = NULL;
if (!isset($caseCount)) {
$caseCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
@@ -302,17 +319,18 @@ public function action(&$object, $action, &$values, &$links, $permission, $force
}
}
+ $object_type = get_class($object);
+
if (!$forceAction) {
if (array_key_exists('is_reserved', $object) && $object->is_reserved) {
$values['class'] = 'reserved';
// check if object is relationship type
- $object_type = get_class($object);
- $exceptions = array(
+ $exceptions = [
'CRM_Contact_BAO_RelationshipType',
'CRM_Core_BAO_LocationType',
'CRM_Badge_BAO_Layout',
- );
+ ];
if (in_array($object_type, $exceptions)) {
$newAction = CRM_Core_Action::VIEW + CRM_Core_Action::UPDATE;
@@ -338,7 +356,7 @@ public function action(&$object, $action, &$values, &$links, $permission, $force
}
//CRM-4418, handling edit and delete separately.
- $permissions = array($permission);
+ $permissions = [$permission];
if ($hasDelete && ($permission == CRM_Core_Permission::EDIT)) {
//previously delete was subset of edit
//so for consistency lets grant delete also.
@@ -348,7 +366,16 @@ public function action(&$object, $action, &$values, &$links, $permission, $force
// make sure we only allow those actions that the user is permissioned for
$newAction = $newAction & CRM_Core_Action::mask($permissions);
- $values['action'] = CRM_Core_Action::formLink($links, $newAction, array('id' => $object->id));
+ $values['action'] = CRM_Core_Action::formLink(
+ $links,
+ $newAction,
+ ['id' => $object->id],
+ 'more',
+ FALSE,
+ "basic.$object_type.page",
+ $object_type,
+ $object->id
+ );
}
/**
diff --git a/CRM/Core/Page/File.php b/CRM/Core/Page/File.php
index b0632cf9beb6..c1f6cd10bf08 100644
--- a/CRM/Core/Page/File.php
+++ b/CRM/Core/Page/File.php
@@ -1,9 +1,9 @@
customFileUploadDir . $fileName;
+ }
- list($path, $mimeType) = CRM_Core_BAO_File::path($id, $eid, NULL, $quest);
if (!$path) {
CRM_Core_Error::statusBounce('Could not retrieve the file');
}
+ if (empty($mimeType)) {
+ $passedInMimeType = self::convertBadMimeAliasTypes(CRM_Utils_Request::retrieveValue('mime-type', 'String', $mimeType, FALSE));
+ if (!in_array($passedInMimeType, explode(',', Civi::settings()->get('requestableMimeTypes')))) {
+ throw new CRM_Core_Exception("Supplied mime-type is not accepted");
+ }
+ $extension = CRM_Utils_File::getExtensionFromPath($path);
+ $candidateExtensions = CRM_Utils_File::getAcceptableExtensionsForMimeType($passedInMimeType);
+ if (!in_array($extension, $candidateExtensions)) {
+ throw new CRM_Core_Exception("Supplied mime-type does not match file extension");
+ }
+ // Now that we have validated mime-type supplied as much as possible lets now set the MimeType variable/
+ $mimeType = $passedInMimeType;
+ }
+
$buffer = file_get_contents($path);
if (!$buffer) {
CRM_Core_Error::statusBounce('The file is either empty or you do not have permission to retrieve the file');
}
if ($action & CRM_Core_Action::DELETE) {
- if (CRM_Utils_Request::retrieve('confirmed', 'Boolean', CRM_Core_DAO::$_nullObject)) {
- CRM_Core_BAO_File::deleteFileReferences($id, $eid, $fid);
+ if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
+ CRM_Core_BAO_File::deleteFileReferences($fileId, $entityId, $fieldId);
CRM_Core_Session::setStatus(ts('The attached file has been deleted.'), ts('Complete'), 'success');
$session = CRM_Core_Session::singleton();
@@ -65,9 +106,41 @@ public function run() {
CRM_Utils_System::download(
CRM_Utils_File::cleanFileName(basename($path)),
$mimeType,
- $buffer
+ $buffer,
+ NULL,
+ TRUE,
+ $disposition
);
}
}
+ /**
+ * Translate one mime type to another.
+ *
+ * Certain non-standard/weird MIME types have been common. Unfortunately, because
+ * of the way this controller is used, the weird types may baked-into URLs.
+ * We clean these up for compatibility.
+ *
+ * @param string $type
+ * Ex: 'image/jpg'
+ * @return string
+ * Ex: 'image/jpeg'.
+ */
+ protected static function convertBadMimeAliasTypes($type) {
+ $badTypes = [
+ // Before PNG format was ubiquitous, it was image/x-png?
+ 'image/x-png' => 'image/png',
+
+ // People see "image/gif" and "image/png" and wrongly guess "image/jpg"?
+ 'image/jpg' => 'image/jpeg',
+ 'image/tif' => 'image/tiff',
+ 'image/svg' => 'image/svg+xml',
+
+ // StackExchange attributes "pjpeg" to some quirk in an old version of IE?
+ 'image/pjpeg' => 'image/jpeg',
+
+ ];
+ return isset($badTypes[$type]) ? $badTypes[$type] : $type;
+ }
+
}
diff --git a/CRM/Core/Page/Inline/Help.php b/CRM/Core/Page/Inline/Help.php
index 9c7d1ce212c5..4920f1857fef 100644
--- a/CRM/Core/Page/Inline/Help.php
+++ b/CRM/Core/Page/Inline/Help.php
@@ -1,9 +1,9 @@
assign('params', $args);
+ $output = $smarty->fetch($file);
$extraoutput = '';
if ($smarty->template_exists($additionalTPLFile)) {
- //@todo hook has been put here as a conservative approach
- // but probably should always run. It doesn't run otherwise because of the exit
- CRM_Utils_Hook::pageRun($this);
$extraoutput .= trim($smarty->fetch($additionalTPLFile));
+ // Allow override param to replace default text e.g. {hlp id='foo' override=1}
+ if ($smarty->get_template_vars('override_help_text')) {
+ $output = '';
+ }
}
- exit($smarty->fetch($file) . $extraoutput);
+ exit($output . $extraoutput);
}
}
diff --git a/CRM/Core/Page/QUnit.php b/CRM/Core/Page/QUnit.php
index 5920d7779c61..ae1c90c3441a 100644
--- a/CRM/Core/Page/QUnit.php
+++ b/CRM/Core/Page/QUnit.php
@@ -43,7 +43,7 @@ public function run() {
CRM_Core_Resources::singleton()->addScriptFile($ext, "tests/qunit/$suite/test.js", 1000, 'html-header');
}
- CRM_Utils_System::setTitle(ts('QUnit: %2 (%1)', array(1 => $ext, 2 => $suite)));
+ CRM_Utils_System::setTitle(ts('QUnit: %2 (%1)', [1 => $ext, 2 => $suite]));
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'bower_components/qunit/qunit/qunit.js', 1, 'html-header')
->addStyleFile('civicrm', 'bower_components/qunit/qunit/qunit.css', 1, 'html-header');
@@ -64,13 +64,13 @@ public function getRequestExtAndSuite() {
&& isset($arg[3])
&& isset($arg[4])
) {
- return array(
+ return [
trim(CRM_Utils_Type::escape($arg[3], 'String'), '/'),
trim(CRM_Utils_Type::escape($arg[4], 'String'), '/'),
- );
+ ];
}
else {
- return array(NULL, NULL);
+ return [NULL, NULL];
}
}
diff --git a/CRM/Core/Page/RecurringEntityPreview.php b/CRM/Core/Page/RecurringEntityPreview.php
index d86ea35d7165..e2505f6a6f10 100644
--- a/CRM/Core/Page/RecurringEntityPreview.php
+++ b/CRM/Core/Page/RecurringEntityPreview.php
@@ -1,9 +1,9 @@
getInterval($startDate, $endDate);
- $recursion->intervalDateColumns = array($endDateColumnName => $interval);
+ $recursion->intervalDateColumns = [$endDateColumnName => $interval];
}
}
- $dates = array_merge(array($original), $recursion->generateRecursiveDates());
+ $dates = array_merge([$original], $recursion->generateRecursiveDates());
foreach ($dates as $key => &$value) {
if ($startDateColumnName) {
@@ -88,8 +88,8 @@ public function run() {
}
//Show the list of participants registered for the events if any
- if ($formValues['entity_table'] == "civicrm_event" && !empty($parentEventId)) {
- $getConnectedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($parentEventId, 'civicrm_event', TRUE);
+ if ($formValues['entity_table'] == "civicrm_event" && !empty($parentEntityId)) {
+ $getConnectedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($parentEntityId, 'civicrm_event', TRUE);
if ($getConnectedEntities) {
$participantDetails = CRM_Event_Form_ManageEvent_Repeat::getParticipantCountforEvent($getConnectedEntities);
if (!empty($participantDetails['countByName'])) {
diff --git a/CRM/Core/Page/Redirect.php b/CRM/Core/Page/Redirect.php
index 98b24af9f793..90be62a20bc2 100644
--- a/CRM/Core/Page/Redirect.php
+++ b/CRM/Core/Page/Redirect.php
@@ -19,7 +19,7 @@ class CRM_Core_Page_Redirect extends CRM_Core_Page {
* @param string $path
* @param array $pageArgs
*/
- public function run($path = NULL, $pageArgs = array()) {
+ public function run($path = NULL, $pageArgs = []) {
$url = self::createUrl($path, $_REQUEST, $pageArgs, TRUE);
CRM_Utils_System::redirect($url);
}
@@ -41,7 +41,7 @@ public static function createUrl($requestPath, $requestArgs, $pageArgs, $absolut
CRM_Core_Error::fatal('This page is configured as a redirect, but it does not have a target.');
}
- $vars = array();
+ $vars = [];
// note: %% isn't legal in a well-formed URL, so it's not a bad variable-delimiter
foreach ($requestPath as $pathPos => $pathPart) {
$vars["%%{$pathPos}%%"] = urlencode($pathPart);
diff --git a/CRM/Core/Payment.php b/CRM/Core/Payment.php
index 745bf1131e13..9399504e1600 100644
--- a/CRM/Core/Payment.php
+++ b/CRM/Core/Payment.php
@@ -1,9 +1,9 @@
notifyUrlParameters;
- }
-
- /**
- * Set notify url parameters.
- *
- * @param array $notifyUrlParameters
- */
- public function setNotifyUrlParameters($notifyUrlParameters) {
- $this->notifyUrlParameters = $notifyUrlParameters;
- }
-
/**
* How are we getting billing information.
*
@@ -107,6 +80,9 @@ public function setNotifyUrlParameters($notifyUrlParameters) {
RECURRING_PAYMENT_START = 'START',
RECURRING_PAYMENT_END = 'END';
+ /**
+ * @var object
+ */
protected $_paymentProcessor;
/**
@@ -130,6 +106,17 @@ public function setNotifyUrlParameters($notifyUrlParameters) {
*/
protected $cancelUrl;
+ /**
+ * Processor type label.
+ *
+ * (Deprecated parameter but used in some messages).
+ *
+ * @var string
+ * @deprecated
+ *
+ */
+ public $_processorName;
+
/**
* The profile configured to show on the billing form.
*
@@ -146,6 +133,58 @@ public function setNotifyUrlParameters($notifyUrlParameters) {
*/
protected $billingProfile;
+ /**
+ * Payment instrument ID.
+ *
+ * This is normally retrieved from the payment_processor table.
+ *
+ * @var int
+ */
+ protected $paymentInstrumentID;
+
+ /**
+ * Is this a back office transaction.
+ *
+ * @var bool
+ */
+ protected $backOffice = FALSE;
+
+ /**
+ * @return bool
+ */
+ public function isBackOffice() {
+ return $this->backOffice;
+ }
+
+ /**
+ * Set back office property.
+ *
+ * @param bool $isBackOffice
+ */
+ public function setBackOffice($isBackOffice) {
+ $this->backOffice = $isBackOffice;
+ }
+
+ /**
+ * Get payment instrument id.
+ *
+ * @return int
+ */
+ public function getPaymentInstrumentID() {
+ return $this->paymentInstrumentID ? $this->paymentInstrumentID : $this->_paymentProcessor['payment_instrument_id'];
+ }
+
+ /**
+ * Set payment Instrument id.
+ *
+ * By default we actually ignore the form value. The manual processor takes it more seriously.
+ *
+ * @param int $paymentInstrumentID
+ */
+ public function setPaymentInstrumentID($paymentInstrumentID) {
+ $this->paymentInstrumentID = $this->_paymentProcessor['payment_instrument_id'];
+ }
+
/**
* Set base return path (offsite processors).
*
@@ -300,6 +339,15 @@ protected function supportsTestMode() {
return TRUE;
}
+ /**
+ * Does this payment processor support refund?
+ *
+ * @return bool
+ */
+ public function supportsRefund() {
+ return FALSE;
+ }
+
/**
* Should the first payment date be configurable when setting up back office recurring payments.
*
@@ -339,6 +387,18 @@ protected function supportsPreApproval() {
return FALSE;
}
+ /**
+ * Does this processor support updating billing info for recurring contributions through code.
+ *
+ * If the processor returns true then it must be possible to update billing info from within CiviCRM
+ * that will be updated at the payment processor.
+ *
+ * @return bool
+ */
+ protected function supportsUpdateSubscriptionBillingInfo() {
+ return method_exists(CRM_Utils_System::getClassName($this), 'updateSubscriptionBillingInfo');
+ }
+
/**
* Can recurring contributions be set against pledges.
*
@@ -365,7 +425,8 @@ protected function supportsRecurContributionsForPledges() {
* - pre_approval_parameters (this will be stored on the calling form & available later)
* - redirect_url (if set the browser will be redirected to this.
*/
- public function doPreApproval(&$params) {}
+ public function doPreApproval(&$params) {
+ }
/**
* Get any details that may be available to the payment processor due to an approval process having happened.
@@ -378,7 +439,7 @@ public function doPreApproval(&$params) {}
* @return array
*/
public function getPreApprovalDetails($storedDetails) {
- return array();
+ return [];
}
/**
@@ -393,7 +454,7 @@ public function getPreApprovalDetails($storedDetails) {
public function validatePaymentInstrument($values, &$errors) {
CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
if ($this->_paymentProcessor['payment_type'] == 1) {
- CRM_Core_Payment_Form::validateCreditCard($values, $errors);
+ CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
}
}
@@ -439,6 +500,59 @@ public function getForm() {
return $this->_paymentForm;
}
+ /**
+ * Get help text information (help, description, etc.) about this payment,
+ * to display to the user.
+ *
+ * @param string $context
+ * Context of the text.
+ * Only explicitly supported contexts are handled without error.
+ * Currently supported:
+ * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
+ *
+ * @param array $params
+ * Parameters for the field, context specific.
+ *
+ * @return string
+ */
+ public function getText($context, $params) {
+ // I have deliberately added a noisy fail here.
+ // The function is intended to be extendable, but not by changes
+ // not documented clearly above.
+ switch ($context) {
+ case 'contributionPageRecurringHelp':
+ // require exactly two parameters
+ if (array_keys($params) == [
+ 'is_recur_installments',
+ 'is_email_receipt',
+ ]) {
+ $gotText = ts('Your recurring contribution will be processed automatically.');
+ if ($params['is_recur_installments']) {
+ $gotText .= ' ' . ts('You can specify the number of installments, or you can leave the number of installments blank if you want to make an open-ended commitment. In either case, you can choose to cancel at any time.');
+ }
+ if ($params['is_email_receipt']) {
+ $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
+ }
+ }
+ return $gotText;
+
+ case 'contributionPageContinueText':
+ if ($params['amount'] <= 0) {
+ return ts('To complete this transaction, click the Continue button below.');
+ }
+ if ($this->_paymentProcessor['billing_mode'] == 4) {
+ return ts('Click the Continue button to go to %1, where you will select your payment method and complete the contribution.', [$this->_paymentProcessor['payment_processor_type']]);
+ }
+ if ($params['is_payment_to_existing']) {
+ return ts('To complete this transaction, click the Make Payment button below.');
+ }
+ return ts('To complete your contribution, click the Continue button below.');
+
+ }
+ CRM_Core_Error::deprecatedFunctionWarning('Calls to getText must use a supported method');
+ return '';
+ }
+
/**
* Getter for accessing member vars.
*
@@ -472,13 +586,22 @@ public function getPaymentTypeLabel() {
/**
* Get array of fields that should be displayed on the payment form.
- * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
+ *
+ * Common results are
+ * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
+ * or
+ * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
+ * or
+ * array()
+ *
* @return array
+ * Array of payment fields appropriate to the payment processor.
+ *
* @throws CiviCRM_API3_Exception
*/
public function getPaymentFormFields() {
if ($this->_paymentProcessor['billing_mode'] == 4) {
- return array();
+ return [];
}
return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
}
@@ -509,8 +632,8 @@ public function getPaymentFormFields() {
* @return array
*/
public function getEditableRecurringScheduleFields() {
- if (method_exists($this, 'changeSubscriptionAmount')) {
- return array('amount');
+ if ($this->supports('changeSubscriptionAmount')) {
+ return ['amount'];
}
}
@@ -534,7 +657,7 @@ public function getRecurringScheduleUpdateHelpText() {
* @return array;
*/
protected function getMandatoryFields() {
- $mandatoryFields = array();
+ $mandatoryFields = [];
foreach ($this->getAllFields() as $field_name => $field_spec) {
if (!empty($field_spec['is_required'])) {
$mandatoryFields[$field_name] = $field_spec;
@@ -553,18 +676,19 @@ protected function getAllFields() {
$billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
return array_merge($paymentFields, $billingFields);
}
+
/**
* Get array of fields that should be displayed on the payment form for credit cards.
*
* @return array
*/
protected function getCreditCardFormFields() {
- return array(
+ return [
'credit_card_type',
'credit_card_number',
'cvv2',
'credit_card_exp_date',
- );
+ ];
}
/**
@@ -573,12 +697,12 @@ protected function getCreditCardFormFields() {
* @return array
*/
protected function getDirectDebitFormFields() {
- return array(
+ return [
'account_holder',
'bank_account_number',
'bank_identification_number',
'bank_name',
- );
+ ];
}
/**
@@ -591,129 +715,164 @@ protected function getDirectDebitFormFields() {
*/
public function getPaymentFormFieldsMetadata() {
//@todo convert credit card type into an option value
- $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
- return array(
- 'credit_card_number' => array(
+ $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::creditCard();
+ $isCVVRequired = Civi::settings()->get('cvv_backoffice_required');
+ if (!$this->isBackOffice()) {
+ $isCVVRequired = TRUE;
+ }
+ return [
+ 'credit_card_number' => [
'htmlType' => 'text',
'name' => 'credit_card_number',
'title' => ts('Card Number'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 20,
'maxlength' => 20,
'autocomplete' => 'off',
'class' => 'creditcard',
- ),
+ ],
'is_required' => TRUE,
- ),
- 'cvv2' => array(
+ // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
+ ],
+ 'cvv2' => [
'htmlType' => 'text',
'name' => 'cvv2',
'title' => ts('Security Code'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 5,
'maxlength' => 10,
'autocomplete' => 'off',
- ),
- 'is_required' => Civi::settings()->get('cvv_backoffice_required'),
- 'rules' => array(
- array(
+ ],
+ 'is_required' => $isCVVRequired,
+ 'rules' => [
+ [
'rule_message' => ts('Please enter a valid value for your card security code. This is usually the last 3-4 digits on the card\'s signature panel.'),
'rule_name' => 'integer',
'rule_parameters' => NULL,
- ),
- ),
- ),
- 'credit_card_exp_date' => array(
+ ],
+ ],
+ ],
+ 'credit_card_exp_date' => [
'htmlType' => 'date',
'name' => 'credit_card_exp_date',
'title' => ts('Expiration Date'),
- 'cc_field' => TRUE,
'attributes' => CRM_Core_SelectValues::date('creditCard'),
'is_required' => TRUE,
- 'rules' => array(
- array(
+ 'rules' => [
+ [
'rule_message' => ts('Card expiration date cannot be a past date.'),
'rule_name' => 'currentDate',
'rule_parameters' => TRUE,
- ),
- ),
- ),
- 'credit_card_type' => array(
+ ],
+ ],
+ 'extra' => ['class' => 'crm-form-select'],
+ ],
+ 'credit_card_type' => [
'htmlType' => 'select',
'name' => 'credit_card_type',
'title' => ts('Card Type'),
- 'cc_field' => TRUE,
'attributes' => $creditCardType,
'is_required' => FALSE,
- ),
- 'account_holder' => array(
+ ],
+ 'account_holder' => [
'htmlType' => 'text',
'name' => 'account_holder',
'title' => ts('Account Holder'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 20,
'maxlength' => 34,
'autocomplete' => 'on',
- ),
+ ],
'is_required' => TRUE,
- ),
+ ],
//e.g. IBAN can have maxlength of 34 digits
- 'bank_account_number' => array(
+ 'bank_account_number' => [
'htmlType' => 'text',
'name' => 'bank_account_number',
'title' => ts('Bank Account Number'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 20,
'maxlength' => 34,
'autocomplete' => 'off',
- ),
- 'rules' => array(
- array(
+ ],
+ 'rules' => [
+ [
'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
'rule_name' => 'nopunctuation',
'rule_parameters' => NULL,
- ),
- ),
+ ],
+ ],
'is_required' => TRUE,
- ),
+ ],
//e.g. SWIFT-BIC can have maxlength of 11 digits
- 'bank_identification_number' => array(
+ 'bank_identification_number' => [
'htmlType' => 'text',
'name' => 'bank_identification_number',
'title' => ts('Bank Identification Number'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 20,
'maxlength' => 11,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- 'rules' => array(
- array(
+ 'rules' => [
+ [
'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
'rule_name' => 'nopunctuation',
'rule_parameters' => NULL,
- ),
- ),
- ),
- 'bank_name' => array(
+ ],
+ ],
+ ],
+ 'bank_name' => [
'htmlType' => 'text',
'name' => 'bank_name',
'title' => ts('Bank Name'),
- 'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 20,
'maxlength' => 64,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- ),
- );
+ ],
+ 'check_number' => [
+ 'htmlType' => 'text',
+ 'name' => 'check_number',
+ 'title' => ts('Check Number'),
+ 'is_required' => FALSE,
+ 'attributes' => NULL,
+ ],
+ 'pan_truncation' => [
+ 'htmlType' => 'text',
+ 'name' => 'pan_truncation',
+ 'title' => ts('Last 4 digits of the card'),
+ 'is_required' => FALSE,
+ 'attributes' => [
+ 'size' => 4,
+ 'maxlength' => 4,
+ 'minlength' => 4,
+ 'autocomplete' => 'off',
+ ],
+ 'rules' => [
+ [
+ 'rule_message' => ts('Please enter valid last 4 digit card number.'),
+ 'rule_name' => 'numeric',
+ 'rule_parameters' => NULL,
+ ],
+ ],
+ ],
+ 'payment_token' => [
+ 'htmlType' => 'hidden',
+ 'name' => 'payment_token',
+ 'title' => ts('Authorization token'),
+ 'is_required' => FALSE,
+ 'attributes' => [
+ 'size' => 10,
+ 'autocomplete' => 'off',
+ 'id' => 'payment_token',
+ ],
+ ],
+ ];
}
/**
@@ -734,9 +893,9 @@ public function getBillingAddressFields($billingLocationID = NULL) {
$billingLocationID = CRM_Core_BAO_LocationType::getBilling();
}
if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
- return array();
+ return [];
}
- return array(
+ return [
'first_name' => 'billing_first_name',
'middle_name' => 'billing_middle_name',
'last_name' => 'billing_last_name',
@@ -745,7 +904,7 @@ public function getBillingAddressFields($billingLocationID = NULL) {
'country' => "billing_country_id-{$billingLocationID}",
'state_province' => "billing_state_province_id-{$billingLocationID}",
'postal_code' => "billing_postal_code-{$billingLocationID}",
- );
+ ];
}
/**
@@ -754,7 +913,7 @@ public function getBillingAddressFields($billingLocationID = NULL) {
* @param int $billingLocationID
*
* @return array
- * Array of metadata for address fields.
+ * Array of metadata for address fields.
*/
public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
if (!$billingLocationID) {
@@ -763,103 +922,103 @@ public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
// So taking this as a param is possibly something to be removed in favour of the standard default.
$billingLocationID = CRM_Core_BAO_LocationType::getBilling();
}
- $metadata = array();
- $metadata['billing_first_name'] = array(
+ $metadata = [];
+ $metadata['billing_first_name'] = [
'htmlType' => 'text',
'name' => 'billing_first_name',
'title' => ts('Billing First Name'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- );
+ ];
- $metadata['billing_middle_name'] = array(
+ $metadata['billing_middle_name'] = [
'htmlType' => 'text',
'name' => 'billing_middle_name',
'title' => ts('Billing Middle Name'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => FALSE,
- );
+ ];
- $metadata['billing_last_name'] = array(
+ $metadata['billing_last_name'] = [
'htmlType' => 'text',
'name' => 'billing_last_name',
'title' => ts('Billing Last Name'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- );
+ ];
- $metadata["billing_street_address-{$billingLocationID}"] = array(
+ $metadata["billing_street_address-{$billingLocationID}"] = [
'htmlType' => 'text',
'name' => "billing_street_address-{$billingLocationID}",
'title' => ts('Street Address'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- );
+ ];
- $metadata["billing_city-{$billingLocationID}"] = array(
+ $metadata["billing_city-{$billingLocationID}"] = [
'htmlType' => 'text',
'name' => "billing_city-{$billingLocationID}",
'title' => ts('City'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- );
+ ];
- $metadata["billing_state_province_id-{$billingLocationID}"] = array(
+ $metadata["billing_state_province_id-{$billingLocationID}"] = [
'htmlType' => 'chainSelect',
'title' => ts('State/Province'),
'name' => "billing_state_province_id-{$billingLocationID}",
'cc_field' => TRUE,
'is_required' => TRUE,
- );
+ ];
- $metadata["billing_postal_code-{$billingLocationID}"] = array(
+ $metadata["billing_postal_code-{$billingLocationID}"] = [
'htmlType' => 'text',
'name' => "billing_postal_code-{$billingLocationID}",
'title' => ts('Postal Code'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'size' => 30,
'maxlength' => 60,
'autocomplete' => 'off',
- ),
+ ],
'is_required' => TRUE,
- );
+ ];
- $metadata["billing_country_id-{$billingLocationID}"] = array(
+ $metadata["billing_country_id-{$billingLocationID}"] = [
'htmlType' => 'select',
'name' => "billing_country_id-{$billingLocationID}",
'title' => ts('Country'),
'cc_field' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'' => ts('- select -'),
- ) + CRM_Core_PseudoConstant::country(),
+ ] + CRM_Core_PseudoConstant::country(),
'is_required' => TRUE,
- );
+ ];
return $metadata;
}
@@ -883,6 +1042,32 @@ protected function getBaseReturnUrl() {
return $baseURL;
}
+ /**
+ * Get the currency for the transaction.
+ *
+ * Handle any inconsistency about how it is passed in here.
+ *
+ * @param $params
+ *
+ * @return string
+ */
+ protected function getCurrency($params) {
+ return CRM_Utils_Array::value('currencyID', $params, CRM_Utils_Array::value('currency', $params));
+ }
+
+ /**
+ * Get the currency for the transaction.
+ *
+ * Handle any inconsistency about how it is passed in here.
+ *
+ * @param $params
+ *
+ * @return string
+ */
+ protected function getAmount($params) {
+ return CRM_Utils_Money::format($params['amount'], NULL, NULL, TRUE);
+ }
+
/**
* Get url to return to after cancelled or failed transaction.
*
@@ -897,20 +1082,20 @@ public function getCancelUrl($qfKey, $participantID) {
}
if ($this->_component == 'event') {
- return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
+ return CRM_Utils_System::url($this->getBaseReturnUrl(), [
'reset' => 1,
'cc' => 'fail',
'participantId' => $participantID,
- ),
+ ],
TRUE, NULL, FALSE
);
}
- return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
+ return CRM_Utils_System::url($this->getBaseReturnUrl(), [
'_qf_Main_display' => 1,
'qfKey' => $qfKey,
'cancel' => 1,
- ),
+ ],
TRUE, NULL, FALSE
);
}
@@ -927,10 +1112,10 @@ protected function getReturnSuccessUrl($qfKey) {
return $this->successUrl;
}
- return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
+ return CRM_Utils_System::url($this->getBaseReturnUrl(), [
'_qf_ThankYou_display' => 1,
'qfKey' => $qfKey,
- ),
+ ],
TRUE, NULL, FALSE
);
}
@@ -973,10 +1158,10 @@ protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL
* @return string url
*/
protected function getGoBackUrl($qfKey) {
- return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
+ return CRM_Utils_System::url($this->getBaseReturnUrl(), [
'_qf_Confirm_display' => 'true',
'qfKey' => $qfKey,
- ),
+ ],
TRUE, NULL, FALSE
);
}
@@ -993,10 +1178,11 @@ protected function getGoBackUrl($qfKey) {
protected function getNotifyUrl() {
$url = CRM_Utils_System::url(
'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
- $this->getNotifyUrlParameters(),
+ [],
TRUE,
NULL,
- FALSE
+ FALSE,
+ TRUE
);
return (stristr($url, '.')) ? $url : '';
}
@@ -1017,7 +1203,7 @@ protected function doDirectPayment(&$params) {
}
/**
- * 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.
@@ -1032,6 +1218,13 @@ protected function doDirectPayment(&$params) {
* Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
* return Error objects
*
+ * Usage:
+ * Payment processors should override this function directly instead of using doDirectPayment/doTransferCheckout which are deprecated.
+ * Payment processors should set and return payment_status_id (Pending if the IPN will complete it, Completed if successful).
+ * @fixme For the contribution workflow we have a contributionID, but for the event and membership workflow the contribution has not yet been created
+ * so we can't update params directly on the contribution. However if you return trxn_id, fee_amount, net_amount they will be set on the contribution
+ * by those workflows. Ideally all workflows would create a pending contribution BEFORE calling doPayment (eg. https://github.com/civicrm/civicrm-core/pull/13763 for events)
+ *
* @param array $params
*
* @param string $component
@@ -1043,7 +1236,7 @@ protected function doDirectPayment(&$params) {
*/
public function doPayment(&$params, $component = 'contribute') {
$this->_component = $component;
- $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
+ $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
// If we have a $0 amount, skip call to processor and set payment_status to Completed.
// Conceivably a processor might override this - perhaps for setting up a token - but we don't
@@ -1077,6 +1270,17 @@ public function doPayment(&$params, $component = 'contribute') {
return $result;
}
+ /**
+ * Refunds payment
+ *
+ * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
+ *
+ * @param array $params
+ *
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
+ */
+ public function doRefund(&$params) {}
+
/**
* Query payment processor for details about a transaction.
*
@@ -1092,7 +1296,7 @@ public function doPayment(&$params, $component = 'contribute') {
* - fee_amount Amount of fee paid
*/
public function doQuery($params) {
- return array();
+ return [];
}
/**
@@ -1137,15 +1341,23 @@ public static function paypalRedirect(&$paymentProcessor) {
* Page callback for civicrm/payment/ipn
*/
public static function handleIPN() {
- self::handlePaymentMethod(
- 'PaymentNotification',
- array(
- 'processor_name' => @$_GET['processor_name'],
- 'processor_id' => @$_GET['processor_id'],
- 'mode' => @$_GET['mode'],
- 'q' => @$_GET['q'],
- )
- );
+ try {
+ self::handlePaymentMethod(
+ 'PaymentNotification',
+ [
+ 'processor_name' => CRM_Utils_Request::retrieveValue('processor_name', 'String'),
+ 'processor_id' => CRM_Utils_Request::retrieveValue('processor_id', 'Integer'),
+ 'mode' => CRM_Utils_Request::retrieveValue('mode', 'Alphanumeric'),
+ ]
+ );
+ }
+ catch (CRM_Core_Exception $e) {
+ Civi::log()->error('ipn_payment_callback_exception', [
+ 'context' => [
+ 'backtrace' => CRM_Core_Error::formatBacktrace(debug_backtrace()),
+ ],
+ ]);
+ }
CRM_Utils_System::civiExit();
}
@@ -1166,14 +1378,15 @@ public static function handleIPN() {
* @throws \CRM_Core_Exception
* @throws \Exception
*/
- public static function handlePaymentMethod($method, $params = array()) {
+ public static function handlePaymentMethod($method, $params = []) {
if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
- $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
+ $q = explode('/', CRM_Utils_Array::value(CRM_Core_Config::singleton()->userFrameworkURLVar, $_GET, ''));
$lastParam = array_pop($q);
if (is_numeric($lastParam)) {
$params['processor_id'] = $_GET['processor_id'] = $lastParam;
}
else {
+ self::logPaymentNotification($params);
throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
}
}
@@ -1188,25 +1401,25 @@ public static function handlePaymentMethod($method, $params = array()) {
if (isset($params['processor_id'])) {
$sql .= " WHERE pp.id = %2";
- $args[2] = array($params['processor_id'], 'Integer');
- $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
+ $args[2] = [$params['processor_id'], 'Integer'];
+ $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
}
else {
// This is called when processor_name is passed - passing processor_id instead is recommended.
$sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
- $args[1] = array(
+ $args[1] = [
(CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
'Integer',
- );
- $args[2] = array($params['processor_name'], 'String');
- $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
+ ];
+ $args[2] = [$params['processor_name'], 'String'];
+ $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
}
$dao = CRM_Core_DAO::executeQuery($sql, $args);
// Check whether we found anything at all.
if (!$dao->N) {
- CRM_Core_Error::fatal($notFound);
+ throw new CRM_Core_Exception($notFound);
}
$method = 'handle' . $method;
@@ -1232,7 +1445,7 @@ public static function handlePaymentMethod($method, $params = array()) {
// Does PP implement this method, and can we call it?
if (!method_exists($processorInstance, $method) ||
- !is_callable(array($processorInstance, $method))
+ !is_callable([$processorInstance, $method])
) {
// on the off chance there is a double implementation of this processor we should keep looking for another
// note that passing processor_id is more reliable & we should work to deprecate processor_name
@@ -1244,10 +1457,16 @@ public static function handlePaymentMethod($method, $params = array()) {
$extension_instance_found = TRUE;
}
+ // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
+ $IPNParams = array_merge($_GET, $_REQUEST);
+ CRM_Utils_Hook::postIPNProcess($IPNParams);
if (!$extension_instance_found) {
$message = "No extension instances of the '%1' payment processor were found.
" .
"%2 method is unsupported in legacy payment processors.";
- CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
+ throw new CRM_Core_Exception(ts($message, [
+ 1 => $params['processor_name'],
+ 2 => $method,
+ ]));
}
}
@@ -1312,18 +1531,24 @@ public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'can
// Set URL
switch ($action) {
case 'cancel':
+ if (!$this->supports('cancelRecurring')) {
+ return NULL;
+ }
$url = 'civicrm/contribute/unsubscribe';
break;
case 'billing':
//in notify mode don't return the update billing url
- if (!$this->isSupported('updateSubscriptionBillingInfo')) {
+ if (!$this->supports('updateSubscriptionBillingInfo')) {
return NULL;
}
$url = 'civicrm/contribute/updatebilling';
break;
case 'update':
+ if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
+ return NULL;
+ }
$url = 'civicrm/contribute/updaterecur';
break;
}
@@ -1348,12 +1573,16 @@ public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'can
case 'recur':
$sql = "
- SELECT con.contact_id
+ SELECT DISTINCT con.contact_id
FROM civicrm_contribution_recur rec
INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
- WHERE rec.id = %1
- GROUP BY rec.id";
- $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
+ WHERE rec.id = %1";
+ $contactID = CRM_Core_DAO::singleValueQuery($sql, [
+ 1 => [
+ $entityID,
+ 'Integer',
+ ],
+ ]);
$entityArg = 'crid';
break;
}
@@ -1369,7 +1598,7 @@ public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'can
}
// Else login URL
- if ($this->isSupported('accountLoginURL')) {
+ if ($this->supports('accountLoginURL')) {
return $this->accountLoginURL();
}
@@ -1392,10 +1621,19 @@ public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'can
* @return string
*/
protected function getPaymentDescription($params, $length = 24) {
- $parts = array('contactID', 'contributionID', 'description', 'billing_first_name', 'billing_last_name');
- $validParts = array();
+ $parts = [
+ 'contactID',
+ 'contributionID',
+ 'description',
+ 'billing_first_name',
+ 'billing_last_name',
+ ];
+ $validParts = [];
if (isset($params['description'])) {
- $uninformativeStrings = array(ts('Online Event Registration: '), ts('Online Contribution: '));
+ $uninformativeStrings = [
+ ts('Online Event Registration: '),
+ ts('Online Contribution: '),
+ ];
$params['description'] = str_replace($uninformativeStrings, '', $params['description']);
}
foreach ($parts as $part) {
@@ -1415,6 +1653,41 @@ public function supportsEditRecurringContribution() {
return FALSE;
}
+ /**
+ * Does this processor support changing the amount for recurring contributions through code.
+ *
+ * If the processor returns true then it must be possible to update the amount from within CiviCRM
+ * that will be updated at the payment processor.
+ *
+ * @return bool
+ */
+ protected function supportsChangeSubscriptionAmount() {
+ return method_exists(CRM_Utils_System::getClassName($this), 'changeSubscriptionAmount');
+ }
+
+ /**
+ * Checks if payment processor supports recurring contributions
+ *
+ * @return bool
+ */
+ public function supportsRecurring() {
+ if (!empty($this->_paymentProcessor['is_recur'])) {
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Checks if payment processor supports an account login URL
+ * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
+ * TODO: It is implemented by AuthorizeNET, any others?
+ *
+ * @return bool
+ */
+ protected function supportsAccountLoginURL() {
+ return method_exists(CRM_Utils_System::getClassName($this), 'accountLoginURL');
+ }
+
/**
* Should a receipt be sent out for a pending payment.
*
diff --git a/CRM/Core/Payment/AuthorizeNet.php b/CRM/Core/Payment/AuthorizeNet.php
index 19b4bcec9c7f..dbdcdcbcac99 100644
--- a/CRM/Core/Payment/AuthorizeNet.php
+++ b/CRM/Core/Payment/AuthorizeNet.php
@@ -28,7 +28,7 @@ class CRM_Core_Payment_AuthorizeNet extends CRM_Core_Payment {
protected $_mode = NULL;
- protected $_params = array();
+ protected $_params = [];
/**
* We only need one instance of this object. So we use the singleton
@@ -126,7 +126,7 @@ public function doDirectPayment(&$params) {
return $params;
}
- $postFields = array();
+ $postFields = [];
$authorizeNetFields = $this->_getAuthorizeNetFields();
// Set up our call for hook_civicrm_paymentProcessor,
@@ -167,25 +167,24 @@ public function doDirectPayment(&$params) {
curl_close($submit);
$response_fields = $this->explode_csv($response);
- // check gateway MD5 response
- if (!$this->checkMD5($response_fields[37], $response_fields[6], $response_fields[9])) {
- return self::error(9003, 'MD5 Verification failed');
- }
+
+ // fetch available contribution statuses
+ $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
// check for application errors
// TODO:
// AVS, CVV2, CAVV, and other verification results
- $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
switch ($response_fields[0]) {
- case self::AUTH_REVIEW :
+ case self::AUTH_REVIEW:
$params['payment_status_id'] = array_search('Pending', $contributionStatus);
break;
- case self::AUTH_ERROR :
+ case self::AUTH_ERROR:
$params['payment_status_id'] = array_search('Failed', $contributionStatus);
- break;
+ $errormsg = $response_fields[2] . ' ' . $response_fields[3];
+ return self::error($response_fields[1], $errormsg);
- case self::AUTH_DECLINED :
+ case self::AUTH_DECLINED:
$errormsg = $response_fields[2] . ' ' . $response_fields[3];
return self::error($response_fields[1], $errormsg);
@@ -199,7 +198,7 @@ public function doDirectPayment(&$params) {
// fix for CRM-2566
if (($this->_mode == 'test') || $response_fields[6] == 0) {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id RLIKE 'test[0-9]+'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_DAO::singleValueQuery($query, $p));
$trxn_id = str_replace('test', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -322,7 +321,7 @@ public function doRecurPayment() {
return self::error(9002, 'Could not initiate connection to payment gateway');
}
curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
+ curl_setopt($submit, CURLOPT_HTTPHEADER, ["Content-Type: text/xml"]);
curl_setopt($submit, CURLOPT_HEADER, 1);
curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML);
curl_setopt($submit, CURLOPT_POST, 1);
@@ -356,11 +355,13 @@ public function doRecurPayment() {
* @return array
*/
public function _getAuthorizeNetFields() {
- $amount = $this->_getParam('total_amount');//Total amount is from the form contribution field
- if (empty($amount)) {//CRM-9894 would this ever be the case??
+ //Total amount is from the form contribution field
+ $amount = $this->_getParam('total_amount');
+ //CRM-9894 would this ever be the case??
+ if (empty($amount)) {
$amount = $this->_getParam('amount');
}
- $fields = array();
+ $fields = [];
$fields['x_login'] = $this->_getParam('apiLogin');
$fields['x_tran_key'] = $this->_getParam('paymentKey');
$fields['x_email_customer'] = $this->_getParam('emailCustomer');
@@ -373,7 +374,7 @@ public function _getAuthorizeNetFields() {
$fields['x_country'] = $this->_getParam('country');
$fields['x_customer_ip'] = $this->_getParam('ip_address');
$fields['x_email'] = $this->_getParam('email');
- $fields['x_invoice_num'] = substr($this->_getParam('invoiceID'), 0, 20);
+ $fields['x_invoice_num'] = $this->_getParam('invoiceID');
$fields['x_amount'] = $amount;
$fields['x_currency_code'] = $this->_getParam('currencyID');
$fields['x_description'] = $this->_getParam('description');
@@ -432,39 +433,6 @@ public function hmac($key, $data) {
}
}
- /**
- * Check the gateway MD5 response to make sure that this is a proper
- * gateway response
- *
- * @param string $responseMD5
- * MD5 hash generated by the gateway.
- * @param string $transaction_id
- * Transaction id generated by the gateway.
- * @param string $amount
- * Purchase amount.
- *
- * @param bool $ipn
- *
- * @return bool
- */
- public function checkMD5($responseMD5, $transaction_id, $amount, $ipn = FALSE) {
- // cannot check if no MD5 hash
- $md5Hash = $this->_getParam('md5Hash');
- if (empty($md5Hash)) {
- return TRUE;
- }
- $loginid = $this->_getParam('apiLogin');
- $hashString = $ipn ? ($md5Hash . $transaction_id . $amount) : ($md5Hash . $loginid . $transaction_id . $amount);
- $result = strtoupper(md5($hashString));
-
- if ($result == $responseMD5) {
- return TRUE;
- }
- else {
- return FALSE;
- }
- }
-
/**
* Calculate and return the transaction fingerprint.
*
@@ -496,10 +464,10 @@ public function explode_csv($data) {
$data = trim($data);
//make it easier to parse fields with quotes in them
$data = str_replace('""', "''", $data);
- $fields = array();
+ $fields = [];
while ($data != '') {
- $matches = array();
+ $matches = [];
if ($data[0] == '"') {
// handle quoted fields
preg_match('/^"(([^"]|\\")*?)",?(.*)$/', $data, $matches);
@@ -535,13 +503,13 @@ public function _parseArbReturn($content) {
$code = $this->_substring_between($content, '', '
');
$text = $this->_substring_between($content, '
"; - return FALSE; - } - $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $transaction = new CRM_Core_Transaction(); @@ -134,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); @@ -149,12 +150,13 @@ public function recur(&$input, &$ids, &$objects, $first) { $contribution->financial_type_id = $objects['contributionType']->id; $contribution->contribution_page_id = $ids['contributionPage']; $contribution->contribution_recur_id = $ids['contributionRecur']; - $contribution->receive_date = $now; + $contribution->receive_date = $input['receive_date']; $contribution->currency = $objects['contribution']->currency; $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id; $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; } @@ -162,14 +164,13 @@ 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 if ($first) { $recur->start_date = $now; $recur->trxn_id = $recur->processor_id; - $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START; + $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START; } $statusName = 'In Progress'; if (($recur->installments > 0) && @@ -178,7 +179,7 @@ public function recur(&$input, &$ids, &$objects, $first) { // this is the last payment $statusName = 'Completed'; $recur->end_date = $now; - $this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END; + $isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END; } $recur->modified_date = $now; $recur->contribution_status_id = array_search($statusName, $contributionStatus); @@ -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 @@ -210,11 +211,23 @@ public function recur(&$input, &$ids, &$objects, $first) { } $this->completeTransaction($input, $ids, $objects, $transaction, $recur); + + // Only Authorize.net does this so it is on the a.net class. If there is a need for other processors + // to do this we should make it available via the api, e.g as a parameter, changing the nuance + // from isSentReceipt to an array of which receipts to send. + // Note that there is site-by-site opinions on which notifications are good to send. + if ($isFirstOrLastRecurringPayment) { + CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, + $isFirstOrLastRecurringPayment); + } + } /** - * @param $input - * @param $ids + * Get the input from passed in fields. + * + * @param array $input + * @param array $ids * * @return bool */ @@ -227,6 +240,8 @@ public function getInput(&$input, &$ids) { $input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE); $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'); if ($input['trxn_id']) { $input['is_test'] = 0; @@ -242,7 +257,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', @@ -251,15 +266,19 @@ 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); } } /** - * @param $ids - * @param $input + * Get ids from input. + * + * @param array $ids + * @param array $input + * + * @throws \CRM_Core_Exception */ public function getIDs(&$ids, &$input) { $ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0); @@ -277,14 +296,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); } @@ -298,8 +317,6 @@ public function getIDs(&$ids, &$input) { // FIXME: figure out fields for event } else { - // get the optional ids - // Get membershipId. Join with membership payment table for additional checks $sql = " SELECT m.id @@ -340,25 +357,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 49e3c7048093..35af834bd575 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); @@ -206,13 +214,13 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces * * @return bool */ - 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,10 +231,10 @@ 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->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); @@ -248,29 +256,26 @@ 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, - )); + $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', [ + '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']); + $params = ['status_id' => $membershipStatuses['Cancelled']]; CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params); } } } 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(); + $participantParams['id'] = $participant->id; + $participantParams['status_id'] = 'Cancelled'; + civicrm_api3('Participant', 'create', $participantParams); } } @@ -304,11 +309,11 @@ public function pending(&$objects, &$transaction) { * * @return bool */ - 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 = [$objects['membership']]; } $participant = &$objects['participant']; @@ -316,10 +321,10 @@ public function cancelled(&$objects, &$transaction, $input = array()) { if (empty($contribution->id)) { $addLineItems = TRUE; } - $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['Cancelled']; $contribution->cancel_date = self::$_now; $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input); @@ -342,10 +347,10 @@ 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, - )); + $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', [ + 'labelColumn' => 'name', + 'flip' => 1, + ]); // Cancel only Pending memberships // CRM-18688 $pendingStatusId = $membershipStatuses['Pending']; @@ -355,19 +360,16 @@ public function cancelled(&$objects, &$transaction, $input = array()) { $membership->save(); //update related Memberships. - $params = array('status_id' => $membershipStatuses['Cancelled']); + $params = ['status_id' => $membershipStatuses['Cancelled']]; CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params); } } } 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(); + $participantParams['id'] = $participant->id; + $participantParams['status_id'] = 'Cancelled'; + civicrm_api3('Participant', 'create', $participantParams); } } $transaction->commit(); @@ -392,6 +394,8 @@ public function unhandled(&$objects, &$transaction) { } /** + * @deprecated + * * Jumbled up function. * * The purpose of this function is to transition a pending transaction to Completed including updating any @@ -411,7 +415,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,12 +449,9 @@ public function unhandled(&$objects, &$transaction) { * @param bool $recur */ public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { - $isRecurring = $this->_isRecurring; - $isFirstOrLastRecurringPayment = $this->_isFirstOrLastRecurringPayment; $contribution = &$objects['contribution']; - CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution, - $isRecurring, $isFirstOrLastRecurringPayment); + CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution); } /** @@ -463,7 +464,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;
}
@@ -471,10 +472,10 @@ public function getBillingID(&$ids) {
}
/**
- * Send receipt from contribution.
- *
* @deprecated
*
+ * @todo confirm this function is not being used by any payment processor outside core & remove.
+ *
* Note that the compose message part has been moved to contribution
* In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
*
@@ -494,7 +495,7 @@ public function getBillingID(&$ids) {
* @return array
*/
public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
- return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values, $recur,
+ return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
$returnMessageText);
}
diff --git a/CRM/Core/Payment/Dummy.php b/CRM/Core/Payment/Dummy.php
index 1d68efe86812..1fdbd9cda340 100644
--- a/CRM/Core/Payment/Dummy.php
+++ b/CRM/Core/Payment/Dummy.php
@@ -22,8 +22,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 +34,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'];
@@ -104,7 +104,7 @@ public function doDirectPayment(&$params) {
}
if ($this->_mode == 'test') {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test\\_%'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('test_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -112,7 +112,7 @@ public function doDirectPayment(&$params) {
}
else {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'live_%'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('live_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -137,6 +137,25 @@ protected function supportsLiveMode() {
return TRUE;
}
+ /**
+ * Does this payment processor support refund?
+ *
+ * @return bool
+ */
+ public function supportsRefund() {
+ 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 +214,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..7b91ac425198 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();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('test', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -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');
@@ -405,7 +405,7 @@ public function GetNodeValue($NodeName, &$strXML) {
* @return mixed
*/
public function decodeXMLresponse($Xml) {
- $processorResponse = array();
+ $processorResponse = [];
$processorResponse['ssl_result'] = self::GetNodeValue("ssl_result", $Xml);
$processorResponse['ssl_result_message'] = self::GetNodeValue("ssl_result_message", $Xml);
diff --git a/CRM/Core/Payment/FirstData.php b/CRM/Core/Payment/FirstData.php
index 116d2322ba53..a123e8f85dea 100644
--- a/CRM/Core/Payment/FirstData.php
+++ b/CRM/Core/Payment/FirstData.php
@@ -1,7 +1,7 @@
$paymentProcessor)));
+ CRM_Core_Error::fatal(ts('%1 - Gateway requires curl with SSL support', [1 => $paymentProcessor]));
}
/**********************************************************
@@ -309,6 +309,7 @@ public function doDirectPayment(&$params) {
return $params;
}
}
+
// end function doDirectPayment
/**
@@ -346,7 +347,7 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
* CiviCRM V2.0 Declaration
*/
public function checkConfig() {
- $errorMsg = array();
+ $errorMsg = [];
if (empty($this->_paymentProcessor['user_name'])) {
$errorMsg[] = ts(' Store Name is not set for this payment processor');
diff --git a/CRM/Core/Payment/Form.php b/CRM/Core/Payment/Form.php
index bafe1ae2a6c8..027904845b36 100644
--- a/CRM/Core/Payment/Form.php
+++ b/CRM/Core/Payment/Form.php
@@ -1,9 +1,9 @@
billingFieldSets = array();
+ public static function setPaymentFieldsByProcessor(&$form, $processor, $billing_profile_id = NULL, $isBackOffice = FALSE, $paymentInstrumentID = NULL) {
+ $form->billingFieldSets = [];
// Load the pay-later processor
// @todo load this right up where the other processors are loaded initially.
if (empty($processor)) {
@@ -62,16 +63,18 @@ static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_
}
$processor['object']->setBillingProfile($billing_profile_id);
+ $processor['object']->setBackOffice($isBackOffice);
+ $processor['object']->setPaymentInstrumentID($paymentInstrumentID);
$paymentTypeName = self::getPaymentTypeName($processor);
- $paymentTypeLabel = self::getPaymentTypeLabel($processor);
$form->assign('paymentTypeName', $paymentTypeName);
- $form->assign('paymentTypeLabel', $paymentTypeLabel);
+ $form->assign('paymentTypeLabel', self::getPaymentLabel($processor['object']));
+ $form->assign('isBackOffice', $isBackOffice);
$form->_paymentFields = $form->billingFieldSets[$paymentTypeName]['fields'] = self::getPaymentFieldMetadata($processor);
$form->_paymentFields = array_merge($form->_paymentFields, self::getBillingAddressMetadata($processor, $form->_bltID));
$form->assign('paymentFields', self::getPaymentFields($processor));
self::setBillingAddressFields($form, $processor);
// @todo - this may be obsolete - although potentially it could be used to re-order things in the form.
- $form->billingFieldSets['billing_name_address-group']['fields'] = array();
+ $form->billingFieldSets['billing_name_address-group']['fields'] = [];
}
/**
@@ -80,7 +83,7 @@ static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_
* @param CRM_Core_Form $form
* @param CRM_Core_Payment $processor
*/
- static protected function setBillingAddressFields(&$form, $processor) {
+ protected static function setBillingAddressFields(&$form, $processor) {
$billingID = $form->_bltID;
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('billingDetailsFields', self::getBillingAddressFields($processor, $billingID));
@@ -109,25 +112,28 @@ static protected function setBillingAddressFields(&$form, $processor) {
* Fields that are to be shown on the payment form.
*/
protected static function addCommonFields(&$form, $paymentFields) {
- $requiredPaymentFields = array();
+ $requiredPaymentFields = $paymentFieldsMetadata = [];
foreach ($paymentFields as $name => $field) {
- if (!empty($field['cc_field'])) {
- if ($field['htmlType'] == 'chainSelect') {
- $form->addChainSelect($field['name'], array('required' => FALSE));
- }
- else {
- $form->add($field['htmlType'],
- $field['name'],
- $field['title'],
- $field['attributes'],
- FALSE
- );
- }
+ $field['extra'] = isset($field['extra']) ? $field['extra'] : NULL;
+ if ($field['htmlType'] == 'chainSelect') {
+ $form->addChainSelect($field['name'], ['required' => FALSE]);
+ }
+ else {
+ $form->add($field['htmlType'],
+ $field['name'],
+ $field['title'],
+ $field['attributes'],
+ FALSE,
+ $field['extra']
+ );
}
// This will cause the fields to be marked as required - but it is up to the payment processor to
// validate it.
$requiredPaymentFields[$field['name']] = $field['is_required'];
+ $paymentFieldsMetadata[$field['name']] = $field;
}
+
+ $form->assign('paymentFieldsMetadata', $paymentFieldsMetadata);
$form->assign('requiredPaymentFields', $requiredPaymentFields);
}
@@ -142,8 +148,7 @@ protected static function addCommonFields(&$form, $paymentFields) {
* @return array
*/
public static function getPaymentFields($paymentProcessor) {
- $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
- return $paymentProcessorObject->getPaymentFormFields();
+ return $paymentProcessor['object']->getPaymentFormFields();
}
/**
@@ -152,8 +157,7 @@ public static function getPaymentFields($paymentProcessor) {
* @return array
*/
public static function getPaymentFieldMetadata($paymentProcessor) {
- $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
- return array_intersect_key($paymentProcessorObject->getPaymentFormFieldsMetadata(), array_flip(self::getPaymentFields($paymentProcessor)));
+ return array_intersect_key($paymentProcessor['object']->getPaymentFormFieldsMetadata(), array_flip(self::getPaymentFields($paymentProcessor)));
}
/**
@@ -203,8 +207,7 @@ public static function getPaymentTypeName($paymentProcessor) {
* @return string
*/
public static function getPaymentTypeLabel($paymentProcessor) {
- $paymentProcessorObject = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
- return ts(($paymentProcessorObject->getPaymentTypeLabel()) . ' Information');
+ return ts('%1 Information', [$paymentProcessor->getPaymentTypeLabel()]);
}
/**
@@ -220,10 +223,12 @@ public static function getPaymentTypeLabel($paymentProcessor) {
* although the distinction is losing it's meaning as front end forms are used for back office and a permission
* for the 'enter without cvn' is probably more appropriate. Paypal std does not support another user
* entering details but once again the issue is not back office but 'another user'.
+ * @param int $paymentInstrumentID
+ * Payment instrument ID.
*
* @return bool
*/
- public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice) {
+ public static function buildPaymentForm(&$form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID = NULL) {
//if the form has address fields assign to the template so the js can decide what billing fields to show
$profileAddressFields = $form->get('profileAddressFields');
if (!empty($profileAddressFields)) {
@@ -234,7 +239,7 @@ public static function buildPaymentForm(&$form, $processor, $billing_profile_id,
return NULL;
}
- self::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice);
+ self::setPaymentFieldsByProcessor($form, $processor, $billing_profile_id, $isBackOffice, $paymentInstrumentID);
self::addCommonFields($form, $form->_paymentFields);
self::addRules($form, $form->_paymentFields);
return (!empty($form->_paymentFields));
@@ -277,24 +282,6 @@ public static function validatePaymentInstrument($payment_processor_id, $values,
$payment->validatePaymentInstrument($values, $errors);
}
- /**
- * The credit card pseudo constant results only the CC label, not the key ID
- * So we normalize the name to use it as a CSS class.
- */
- public static function getCreditCardCSSNames() {
- $creditCardTypes = array();
- foreach (CRM_Contribute_PseudoConstant::creditCard() as $key => $name) {
- // Replace anything not css-friendly by an underscore
- // Non-latin names will not like this, but so many things are wrong with
- // the credit-card type configurations already.
- $key = str_replace(' ', '', $key);
- $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
- $key = strtolower($key);
- $creditCardTypes[$key] = $name;
- }
- return $creditCardTypes;
- }
-
/**
* Set default values for the form.
*
@@ -325,9 +312,16 @@ public static function setDefaultValues(&$form, $contactID) {
*
* @param array $values
* @param array $errors
+ * @param int $processorID
*/
- public static function validateCreditCard($values, &$errors) {
+ public static function validateCreditCard($values, &$errors, $processorID = NULL) {
if (!empty($values['credit_card_type']) || !empty($values['credit_card_number'])) {
+ if (!empty($values['credit_card_type'])) {
+ $processorCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($processorID);
+ if (!empty($processorCards) && !in_array($values['credit_card_type'], $processorCards)) {
+ $errors['credit_card_type'] = ts('This procesor does not support credit card type ' . $values['credit_card_type']);
+ }
+ }
if (!empty($values['credit_card_number']) &&
!CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
) {
@@ -350,14 +344,7 @@ public static function validateCreditCard($values, &$errors) {
* @param bool $reverse
*/
public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
- // Set text version of state & country if present.
- if (isset($src["billing_state_province_id-{$id}"])) {
- $src["billing_state_province-{$id}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($src["billing_state_province_id-{$id}"]);
- }
- if (isset($src["billing_country_id-{$id}"])) {
- $src["billing_country-{$id}"] = CRM_Core_PseudoConstant::countryIsoCode($src["billing_country_id-{$id}"]);;
- };
- $map = array(
+ $map = [
'first_name' => 'billing_first_name',
'middle_name' => 'billing_middle_name',
'last_name' => 'billing_last_name',
@@ -369,7 +356,7 @@ public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
'postal_code' => "billing_postal_code-$id",
'country' => "billing_country-$id",
'contactID' => 'contact_id',
- );
+ ];
foreach ($map as $n => $v) {
if (!$reverse) {
@@ -383,6 +370,9 @@ public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
}
}
}
+
+ //CRM-19469 provide option for returning modified params
+ return $dst;
}
/**
@@ -415,4 +405,25 @@ public static function getCreditCardExpirationYear($src) {
return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
}
+ /**
+ * Get the label for the processor.
+ *
+ * We do not use a label if there are no enterable fields.
+ *
+ * @param \CRM_Core_Payment $processor
+ *
+ * @return string
+ */
+ public static function getPaymentLabel($processor) {
+ $isVisible = FALSE;
+ $paymentTypeLabel = self::getPaymentTypeLabel($processor);
+ foreach (self::getPaymentFieldMetadata(['object' => $processor]) as $paymentField) {
+ if ($paymentField['htmlType'] !== 'hidden') {
+ $isVisible = TRUE;
+ }
+ }
+ return $isVisible ? $paymentTypeLabel : '';
+
+ }
+
}
diff --git a/CRM/Core/Payment/Manual.php b/CRM/Core/Payment/Manual.php
index ecc3c9252004..5621d712800c 100644
--- a/CRM/Core/Payment/Manual.php
+++ b/CRM/Core/Payment/Manual.php
@@ -1,9 +1,9 @@
'billing_first_name',
'middle_name' => 'billing_middle_name',
'last_name' => 'billing_last_name',
@@ -71,10 +71,10 @@ public function getBillingAddressFields($billingLocationID = NULL) {
'country' => "billing_country_id-{$billingLocationID}",
'state_province' => "billing_state_province_id-{$billingLocationID}",
'postal_code' => "billing_postal_code-{$billingLocationID}",
- );
+ ];
}
else {
- return array();
+ return [];
}
}
@@ -84,8 +84,20 @@ public function getBillingAddressFields($billingLocationID = NULL) {
* @return array
*/
public function getPaymentFormFields() {
- return array();
+ if (!$this->isBackOffice()) {
+ return [];
+ }
+
+ $paymentInstrument = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $this->getPaymentInstrumentID());
+ if ($paymentInstrument === 'Credit Card') {
+ return ['credit_card_type', 'pan_truncation'];
+ }
+ elseif ($paymentInstrument === 'Check') {
+ return ['check_number'];
+ }
+ return [];
}
+
/**
* Process payment.
*
@@ -137,6 +149,15 @@ public function setResult($result) {
$this->result = $result;
}
+ /**
+ * Set payment instrument id.
+ *
+ * @param int $paymentInstrumentID
+ */
+ public function setPaymentInstrumentID($paymentInstrumentID) {
+ $this->paymentInstrumentID = $paymentInstrumentID;
+ }
+
/**
* Get the name of the payment type.
*
@@ -152,7 +173,7 @@ public function getPaymentTypeName() {
* @return string
*/
public function getPaymentTypeLabel() {
- return '';
+ return CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $this->getPaymentInstrumentID());
}
/**
@@ -173,6 +194,15 @@ public function supportsEditRecurringContribution() {
return TRUE;
}
+ /**
+ * Are back office payments supported.
+ *
+ * @return bool
+ */
+ protected function supportsBackOffice() {
+ return TRUE;
+ }
+
/**
* Submit a manual payment.
*
@@ -201,4 +231,30 @@ public function isSendReceiptForPending() {
return TRUE;
}
+ /**
+ * Get help text information (help, description, etc.) about this payment,
+ * to display to the user.
+ *
+ * @param string $context
+ * Context of the text.
+ * Only explicitly supported contexts are handled without error.
+ * Currently supported:
+ * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
+ *
+ * @param array $params
+ * Parameters for the field, context specific.
+ *
+ * @return string
+ */
+ public function getText($context, $params) {
+ switch ($context) {
+ case 'contributionPageContinueText':
+ if ($params['amount'] <= 0) {
+ return ts('To complete this transaction, click the Continue button below.');
+ }
+ return ts('To complete your contribution, click the Continue button below.');
+
+ }
+ }
+
}
diff --git a/CRM/Core/Payment/PayJunction.php b/CRM/Core/Payment/PayJunction.php
index 81b113b1f585..42eeb94d4acb 100644
--- a/CRM/Core/Payment/PayJunction.php
+++ b/CRM/Core/Payment/PayJunction.php
@@ -12,11 +12,12 @@
*
* @package CRM
* @author Michael Morris and Gene Chi @ Phase2 Technology " . 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'];
@@ -106,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) {
@@ -123,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;
@@ -143,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;
@@ -152,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) {
@@ -176,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;
}
@@ -185,7 +188,6 @@ public function recur(&$input, &$ids, &$objects, $first) {
$recur->save();
if ($sendNotification) {
-
$autoRenewMembership = FALSE;
if ($recur->id &&
isset($ids['membership']) && $ids['membership']
@@ -207,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,
@@ -236,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 {
@@ -265,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 {
@@ -276,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);
@@ -294,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);
@@ -307,11 +304,11 @@ 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;
@@ -333,23 +330,12 @@ public function main() {
$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('receiver_email', '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 = self::getPayPalPaymentProcessorID($input, $ids);
- $processorInfo = array();
- if (!CRM_Financial_BAO_PaymentProcessor::retrieve($processorParams, $processorInfo)) {
- return FALSE;
- }
- $paymentProcessorID = $processorInfo['id'];
- }
+ Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
- return FALSE;
+ return;
}
self::$_paymentProcessor = &$objects['paymentProcessor'];
@@ -357,29 +343,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);
@@ -389,7 +372,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',
@@ -397,7 +380,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;
@@ -407,6 +390,69 @@ 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
+ */
+ $systemTimeZone = new DateTimeZone(CRM_Core_Config::singleton()->userSystem->getTimeZoneString());
+ $receiveDateTime->setTimezone($systemTimeZone);
+ $input['receive_date'] = $receiveDateTime->format('YmdHis');
+ }
+ }
+
+ /**
+ * 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 d71e9613d520..5b4a109802e0 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;
@@ -137,14 +173,27 @@ public function buildForm(&$form) {
* @param CRM_Core_Form $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']
);
}
}
@@ -173,10 +222,12 @@ 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)) {
- CRM_Core_Payment_Form::validateCreditCard($values, $errors);
+ 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);
}
}
@@ -191,9 +242,10 @@ public function validatePaymentInstrument($values, &$errors) {
*
* @return array
* the result in an nice formatted array (or an error object)
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function setExpressCheckOut(&$params) {
- $args = array();
+ $args = [];
$this->initialize($args, 'SetExpressCheckout');
@@ -237,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']);
}
/**
@@ -252,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;
@@ -268,7 +322,7 @@ public function getExpressCheckoutDetails($token) {
}
/* Success */
- $fieldMap = array(
+ $fieldMap = [
'token' => 'token',
'payer_status' => 'payerstatus',
'payer_id' => 'payerid',
@@ -281,7 +335,7 @@ public function getExpressCheckoutDetails($token) {
'postal_code' => 'shiptozip',
'state_province' => 'shiptostate',
'country' => 'shiptocountrycode',
- );
+ ];
return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
}
@@ -302,7 +356,7 @@ public function doExpressCheckout(&$params) {
if (!empty($params['is_recur'])) {
return $this->createRecurringPayments($params);
}
- $args = array();
+ $args = [];
$this->initialize($args, 'DoExpressCheckoutPayment');
$args['token'] = $params['token'];
@@ -348,13 +402,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'));
@@ -366,15 +423,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=" .
@@ -392,16 +446,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;
}
@@ -422,7 +478,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.
@@ -447,9 +503,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);
@@ -467,15 +521,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'];
@@ -510,7 +565,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'] = "" .
@@ -524,7 +579,7 @@ public function doDirectPayment(&$params, $component = 'contribute') {
$result = $this->invokeAPI($args);
- //WAG
+ // WAG
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
@@ -564,33 +619,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.');
}
@@ -613,9 +668,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 {
@@ -630,9 +686,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;
@@ -645,9 +702,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;
@@ -658,10 +716,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);
@@ -680,23 +739,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();
}
@@ -705,15 +785,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'];
@@ -743,15 +824,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'];
@@ -775,17 +857,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",
- );
+ ];
}
/**
@@ -796,8 +879,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',
@@ -805,13 +888,15 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'membershipID' => 'membershipID',
'related_contact' => 'relatedContactID',
'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
- );
+ 'accountingCode' => 'accountingCode',
+ 'contributionRecurID' => 'contributionRecurID',
+ 'contributionPageID' => 'contributionPageID',
+ ];
foreach ($notifyParameterMap as $paramsName => $notifyName) {
if (!empty($params[$paramsName])) {
$notifyParameters[$notifyName] = $params[$paramsName];
}
}
- $this->setNotifyUrlParameters($notifyParameters);
$notifyURL = $this->getNotifyUrl();
$config = CRM_Core_Config::singleton();
@@ -829,10 +914,10 @@ 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),
+ 'item_name' => $this->getPaymentDescription($params, 127),
'quantity' => 1,
'undefined_quantity' => 0,
'cancel_return' => $cancelURL,
@@ -844,12 +929,12 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'invoice' => $params['invoiceID'],
'lc' => substr($config->lcMessages, -2),
'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
- 'custom' => CRM_Utils_Array::value('accountingCode', $params),
+ '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',
@@ -859,7 +944,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
@@ -887,17 +972,13 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
// if recurring donations, add a few more items
if (!empty($params['is_recur'])) {
- if ($params['contributionRecurID']) {
- $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
- $paypalParams['notify_url'] = $notifyURL;
- }
- else {
+ if (!$params['contributionRecurID']) {
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 +986,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 +1045,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 +1069,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 +1090,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 +1115,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 +1141,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 +1161,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 +1176,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 +1193,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 28ffe414431e..d88f12de7dec 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 +112,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 +162,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 +177,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 +212,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 +237,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 +266,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 +291,7 @@ public function recur(&$input, &$ids, &$objects, $first) {
}
if ($txnType != 'recurring_payment') {
- return TRUE;
+ return;
}
if (!$first) {
@@ -296,9 +300,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 +314,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 +337,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 +348,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,49 +359,77 @@ 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);
}
+ /**
+ * Gets PaymentProcessorID for PayPal
+ *
+ * @return int
+ */
+ public function getPayPalPaymentProcessorID() {
+ // 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 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', [
+ 'is_test' => 0,
+ 'options' => ['limit' => 1],
+ 'payment_processor_type_id' => $paymentProcessorTypeID,
+ 'return' => 'id',
+ ]);
+
+ }
+
/**
* This is the main function to call. It should be sufficient to instantiate the class
* (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
@@ -430,32 +461,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).
- $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
- 'PayPal', 'id', 'name'
- );
- $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', array(
- 'is_test' => 0,
- 'options' => array('limit' => 1),
- 'payment_processor_type_id' => $paymentProcessorTypeID,
- 'return' => 'id',
- ));
+ $paymentProcessorID = self::getPayPalPaymentProcessorID();
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
- return FALSE;
+ return;
}
self::$_paymentProcessor = &$objects['paymentProcessor'];
@@ -466,31 +484,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);
- }
- else {
- return $this->single($input, $ids, $objects, FALSE, FALSE);
+ $this->recur($input, $ids, $objects, $first);
+ return;
}
}
- 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);
@@ -500,7 +514,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',
@@ -508,7 +522,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;
@@ -519,10 +533,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
@@ -539,51 +555,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 = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
- 'PayPal', 'id', 'name'
- );
+ $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);
}
/**
@@ -593,9 +614,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 f94448c53328..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,17 +122,17 @@ public function doDirectPayment(&$params) {
'ORDERDESC' => urlencode($params['description']),
'VERBOSITY' => 'MEDIUM',
'BILLTOCOUNTRY' => urlencode($params['country']),
- );
+ ];
if ($params['installments'] == 1) {
- $params['is_recur'] == FALSE;
+ $params['is_recur'] = FALSE;
}
if ($params['is_recur'] == TRUE) {
$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
@@ -268,7 +269,11 @@ public function doDirectPayment(&$params) {
* Payment successfully sent to gateway - process the response now
*/
$result = strstr($responseData, "RESULT");
- $nvpArray = array();
+ if (empty($result)) {
+ return self::errorExit(9016, "No RESULT code from PayPal.");
+ }
+
+ $nvpArray = [];
while (strlen($result)) {
// name
$keypos = strpos($result, '=');
@@ -299,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
@@ -340,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
*
@@ -360,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
*
@@ -374,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)) {
@@ -414,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
@@ -433,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:
@@ -463,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);
@@ -524,6 +503,9 @@ public function submit_transaction($submiturl, $payflow_query) {
break;
}
}
+ if ($responseHeaders['http_code'] != 200) {
+ return self::errorExit(9015, "Error connecting to the Payflow Pro API server.");
+ }
/*
* Transaction submitted -
@@ -584,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..e3e5b0d1a026 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"),
@@ -308,7 +308,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
$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'])));
+ CRM_Core_Error::fatal(ts($log_message, [1 => $info['http_code'], 2 => $info['url']]));
}
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');
@@ -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 @@
_type) {
+ // @todo not sure when this would be true. Never passed in.
$form->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($form->_type, $form->_mode);
}
@@ -63,10 +65,15 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
}
$form->set('paymentProcessor', $form->_paymentProcessor);
$form->_paymentObject = System::singleton()->getByProcessor($form->_paymentProcessor);
+ if ($form->paymentInstrumentID) {
+ $form->_paymentObject->setPaymentInstrumentID($form->paymentInstrumentID);
+ }
+ $form->_paymentObject->setBackOffice($form->isBackOffice);
+ $form->assign('isBackOffice', $form->isBackOffice);
$form->assign('suppressSubmitButton', $form->_paymentObject->isSuppressSubmitButtons());
- $form->assign('currency', CRM_Utils_Array::value('currency', $form->_values));
+ $form->assign('currency', $form->getCurrency());
// also set cancel subscription url
if (!empty($form->_paymentProcessor['is_recur']) && !empty($form->_values['is_recur'])) {
@@ -74,12 +81,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);
@@ -92,7 +99,9 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
CRM_Core_Payment_Form::setPaymentFieldsByProcessor(
$form,
$form->_paymentProcessor,
- CRM_Utils_Request::retrieve('billing_profile_id', 'String')
+ CRM_Utils_Request::retrieve('billing_profile_id', 'String'),
+ $form->isBackOffice,
+ $form->paymentInstrumentID
);
$form->assign_by_ref('paymentProcessor', $form->_paymentProcessor);
@@ -120,7 +129,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']]
)
);
}
@@ -131,7 +140,7 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
*
* @param CRM_Core_Form $form
*/
- public static function buildQuickform(&$form) {
+ public static function buildQuickForm(&$form) {
//@todo document why this addHidden is here
//CRM-15743 - we should not set/create hidden element for pay later
// because payment processor is not selected
@@ -143,7 +152,7 @@ public static function buildQuickform(&$form) {
if (!empty($processorId)) {
$form->addElement('hidden', 'hidden_processor', 1);
}
- CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, $billing_profile_id, FALSE);
+ CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, $billing_profile_id, $form->isBackOffice, $form->paymentInstrumentID);
}
}
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 f1b4e733361c..68992819af9a 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 2e6aedfb40cc..d1ed8ea0559e 100644
--- a/CRM/Core/Permission.php
+++ b/CRM/Core/Permission.php
@@ -1,9 +1,9 @@
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
return FALSE;
}
else {
+ // This is an individual 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, $contactId);
if (
- !CRM_Core_Config::singleton()->userPermissionClass->check($permission)
+ !$granted
&& !($tempPerm && $tempPerm->check($permission))
) {
//one of our 'and' conditions has not been met
@@ -245,8 +254,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)
@@ -371,7 +380,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')) {
@@ -468,7 +477,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',
@@ -476,7 +485,7 @@ public static function checkActionPermission($module, $action) {
'CiviGrant' => 'edit grants',
'CiviMail' => 'access CiviMail',
'CiviAuction' => 'add auction items',
- );
+ ];
$permissionName = CRM_Utils_Array::value($module, $editPermissions);
}
@@ -576,7 +585,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);
}
@@ -596,7 +605,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) {
@@ -618,7 +627,7 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
foreach ($perm as $p => $attr) {
if (!is_array($attr)) {
- $attr = array($attr);
+ $attr = [$attr];
}
$attr[0] = $info['translatedName'] . ': ' . $attr[0];
@@ -644,11 +653,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')) {
@@ -676,196 +685,848 @@ 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'),
- ),
- 'administer reserved groups' => array(
+ ],
+ 'manage tags' => [
+ $prefix . ts('manage tags'),
+ ts('Create and rename tags'),
+ ],
+ '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;
+ }
+ /**
+ * For each entity provides an array of permissions required for each action
+ *
+ * The action is the array key, possible values:
+ * * create: applies to create (with no id in params)
+ * * update: applies to update, setvalue, create (with id in params)
+ * * get: applies to getcount, getsingle, getvalue and other gets
+ * * delete: applies to delete, replace
+ * * meta: applies to getfields, getoptions, getspec
+ * * default: catch-all for anything not declared
+ *
+ * Note: some APIs declare other actions as well
+ *
+ * Permissions should use arrays for AND and arrays of arrays for OR
+ * @see CRM_Core_Permission::check
+ *
+ * @return array of permissions
+ */
+ public static function getEntityActionPermissions() {
+ $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'] = [
+ // applies to getfields, getoptions, etc.
+ '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' => ['administer CiviCRM'],
+ ];
+
+ // Note: Additional permissions in DynamicFKAuthorization
+ $permissions['attachment'] = [
+ 'default' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ ];
+
+ // Contact permissions
+ $permissions['contact'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'add contacts',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'delete contacts',
+ ],
+ // managed by query object
+ 'get' => [],
+ // managed by _civicrm_api3_check_edit_permissions
+ 'update' => [],
+ 'getquick' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ 'duplicatecheck' => [
+ 'access CiviCRM',
+ ],
+ ];
+
+ // CRM-16963 - Permissions for country.
+ $permissions['country'] = [
+ 'get' => [
+ 'access CiviCRM',
+ ],
+ 'default' => [
+ 'administer CiviCRM',
+ ],
+ ];
+
+ // Contact-related data permissions.
+ $permissions['address'] = [
+ // get is managed by BAO::addSelectWhereClause
+ // create/delete are managed by _civicrm_api3_check_edit_permissions
+ 'default' => [],
+ ];
+ $permissions['email'] = $permissions['address'];
+ $permissions['phone'] = $permissions['address'];
+ $permissions['website'] = $permissions['address'];
+ $permissions['im'] = $permissions['address'];
+ $permissions['open_i_d'] = $permissions['address'];
+
+ // Also managed by ACLs - CRM-19448
+ $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'] = [
+ 'get' => ['access CiviCRM'],
+ 'create' => ['access CiviCRM'],
+ 'update' => ['access CiviCRM'],
+ ];
+
+ //relationship permissions
+ $permissions['relationship'] = [
+ // get is managed by BAO::addSelectWhereClause
+ 'get' => [],
+ 'delete' => [
+ 'access CiviCRM',
+ 'edit all contacts',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'edit all contacts',
+ ],
+ ];
+
+ // CRM-17741 - Permissions for RelationshipType.
+ $permissions['relationship_type'] = [
+ 'get' => [
+ 'access CiviCRM',
+ ],
+ 'default' => [
+ 'administer CiviCRM',
+ ],
+ ];
+
+ // Activity permissions
+ $permissions['activity'] = [
+ 'delete' => [
+ 'access CiviCRM',
+ 'delete activities',
+ ],
+ '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' => [
+ 'access CiviCRM',
+ 'view all activities',
+ ],
+ ];
+ $permissions['activity_contact'] = $permissions['activity'];
+
+ // Case permissions
+ $permissions['case'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'add cases',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'delete in CiviCase',
+ ],
+ 'restore' => [
+ 'administer CiviCase',
+ ],
+ 'merge' => [
+ 'administer CiviCase',
+ ],
+ 'default' => [
+ // At minimum the user needs one of the following. Finer-grained access is controlled by CRM_Case_BAO_Case::addSelectWhereClause
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
+ $permissions['case_contact'] = $permissions['case'];
+
+ $permissions['case_type'] = [
+ 'default' => ['administer CiviCase'],
+ 'get' => [
+ // nested array = OR
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
+
+ // Campaign permissions
+ $permissions['campaign'] = [
+ 'get' => ['access CiviCRM'],
+ 'default' => [
+ // nested array = OR
+ ['administer CiviCampaign', 'manage campaign'],
+ ],
+ ];
+ $permissions['survey'] = $permissions['campaign'];
+
+ // Financial permissions
+ $permissions['contribution'] = [
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'delete in CiviContribute',
+ ],
+ 'completetransaction' => [
+ 'edit contributions',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ ];
+ $permissions['line_item'] = $permissions['contribution'];
+
+ // Payment permissions
+ $permissions['payment'] = [
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'delete in CiviContribute',
+ ],
+ 'cancel' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ ];
+ $permissions['contribution_recur'] = $permissions['payment'];
+
+ // Custom field permissions
+ $permissions['custom_field'] = [
+ 'default' => [
+ 'administer CiviCRM',
+ 'access all custom data',
+ ],
+ ];
+ $permissions['custom_group'] = $permissions['custom_field'];
+
+ // Event permissions
+ $permissions['event'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit all events',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'delete in CiviEvent',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'view event info',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit all events',
+ ],
+ ];
+ // Loc block is only used for events
+ $permissions['loc_block'] = $permissions['event'];
+
+ $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'] = [
+ 'default' => [
+ ['access CiviEvent', 'access CiviContribute', 'access CiviMember'],
+ ],
+ 'get' => [
+ ['access CiviCRM', 'view event info', 'make online contributions'],
+ ],
+ ];
+
+ // File permissions
+ $permissions['file'] = [
+ 'default' => [
+ 'access CiviCRM',
+ 'access uploaded files',
+ ],
+ ];
+ $permissions['files_by_entity'] = $permissions['file'];
+
+ // Group permissions
+ $permissions['group'] = [
+ 'get' => [
+ 'access CiviCRM',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'edit groups',
+ ],
+ ];
+
+ $permissions['group_nesting'] = $permissions['group'];
+ $permissions['group_organization'] = $permissions['group'];
+
+ //Group Contact permission
+ $permissions['group_contact'] = [
+ 'get' => [
+ 'access CiviCRM',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'edit all contacts',
+ ],
+ ];
+
+ // CiviMail Permissions
+ $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'] = [
+ 'get' => [
+ 'access CiviCRM',
+ $civiMailBasePerms,
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ $civiMailBasePerms,
+ 'delete in CiviMail',
+ ],
+ 'submit' => [
+ 'access CiviCRM',
+ ['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'] = [
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviMail',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviMail',
+ 'delete in CiviMail',
+ ],
+ 'submit' => [
+ 'access CiviCRM',
+ ['access CiviMail', 'schedule mailings'],
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'access CiviMail',
+ ],
+ ];
+
+ // Membership permissions
+ $permissions['membership'] = [
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'delete in CiviMember',
+ ],
+ 'default' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'edit memberships',
+ ],
+ ];
+ $permissions['membership_status'] = $permissions['membership'];
+ $permissions['membership_type'] = $permissions['membership'];
+ $permissions['membership_payment'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'edit memberships',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'delete in CiviMember',
+ 'access CiviContribute',
+ 'delete in CiviContribute',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'access CiviContribute',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ 'access CiviMember',
+ 'edit memberships',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ ];
+
+ // Participant permissions
+ $permissions['participant'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'register for events',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit event participants',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'view event participants',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit event participants',
+ ],
+ ];
+ $permissions['participant_payment'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'register for events',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit event participants',
+ 'access CiviContribute',
+ 'delete in CiviContribute',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'view event participants',
+ 'access CiviContribute',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ 'access CiviEvent',
+ 'edit event participants',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ ];
+
+ // Pledge permissions
+ $permissions['pledge'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'edit pledges',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'delete in CiviPledge',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ ],
+ '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'] = [
+ 'update' => [
+ [
+ 'access CiviCRM',
+ 'edit all events',
+ ],
+ ],
+ ];
+
+ $permissions['pledge_payment'] = [
+ 'create' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'edit pledges',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ 'delete' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'delete in CiviPledge',
+ 'access CiviContribute',
+ 'delete in CiviContribute',
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'access CiviContribute',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ 'access CiviPledge',
+ 'edit pledges',
+ 'access CiviContribute',
+ 'edit contributions',
+ ],
+ ];
+
+ // Profile permissions
+ $permissions['profile'] = [
+ // the profile will take care of this
+ 'get' => [],
+ ];
+
+ $permissions['uf_group'] = [
+ 'create' => [
+ 'access CiviCRM',
+ [
+ 'administer CiviCRM',
+ 'manage event profiles',
+ ],
+ ],
+ 'get' => [
+ 'access CiviCRM',
+ ],
+ 'update' => [
+ 'access CiviCRM',
+ [
+ 'administer CiviCRM',
+ 'manage event profiles',
+ ],
+ ],
+ ];
+ $permissions['uf_field'] = $permissions['uf_join'] = $permissions['uf_group'];
+ $permissions['uf_field']['delete'] = [
+ 'access CiviCRM',
+ [
+ 'administer CiviCRM',
+ 'manage event profiles',
+ ],
+ ];
+ $permissions['option_value'] = $permissions['uf_group'];
+ $permissions['option_group'] = $permissions['option_value'];
+
+ $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;
}
+ /**
+ * Translate an unknown action to a canonical form.
+ *
+ * @param string $action
+ *
+ * @return string
+ * the standardised action name
+ */
+ public static function getGenericAction($action) {
+ $snippet = substr($action, 0, 3);
+ if ($action == 'replace' || $snippet == 'del') {
+ // 'Replace' is a combination of get+create+update+delete; however, the permissions
+ // on each of those will be tested separately at runtime. This is just a sniff-test
+ // based on the heuristic that 'delete' tends to be the most closely guarded
+ // of the necessary permissions.
+ $action = 'delete';
+ }
+ elseif ($action == 'setvalue' || $snippet == 'upd') {
+ $action = 'update';
+ }
+ elseif ($action == 'getfields' || $action == 'getfield' || $action == 'getspec' || $action == 'getoptions') {
+ $action = 'meta';
+ }
+ elseif ($snippet == 'get') {
+ $action = 'get';
+ }
+ return $action;
+ }
+
/**
* Validate user permission across.
* edit or view or with supportable acls.
@@ -884,17 +1545,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,
@@ -919,7 +1580,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) {
@@ -983,8 +1644,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 0f126e8dafad..e2277df2f173 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 +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;
}
@@ -145,7 +148,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 +156,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 333e0d9d2c85..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 6f2de9079d3d..9c0bbdee78c9 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 dd70a79bbcfb..d969ed42373f 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 5d8da45f3f24..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 3221e869cd46..b691211be25a 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 +162,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 +193,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 +245,7 @@ public function getContactEmails($uids) {
$dao = CRM_Core_DAO::executeQuery($sql);
- $emails = array();
+ $emails = [];
while ($dao->fetch()) {
$emails[] = $dao->email;
}
@@ -292,13 +292,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 0f24fc16c91d..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 a8d79883a411..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 dafb7068db90..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..6c355050e757
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Interface.php
@@ -0,0 +1,133 @@
+ ['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);
+
+}
diff --git a/CRM/Core/PrevNextCache/Redis.php b/CRM/Core/PrevNextCache/Redis.php
new file mode 100644
index 000000000000..a08d9ba0c614
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Redis.php
@@ -0,0 +1,255 @@
+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];
+ }
+
+}
diff --git a/CRM/Core/PrevNextCache/Sql.php b/CRM/Core/PrevNextCache/Sql.php
new file mode 100644
index 000000000000..10fed3637e24
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Sql.php
@@ -0,0 +1,275 @@
+ ['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;
+ }
+
+}
diff --git a/CRM/Core/PseudoConstant.php b/CRM/Core/PseudoConstant.php
index 9638078a6da2..0af4bd1e105f 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
if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
$customField = new CRM_Core_BAO_CustomField();
$customField->id = (int) substr($fieldName, 7);
- $options = $customField->getOptions();
+ $options = $customField->getOptions($context);
if ($options && $flip) {
$options = array_flip($options);
}
@@ -246,18 +242,18 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
// if callback is specified..
if (!empty($pseudoconstant['callback'])) {
- $fieldOptions = call_user_func(Civi\Core\Resolver::singleton()->get($pseudoconstant['callback']));
+ $fieldOptions = call_user_func(Civi\Core\Resolver::singleton()->get($pseudoconstant['callback']), $context);
//CRM-18223: Allow additions to field options via hook.
CRM_Utils_Hook::fieldOptions($entity, $fieldName, $fieldOptions, $params);
return $fieldOptions;
}
// 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) {
@@ -321,7 +317,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$select = "SELECT %1 AS id, %2 AS label";
$from = "FROM %3";
- $wheres = array();
+ $wheres = [];
$order = "ORDER BY %2";
// Use machine name in certain contexts
@@ -340,7 +336,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
}
// 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 +346,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 +365,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 ');
@@ -382,12 +378,9 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$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);
@@ -405,7 +398,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;
}
@@ -503,7 +496,7 @@ public static function getOptionEditUrl($fieldSpec) {
}
/**
- * 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,13 +534,14 @@ public static function populate(
$key = 'id',
$force = NULL
) {
- $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
+ $cacheKey = CRM_Core_BAO_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;
}
+ /* @var CRM_Core_DAO $object */
$object = new $name();
$object->selectAdd();
@@ -565,10 +559,14 @@ public static function populate(
if (!$all) {
$object->$filter = 1;
+ $aclClauses = array_filter($name::getSelectWhereClause());
+ foreach ($aclClauses as $clause) {
+ $object->whereAdd($clause);
+ }
}
$object->find();
- $var = array();
+ $var = [];
while ($object->fetch()) {
$var[$object->$key] = $object->$retrieve;
}
@@ -580,7 +578,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') {
@@ -589,6 +586,9 @@ public static function flush($name = 'cache') {
}
if ($name == 'cache') {
CRM_Core_OptionGroup::flushAll();
+ if (isset(\Civi::$statics[__CLASS__])) {
+ unset(\Civi::$statics[__CLASS__]);
+ }
}
}
@@ -616,7 +616,7 @@ public static function &activityType() {
$index .= '_' . (int) $onlyComponentActivities;
if (NULL === self::$activityType) {
- self::$activityType = array();
+ self::$activityType = [];
}
if (!isset(self::$activityType[$index]) || $reset) {
@@ -629,7 +629,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
@@ -687,7 +687,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));
}
@@ -704,9 +704,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);
}
}
@@ -741,12 +741,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];
@@ -757,7 +757,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);
@@ -775,6 +775,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.
*
@@ -789,14 +815,14 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
*
* @param bool $applyLimit
*
- * @return array
+ * @return array|null
* array reference of all countries.
*/
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
@@ -804,9 +830,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);
@@ -835,9 +861,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);
}
}
@@ -846,7 +872,7 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
return self::$country[$id];
}
else {
- return CRM_Core_DAO::$_nullObject;
+ return NULL;
}
}
return self::$country;
@@ -903,19 +929,18 @@ public static function &countryIsoCode($id = FALSE) {
* array reference of all groups.
*/
public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
- $condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
-
- if (!self::$group) {
- self::$group = array();
+ 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);
- if (!isset(self::$group[$groupKey])) {
- self::$group[$groupKey] = NULL;
- self::populate(self::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
+ if (!isset(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey])) {
+ self::populate(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
}
- return self::$group[$groupKey];
+ return Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey];
}
/**
@@ -1003,7 +1028,7 @@ public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $exc
* Db column name/label.
* @param bool $reset
* Reset relationship types if true.
- * @param bool|NULL $isActive
+ * @param bool $isActive
* Filter by is_active. NULL to disable.
*
* @return array
@@ -1012,7 +1037,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";
@@ -1027,7 +1052,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,
@@ -1035,7 +1060,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",
- );
+ ];
}
}
@@ -1053,275 +1078,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;
}
@@ -1463,10 +1226,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);
}
@@ -1489,7 +1252,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])) {
@@ -1510,7 +1273,7 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
$cacheKey = "{$countryID}_{$field}";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1522,16 +1285,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;
}
@@ -1541,9 +1304,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);
}
@@ -1571,7 +1334,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;
}
@@ -1582,7 +1345,7 @@ public static function &countyForState($stateID) {
$cacheKey = "{$stateID}_name";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1594,16 +1357,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;
}
@@ -1618,12 +1381,12 @@ public static function &countyForState($stateID) {
*
* @param int $stateID
*
- * @return int
+ * @return int|null
* the country id that the state belongs to
*/
public static function countryIDForStateID($stateID) {
if (empty($stateID)) {
- return CRM_Core_DAO::$_nullObject;
+ return NULL;
}
$query = "
@@ -1631,7 +1394,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);
}
@@ -1651,6 +1414,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
@@ -1659,11 +1426,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 =';
@@ -1683,40 +1446,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];
}
/**
@@ -1733,7 +1466,7 @@ public static function &greetingDefaults() {
*/
public static function &getExtensions() {
if (!self::$extensions) {
- self::$extensions = array();
+ self::$extensions = [];
$sql = '
SELECT full_name, label
FROM civicrm_extension
@@ -1788,7 +1521,6 @@ public static function getModuleExtensions($fresh = FALSE) {
return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
}
-
/**
* Get all tax rates.
*
@@ -1799,13 +1531,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) {
@@ -1815,7 +1547,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 = '';
@@ -1836,4 +1568,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 5a666e58d850..c36855e66717 100644
--- a/CRM/Core/QuickForm/Action.php
+++ b/CRM/Core/QuickForm/Action.php
@@ -1,9 +1,9 @@
toSmarty();
// Deprecated - use snippet=6 instead of json=1
- $json = CRM_Utils_Request::retrieve('json', 'Boolean', CRM_Core_DAO::$_nullObject);
+ $json = CRM_Utils_Request::retrieve('json', 'Boolean');
if ($json) {
CRM_Utils_JSON::output($form);
}
@@ -152,7 +152,7 @@ public function renderForm(&$page) {
}
if ($controller->_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 b532a74bd24e..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 031a68f677f1..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]);
}
- $data['values'][$pageName][$uploadName] = 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 411d30627bdf..a3e1fe73f8a7 100644
--- a/CRM/Core/Reference/Basic.php
+++ b/CRM/Core/Reference/Basic.php
@@ -78,11 +78,16 @@ public function matchesTargetTable($tableName) {
*/
public function findReferences($targetDao) {
$targetColumn = $this->getTargetKey();
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
- );
+ $select = 'id';
+ // CRM-19385: Since id is removed, return all rows for cache tables.
+ if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists($this->getReferenceTable(), 'id')) {
+ $select = '*';
+ }
+ $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]) . ' ' . $description . ' ' . $description . ' ' . 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 ffe3b7f56386..a78d34f0263c 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
@@ -98,8 +98,10 @@ public function build_price_options($event) {
if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
(CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE)) {
$field_name = "event_{$event->id}_price_{$field['id']}";
- CRM_Price_BAO_PriceField::addQuickFormElement($this, $field_name, $field['id'], FALSE);
- $price_fields_for_event[] = $field_name;
+ if (!empty($field['options'])) {
+ CRM_Price_BAO_PriceField::addQuickFormElement($this, $field_name, $field['id'], FALSE);
+ $price_fields_for_event[] = $field_name;
+ }
}
}
}
@@ -126,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}"])) {
@@ -139,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...
@@ -163,11 +165,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,
+ ]);
}
}
}
@@ -184,7 +186,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)
@@ -192,8 +194,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();
@@ -244,7 +246,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)) {
@@ -257,8 +259,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) {
@@ -278,14 +280,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);
diff --git a/CRM/Event/Cart/Form/Checkout/Payment.php b/CRM/Event/Cart/Form/Checkout/Payment.php
index 9bf8430f1688..d6906fd94ce6 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,7 +42,7 @@ 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';
@@ -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(
+ $payment_params = [
'participant_id' => $participant->id,
'contribution_id' => $params['contributionID'],
- );
- $ids = array();
- CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
+ ];
+ CRM_Event_BAO_ParticipantPayment::create($payment_params);
}
$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;
@@ -183,7 +182,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 +200,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 +219,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 +252,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 +260,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 +299,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 +322,15 @@ 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;
}
/**
- * @return mixed
- */
- public function getDefaultFrom() {
- $values = CRM_Core_OptionGroup::values('from_email_address');
- return $values[1];
- }
-
- /**
- * @param $events_in_cart
+ * Send email receipt.
+ *
+ * @param array $events_in_cart
* @param array $params
*/
public function emailReceipt($events_in_cart, $params) {
@@ -351,19 +344,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' => 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,
@@ -383,11 +376,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',
@@ -397,7 +390,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]);
}
@@ -406,14 +399,16 @@ public function emailReceipt($events_in_cart, $params) {
}
/**
- * @param $fields
- * @param $files
- * @param $self
+ * Apply form rules.
+ *
+ * @param array $fields
+ * @param array $files
+ * @param CRM_Core_Form $self
*
* @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);
@@ -426,6 +421,8 @@ public static function formRule($fields, $files, $self) {
}
/**
+ * Validate form.
+ *
* @todo this should surely go! Test & remove.
* @return bool
*/
@@ -439,6 +436,9 @@ public function validate() {
return parent::validate();
}
+ /**
+ * Pre-process form.
+ */
public function preProcess() {
$params = $this->_submitValues;
$this->is_pay_later = CRM_Utils_Array::value('is_pay_later', $params, FALSE) && !CRM_Utils_Array::value('payment_completed', $params);
@@ -446,6 +446,9 @@ public function preProcess() {
parent::preProcess();
}
+ /**
+ * Post process form.
+ */
public function postProcess() {
$transaction = new CRM_Core_Transaction();
@@ -454,8 +457,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();
@@ -463,18 +466,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,
@@ -485,7 +488,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);
@@ -518,11 +521,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);
@@ -544,7 +547,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));
}
@@ -580,9 +583,11 @@ public function postProcess() {
}
/**
+ * Make payment.
+ *
* @param array $params
*
- * @return array|void
+ * @return array
* @throws Exception
*/
public function make_payment(&$params) {
@@ -609,18 +614,20 @@ 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;
}
/**
- * @param $mer_participant
+ * Record contribution.
+ *
+ * @param CRM_Event_BAO_Participant $mer_participant
* @param array $params
- * @param $event
+ * @param CRM_Event_BAO_Event $event
*
* @return object
* @throws Exception
@@ -640,7 +647,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'],
@@ -656,26 +663,26 @@ 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;
return $contribution;
}
+ /**
+ * 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;
@@ -691,6 +698,8 @@ public function saveDataToSession() {
}
/**
+ * Set form default values.
+ *
* @return array
*/
public function setDefaultValues() {
@@ -704,7 +713,7 @@ public function setDefaultValues() {
$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) {
@@ -741,18 +750,23 @@ public function setDefaultValues() {
}
/**
+ * Apply discount.
+ *
* @param string $discountCode
* @param array $price_set_amount
- * @param $cost
+ * @param float $cost
+ * @param int $event_id
+ *
+ * @return bool
*/
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()) {
if ($dao->is_active != '1') {
- return;
+ return FALSE;
}
}
$discounted_priceset_ids = _cividiscount_get_discounted_priceset_ids();
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 6695c8a473d8..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
+ * 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,
- ) ,
- 'event_title' => array(
+ 'title' => ts('Event ID'),
+ 'description' => ts('Event'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'event_type_id' => array(
+ ],
+ ],
+ '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.',
- 'html' => array(
+ 'title' => ts('Event Type'),
+ 'description' => ts('Event Type ID.Implicit FK to civicrm_option_value where option_group = event_type.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Participant Listing'),
+ 'description' => ts('Should we expose the participant list? Implicit FK to civicrm_option_value where option_group = participant_listing.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Is Online Registration'),
+ 'description' => ts('If true, include registration link on Event Info page.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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.',
- 'html' => array(
+ 'title' => ts('Registration Start Date'),
+ 'description' => ts('Date and time that online registration starts.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Registration End Date'),
+ 'description' => ts('Date and time that online registration ends.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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.',
- 'html' => array(
+ '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.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ '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?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this Event enabled or disabled/cancelled?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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.'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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'),
+ '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',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'footer_text' => array(
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_title' => array(
+ ],
+ ],
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_footer_text' => array(
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_email_confirm' => array(
+ ],
+ ],
+ '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.',
- 'html' => array(
+ 'title' => ts('Is confirm email'),
+ 'description' => ts('If true, confirmation is automatically emailed to contact on successful registration.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'default_discount_fee_id' => array(
+ 'title' => ts('Default Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ ],
+ '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.',
- ) ,
- 'thankyou_title' => array(
+ 'title' => ts('Default Discount Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'thankyou_footer_text' => array(
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_pay_later' => array(
+ ],
+ ],
+ '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',
- 'html' => array(
+ 'title' => ts('Pay Later Allowed'),
+ 'description' => ts('if true - allows the user to send payment directly to the org later'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('Pay Later Text'),
+ 'description' => ts('The text displayed to the user in the main form'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pay_later_receipt' => array(
+ ],
+ ],
+ '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',
- 'html' => array(
+ 'title' => ts('Pay Later Receipt Text'),
+ 'description' => ts('The receipt sent to the user instead of the normal receipt text'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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',
- 'html' => array(
+ 'title' => ts('Partial Payments Enabled'),
+ 'description' => ts('is partial payment enabled for this event'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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',
- 'html' => array(
+ 'title' => ts('Initial Amount Help Text'),
+ 'description' => ts('Initial amount help text for partial payment'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('Allow Multiple Registrations'),
+ 'description' => ts('if true - allows the user to register multiple participants for event'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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',
- ) ,
- 'allow_same_participant_emails' => array(
+ 'title' => ts('Maximum number of additional participants per registration'),
+ 'description' => ts('Maximum number of additional participants that can be registered on a single booking'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ ],
+ '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.',
- 'html' => array(
+ '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.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Waitlist Enabled'),
+ 'description' => ts('Whether the event has waitlist support.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Requires Approval'),
+ 'description' => ts('Whether participants require approval before they can finish registering.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Expiration Time'),
+ 'description' => ts('Expire pending but unconfirmed registrations after this many hours.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Allow Self-service Cancellation or Transfer'),
+ 'description' => ts('Allow self service cancellation or transfer for event?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ '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.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'title' => ts('Is an Event Template'),
+ 'description' => ts('whether the event has template'),
+ 'required' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 1,
+ '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'),
+ '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.',
- ) ,
- 'currency' => array(
+ 'title' => ts('Event Created Date'),
+ 'description' => ts('Date and time that event was created.'),
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'campaign_id' => array(
+ ]
+ ],
+ '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.'),
+ '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?'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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.'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ 'localizable' => 0,
+ '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'),
'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',
- 'html' => array(
+ 'title' => ts('Is billing block required'),
+ 'description' => ts('if true than billing block is required this event'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_event',
+ 'entity' => 'Event',
+ 'bao' => 'CRM_Event_BAO_Event',
+ '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
*
@@ -1280,10 +1628,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
*
@@ -1291,8 +1640,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 = [
+ 'index_event_type_id' => [
+ 'name' => 'index_event_type_id',
+ 'field' => [
+ 0 => 'event_type_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_event::0::event_type_id',
+ ],
+ 'index_participant_listing_id' => [
+ 'name' => 'index_participant_listing_id',
+ 'field' => [
+ 0 => 'participant_listing_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_event::0::participant_listing_id',
+ ],
+ 'index_parent_event_id' => [
+ 'name' => 'index_parent_event_id',
+ 'field' => [
+ 0 => 'parent_event_id',
+ ],
+ '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 8cec1e724966..93be1828dbd8 100644
--- a/CRM/Event/DAO/Participant.php
+++ b/CRM/Event/DAO/Participant.php
@@ -1,95 +1,82 @@
__table = 'civicrm_participant';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'participant_contact_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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',
- 'html' => array(
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'participant_source' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ '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,
- ) ,
- 'participant_fee_level' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ '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
+ '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,
+ '),
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_level',
'headerPattern' => '/^(f(ee\s)?level)$/i',
'dataPattern' => '',
- 'export' => true,
- ) ,
- 'participant_is_test' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'participant_is_pay_later' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'participant_fee_amount' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_amount',
'headerPattern' => '/fee(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
- ) ,
- 'participant_registered_by_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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'),
'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',
- 'html' => array(
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'participant_campaign_id' => array(
+ ]
+ ],
+ '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',
- ) ,
- 'cart_id' => array(
+ 'title' => ts('Discount Amount'),
+ 'description' => ts('Discount Amount'),
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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',
- ) ,
- 'transferred_to_contact_id' => array(
+ 'title' => ts('Must Wait on List'),
+ 'description' => ts('On Waiting List'),
+ 'table_name' => 'civicrm_participant',
+ 'entity' => 'Participant',
+ 'bao' => 'CRM_Event_BAO_Participant',
+ 'localizable' => 0,
+ ],
+ '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
*
@@ -485,10 +573,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
*
@@ -496,8 +585,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 = [
+ 'index_status_id' => [
+ 'name' => 'index_status_id',
+ 'field' => [
+ 0 => 'status_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_participant::0::status_id',
+ ],
+ 'index_role_id' => [
+ 'name' => 'index_role_id',
+ 'field' => [
+ 0 => 'role_id',
+ ],
+ '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 b3cca363ff45..91838cbf532e 100644
--- a/CRM/Event/DAO/ParticipantPayment.php
+++ b/CRM/Event/DAO/ParticipantPayment.php
@@ -1,159 +1,158 @@
__table = 'civicrm_participant_payment';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'participant_id' => array(
+ 'title' => ts('Payment ID'),
+ 'description' => ts('Participant Payment Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_participant_payment',
+ 'entity' => 'ParticipantPayment',
+ 'bao' => 'CRM_Event_BAO_ParticipantPayment',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
+ '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
*
@@ -161,10 +160,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
*
@@ -172,8 +172,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 = [
+ 'UI_contribution_participant' => [
+ 'name' => 'UI_contribution_participant',
+ 'field' => [
+ 0 => 'contribution_id',
+ 1 => 'participant_id',
+ ],
+ '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 0d381e757520..00c8d1def9bd 100644
--- a/CRM/Event/DAO/ParticipantStatusType.php
+++ b/CRM/Event/DAO/ParticipantStatusType.php
@@ -1,238 +1,266 @@
__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,
- ) ,
- 'participant_status' => array(
+ 'title' => ts('Participant Status Type ID'),
+ 'description' => ts('unique participant status type id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'label' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'class' => array(
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 1,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ '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',
- ) ,
- 'is_active' => array(
+ 'title' => ts('Participant Status Is Reserved?>'),
+ 'description' => ts('whether this is a status type required by the system'),
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => '1',
- ) ,
- 'is_counted' => array(
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ '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',
- ) ,
- 'weight' => array(
+ 'title' => ts('Participant Status Counts?'),
+ 'description' => ts('whether this status type is counted against event size limit'),
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'controls sort order',
- 'required' => true,
- ) ,
- 'visibility_id' => array(
+ 'title' => ts('Order'),
+ 'description' => ts('controls sort order'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ ],
+ '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',
- 'html' => array(
+ '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'),
+ 'table_name' => 'civicrm_participant_status_type',
+ 'entity' => 'ParticipantStatusType',
+ 'bao' => 'CRM_Event_BAO_ParticipantStatusType',
+ 'localizable' => 0,
+ '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
*
@@ -240,10 +268,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
*
@@ -251,8 +280,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 = [];
+ 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 db8b38ffd490..f5972943bfde 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'];
@@ -83,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);
@@ -112,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
@@ -138,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
@@ -178,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)) {
@@ -225,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];
@@ -249,7 +240,6 @@ public static function setDefaultValues(&$form) {
/**
* This function sets the default values for price set.
*
- *
* @param int $participantID
* @param int $eventID
* @param bool $includeQtyZero
@@ -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');
}
@@ -272,13 +262,13 @@ public static function setDefaultPriceSet($participantID, $eventID = NULL, $incl
}
// use line items for setdefault price set fields, CRM-4090
- $lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID, 'participant', NULL, $includeQtyZero);
+ $lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID, 'participant', FALSE, $includeQtyZero);
if (is_array($lineItems[$participantID]) &&
!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']);
}
}
@@ -362,14 +352,14 @@ public static function buildQuickForm(&$form) {
}
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) {
@@ -407,15 +397,14 @@ public static function buildQuickForm(&$form) {
&& !CRM_Utils_Array::value('fee', $form->_values)
&& CRM_Utils_Array::value('snippet', $_REQUEST) == CRM_Core_Smarty::PRINT_NOFORM
) {
- $form->assign('isFTPermissionDenied', TRUE);
+ CRM_Core_Session::setStatus(ts('You do not have all the permissions needed for this page.'), 'Permission Denied', 'error');
return FALSE;
}
- if ($form->_mode) {
- CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE);
- }
- elseif (!$form->_mode) {
+
+ 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()) {
@@ -427,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();
@@ -443,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'),
@@ -486,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']);
@@ -512,4 +486,19 @@ public static function buildQuickForm(&$form) {
$form->assign('hasPayment', $form->_paymentId);
}
+ /**
+ * Get the default payment instrument id.
+ *
+ * @todo resolve relationship between this form & abstractEdit -which should be it's parent.
+ *
+ * @return int
+ */
+ protected static function getDefaultPaymentInstrumentId() {
+ $paymentInstrumentID = CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer');
+ if ($paymentInstrumentID) {
+ return $paymentInstrumentID;
+ }
+ return key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
+ }
+
}
diff --git a/CRM/Event/Form/ManageEvent.php b/CRM/Event/Form/ManageEvent.php
index b502289b7b59..cd013d81cc3a 100644
--- a/CRM/Event/Form/ManageEvent.php
+++ b/CRM/Event/Form/ManageEvent.php
@@ -1,9 +1,9 @@
_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
@@ -203,12 +205,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 +220,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 +231,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,15 +257,15 @@ 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'];
@@ -303,44 +305,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 +359,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,7 +376,7 @@ 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))
+ [1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className)]
), ts('Saved'), 'success');
$config = CRM_Core_Config::singleton();
@@ -423,7 +425,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 1b10cae99ae1..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 8ff294c04311..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 bf9b7872769e..31317c09aa8d 100644
--- a/CRM/Event/Form/ManageEvent/EventInfo.php
+++ b/CRM/Event/Form/ManageEvent/EventInfo.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'settings');
if ($this->_id) {
$this->assign('entityID', $this->_id);
@@ -112,11 +114,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;
}
@@ -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']);
+ $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
@@ -242,11 +231,8 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
//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);
@@ -268,11 +254,12 @@ public function postProcess() {
$params = array_merge(CRM_Event_BAO_Event::getTemplateDefaultValues($params['template_id']), $params);
}
- $event = CRM_Event_BAO_Event::create($params);
-
// 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 +274,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 b235f9b0ee59..3a02919e228b 100644
--- a/CRM/Event/Form/ManageEvent/Fee.php
+++ b/CRM/Event/Form/ManageEvent/Fee.php
@@ -1,9 +1,9 @@
assign('selectedChild', '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,12 +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,
- '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 4e50b515d83c..a9f5ccb6c62e 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');
diff --git a/CRM/Event/Form/Task/PickProfile.php b/CRM/Event/Form/Task/PickProfile.php
index 59daf4afba48..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 f7e0d0917a01..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 1e8047af6255..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 1e18d7fdb6ea..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 b87cbff8480d..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 6cd2268fba97..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 2ff08f17b613..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 a94c0be47c7b..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']
);
@@ -422,10 +436,10 @@ public function buildQuickForm() {
$_showHide->addToTemplate();
// text length for alpha numeric data types
- $this->add('text',
+ $this->add('number',
'text_length',
ts('Database field length'),
- $attributes['text_length'],
+ $attributes['text_length'] + ['min' => 1],
FALSE
);
$this->addRule('text_length', ts('Value should be a positive number'), 'integer');
@@ -447,30 +461,31 @@ 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
- $this->add('text',
+ $this->add('number',
'note_columns',
ts('Width (columns)') . ' ',
$attributes['note_columns'],
FALSE
);
- $this->add('text',
+ $this->add('number',
'note_rows',
ts('Height (rows)') . ' ',
$attributes['note_rows'],
FALSE
);
- $this->add('text',
+ $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
);
@@ -479,7 +494,7 @@ public function buildQuickForm() {
$this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
// weight
- $this->add('text', 'weight', ts('Order'),
+ $this->add('number', 'weight', ts('Order'),
$attributes['weight'],
TRUE
);
@@ -489,7 +504,7 @@ public function buildQuickForm() {
$this->add('advcheckbox', 'is_required', ts('Required?'));
// checkbox / radio options per line
- $this->add('text', 'options_per_line', ts('Options Per Line'));
+ $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'];
}
@@ -959,6 +973,8 @@ public function postProcess() {
switch ($params['data_type']) {
case 'StateProvince':
$fieldStateProvince = $strtolower($params['default_value']);
+
+ // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
$query = "
SELECT id
FROM civicrm_state_province
@@ -972,6 +988,8 @@ public function postProcess() {
case 'Country':
$fieldCountry = $strtolower($params['default_value']);
+
+ // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
$query = "
SELECT id
FROM civicrm_country
@@ -1003,7 +1021,7 @@ public function postProcess() {
// reset the cache
CRM_Core_BAO_Cache::deleteGroup('contact fields');
- $msg = '$1
', $item['description']);
- $description = strip_tags($description, "
");
- // Add paragraph markup if it's missing.
- if (strpos($description, '$1
', $item['description']);
+ $description = strip_tags($description, "
");
+ $description = preg_replace('/(<[^>]+) style=["\'].*?["\']/i', '$1', $description);
+ // Add paragraph markup if it's missing.
+ if (strpos($description, '
' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
- array(
+ [
1 => $allStatuses[$statusChangeTo],
2 => $results['mailedParticipants'][$processedId],
- )
+ ]
);
}
}
@@ -1654,9 +1668,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;
@@ -1678,10 +1692,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,
- )
+ ]
);
}
@@ -1722,9 +1736,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();
@@ -1767,22 +1781,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;
@@ -1799,7 +1817,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']}"
@@ -1825,16 +1843,15 @@ 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'];
$checkDiscount = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
if (!empty($checkDiscount)) {
$mainAmount = self::getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel);
- $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Discounts Account is' "));
- $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
- $financialTypeID, $relationTypeId);
+ $transactionParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
+ $financialTypeID, 'Discounts Account is');
if (!empty($transactionParams['trxnParams']['from_financial_account_id'])) {
$transactionParams['trxnParams']['total_amount'] = $mainAmount - $total_amount;
$transactionParams['trxnParams']['payment_processor_id'] = NULL;
@@ -1866,319 +1883,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
- unset($insertLines[$previousLineItem['price_field_value_id']]);
- // 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);
- }
- 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();
- $financialItemsArray = 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) {
- $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) {
- $total = 0;
- foreach ($ids as $val) {
- $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
- }
- $updatedAmount = $total;
- }
- 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);
- 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
- );
- $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
- $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
- $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
@@ -2191,35 +1895,26 @@ 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,
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- $activityType,
- 'name'
- ),
+ $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_OptionGroup::getValue('activity_status',
- 'Completed',
- 'name'
- ),
+ '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);
}
@@ -2235,8 +1930,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
@@ -2258,9 +1953,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 e9f1e5c2caa4..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 802c7363d35d..a897d21cc34f 100644
--- a/CRM/Event/BAO/ParticipantStatusType.php
+++ b/CRM/Event/BAO/ParticipantStatusType.php
@@ -1,9 +1,9 @@
id = $id;
- $dao->find(TRUE);
+ if (!$dao->find()) {
+ return FALSE;
+ }
$dao->delete();
return TRUE;
}
@@ -121,9 +124,8 @@ public static function setIsActive($id, $isActive) {
*/
public static function process($params) {
- $returnMessages = array();
+ $returnMessages = [];
- $participantRole = CRM_Event_PseudoConstant::participantRole();
$pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
$expiredStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
$waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
@@ -131,12 +133,10 @@ public static function process($params) {
//build the required status ids.
$statusIds = '(' . implode(',', array_merge(array_keys($pendingStatuses), array_keys($waitingStatuses))) . ')';
- $participantDetails = $fullEvents = array();
+ $participantDetails = $fullEvents = [];
$expiredParticipantCount = $waitingConfirmCount = $waitingApprovalCount = 0;
//get all participant who's status in class pending and waiting
- $query = "SELECT * FROM civicrm_participant WHERE status_id IN {$statusIds} ORDER BY register_date";
-
$query = "
SELECT participant.id,
participant.contact_id,
@@ -159,7 +159,7 @@ public static function process($params) {
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
@@ -172,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)) {
@@ -197,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();
@@ -247,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);
}
@@ -258,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
@@ -319,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 7bce9747f77b..5f8e8bf00023 100644
--- a/CRM/Event/BAO/Query.php
+++ b/CRM/Event/BAO/Query.php
@@ -1,9 +1,9 @@
_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
*/
@@ -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,17 +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':
+ $val_regexp = [];
foreach ($value 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('|', $value);
+ $feeLabel = implode('|', $val_regexp);
$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;
@@ -371,7 +373,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 +383,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 +402,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;
@@ -410,6 +411,8 @@ public static function whereClauseSingle(&$values, &$query) {
$qillName = $name;
$name = 'role_id';
+ $dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
+ $tableName = empty($tableName) ? 'civicrm_participant' : $tableName;
if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$value = $value[$op];
@@ -424,7 +427,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;
@@ -443,13 +446,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';
@@ -459,9 +460,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;
}
}
@@ -490,8 +498,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':
@@ -512,15 +520,6 @@ public static function from($name, $mode, $side) {
return $from;
}
- /**
- * Getter for the qill object.
- *
- * @return string
- */
- public function qill() {
- return (isset($this->_qill)) ? $this->_qill : "";
- }
-
/**
* @param $mode
* @param bool $includeCustomFields
@@ -533,7 +532,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,
@@ -559,7 +558,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
@@ -586,27 +585,25 @@ 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);
@@ -615,62 +612,44 @@ public static function buildSearchForm(&$form) {
$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->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', [1 => '%1']));
$form->addSelect('participant_status_id',
- array(
+ [
'entity' => 'participant',
'label' => ts('Participant Status'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
- )
+ ]
);
$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');
- // add all the custom searchable fields
- $extends = array('Participant', 'Event');
- $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
- if ($groupDetails) {
- $form->assign('participantGroupTree', $groupDetails);
- foreach ($groupDetails as $group) {
- foreach ($group['fields'] as $field) {
- $fieldId = $field['id'];
- $elementName = 'custom_' . $fieldId;
- CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
- }
- }
- }
+
+ self::addCustomFormFields($form, ['Participant', 'Event']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'participant_campaign_id');
$form->assign('validCiviEvent', TRUE);
- $form->setDefaults(array('participant_test' => 0));
- }
-
- /**
- * @param $row
- * @param int $id
- */
- public static function searchAction(&$row, $id) {
+ $form->setDefaults(['participant_test' => 0]);
}
/**
@@ -679,7 +658,7 @@ public static function searchAction(&$row, $id) {
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);
}
}
@@ -695,7 +674,7 @@ 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']))) {
return TRUE;
diff --git a/CRM/Event/Badge.php b/CRM/Event/Badge.php
index e0b9b3542a0a..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 98c1398a0d86..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 e3cd206c6521..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 3ddf6a4c847f..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 edde650d985e..e953400f05e8 100644
--- a/CRM/Event/Cart/DAO/Cart.php
+++ b/CRM/Event/Cart/DAO/Cart.php
@@ -1,153 +1,152 @@
__table = 'civicrm_event_carts';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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(), '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,
- ) ,
- 'user_id' => array(
+ 'title' => ts('Cart ID'),
+ 'description' => ts('Cart Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_event_carts',
+ 'entity' => 'Cart',
+ 'bao' => 'CRM_Event_Cart_BAO_Cart',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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?'),
+ '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
*
@@ -155,10 +154,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
*
@@ -166,8 +166,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 = [];
+ 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 dbfaeb3c57f3..f0c31b4d3189 100644
--- a/CRM/Event/Cart/DAO/EventInCart.php
+++ b/CRM/Event/Cart/DAO/EventInCart.php
@@ -1,157 +1,156 @@
__table = 'civicrm_events_in_carts';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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'][] = 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,
- ) ,
- 'event_id' => array(
+ 'title' => ts('Event In Cart'),
+ 'description' => ts('Event In Cart Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_events_in_carts',
+ 'entity' => 'EventInCart',
+ 'bao' => 'CRM_Event_Cart_BAO_EventInCart',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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'),
+ '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
*
@@ -159,10 +158,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
*
@@ -170,8 +170,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 = [];
+ 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 f7a874203005..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,15 +128,7 @@ public function getContactID() {
* @return mixed|null
*/
public static function find_contact($fields) {
- $dedupe_params = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
- $dedupe_params['check_permission'] = FALSE;
- $ids = CRM_Dedupe_Finder::dupesByParams($dedupe_params, 'Individual');
- if (is_array($ids)) {
- return array_pop($ids);
- }
- else {
- return NULL;
- }
+ return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
}
/**
@@ -145,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() ||
@@ -269,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'),
@@ -292,21 +291,21 @@ public function buildQuickForm() {
$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);")
+ ] + $price,
+ NULL, ['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'));
+ $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);
@@ -315,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++) {
@@ -343,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.
@@ -358,32 +356,28 @@ 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')) {
+ $deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
+ $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
+ }
$this->buildAmountLabel();
parent::buildQuickForm();
}
@@ -392,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']);
}
/**
@@ -405,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;
@@ -442,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]);
}
}
}
@@ -490,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;
@@ -520,26 +514,24 @@ public static function formRule($values) {
$errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.');
}
}
- }
- // CRM-16189
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($values['financial_type_id']);
- }
- catch (CRM_Core_Exception $e) {
- $errors['financial_type_id'] = $e->getMessage();
+ 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
@@ -554,7 +546,7 @@ public function buildAmountLabel() {
*/
public function postProcess() {
$eventTitle = '';
- $params = $this->exportValues();
+ $params = $this->cleanMoneyFields($this->exportValues());
$this->set('discountSection', 0);
@@ -565,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';
@@ -604,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)) {
@@ -673,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
@@ -684,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));
@@ -727,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'];
}
@@ -764,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);
}
}
@@ -818,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 ce64515b52cc..b33eafe0a420 100644
--- a/CRM/Event/Form/ManageEvent/Location.php
+++ b/CRM/Event/Form/ManageEvent/Location.php
@@ -1,9 +1,9 @@
assign('selectedChild', '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']);
}
/**
@@ -138,7 +140,7 @@ public function addRules() {
*/
public static function formRule($fields) {
// check for state/country mapping
- $errors = CRM_Contact_Form_Edit_Address::formRule($fields, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullObject);
+ $errors = CRM_Contact_Form_Edit_Address::formRule($fields);
return empty($errors) ? TRUE : $errors;
}
@@ -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);
+ $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,6 +255,9 @@ 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'];
+ }
}
}
diff --git a/CRM/Event/Form/ManageEvent/Registration.php b/CRM/Event/Form/ManageEvent/Registration.php
index b114488f3b90..0c62605713f5 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->assign('selectedChild', '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']
@@ -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');
+ $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'));
- $form->add('wysiwyg', 'confirm_footer_text', ts('Footer Text'), $attributes['confirm_text'] + array('class' => 'collapsed'));
+ $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'));
- $form->add('wysiwyg', 'thankyou_footer_text', ts('Footer Text'), $attributes['thankyou_text'] + array('class' => 'collapsed'));
+ $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..f02716591d66 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->assign('selectedChild', '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,15 +193,15 @@ 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);
diff --git a/CRM/Event/Form/ManageEvent/ScheduleReminders.php b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
index 5f74c2cdce92..483f275de624 100644
--- a/CRM/Event/Form/ManageEvent/ScheduleReminders.php
+++ b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
@@ -1,9 +1,9 @@
assign('selectedChild', '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 07ccfc82f91b..c966147e4fc7 100644
--- a/CRM/Event/Form/ManageEvent/TabHeader.php
+++ b/CRM/Event/Form/ManageEvent/TabHeader.php
@@ -1,9 +1,9 @@
assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'Alphanumeric', $form));
+
$tabs = $form->get('tabHeader');
if (!$tabs || empty($_GET['reset'])) {
$tabs = self::process($form);
@@ -52,11 +55,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 +75,26 @@ 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;
+ $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;
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['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 06b04f8d6511..0b0b31e0dcf2 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;
@@ -108,52 +112,61 @@ class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment
/**
* 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';
@@ -162,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;
@@ -198,26 +216,33 @@ 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();
$this->_showFeeBlock = CRM_Utils_Array::value('eventId', $_GET);
$this->assign('showFeeBlock', FALSE);
$this->assign('feeBlockPaid', FALSE);
- $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
- $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ // @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) {
- $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
- $this->assign('displayName', $displayName);
- $this->setPageTitle(ts('Event Registration for %1', array(1 => $displayName)));
+ if ($this->_contactID) {
+ $this->setPageTitle(ts('Event Registration for %1', [1 => $this->userDisplayName]));
}
else {
$this->setPageTitle(ts('Event Registration'));
@@ -244,6 +269,8 @@ public function preProcess() {
);
$this->assign('hasPayment', $this->_paymentId);
+ $this->assign('componentId', $this->_id);
+ $this->assign('component', 'event');
// CRM-12615 - Get payment information from the primary registration
if ((!$this->_paymentId) && ($this->_action == CRM_Core_Action::UPDATE)) {
@@ -258,18 +285,10 @@ public function preProcess() {
}
}
}
-
- // get the option value for custom data type
- $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
- $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
- $this->_eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
- $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);
- $this->assignPaymentRelatedVariables();
}
if ($this->_showFeeBlock) {
@@ -287,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);
}
@@ -368,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
@@ -380,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,
@@ -415,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;
@@ -462,19 +482,10 @@ 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($this->_participantStatuses);
- $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value(ts('Registered'), $statuses);
+ $statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
+ $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value('Registered', $statuses);
if (!empty($defaults[$this->_id]['event_id'])) {
$contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$defaults[$this->_id]['event_id'],
@@ -508,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;
@@ -527,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'])) {
@@ -581,6 +590,8 @@ 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();
@@ -605,51 +616,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);
@@ -675,26 +685,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()
@@ -702,18 +711,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)));
@@ -729,42 +738,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) {
@@ -775,11 +784,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);
}
/**
@@ -804,7 +812,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
@@ -818,6 +826,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.');
}
+ if (!empty($values['priceSetId'])) {
+ CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
+ }
}
// validate contribution status for 'Failed'.
@@ -841,14 +852,22 @@ public static function formRule($values, $files, $self) {
}
}
// For single additions - show validation error if the contact has already been registered
- // for this event with the same role.
+ // for this event.
if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
- $contactId = $self->_contactId;
+ if ($self->_context == 'standalone') {
+ $contactId = CRM_Utils_Array::value('contact_id', $values);
+ }
+ else {
+ $contactId = $self->_contactId;
+ }
+
$eventId = CRM_Utils_Array::value('event_id', $values);
if (!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.");
@@ -894,7 +913,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;
@@ -908,7 +927,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);
}
@@ -923,10 +942,48 @@ 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'])) {
- $this->_contactId = $params['contact_id'];
+ $this->_contactID = $this->_contactId = $params['contact_id'];
}
if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
$this->_quickConfig = $isQuickConfig;
@@ -937,14 +994,17 @@ public function postProcess() {
}
$config = CRM_Core_Config::singleton();
+ if (isset($params['total_amount'])) {
+ $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
+ }
if ($this->_isPaidEvent) {
- $contributionParams = array();
- $lineItem = array();
- $additionalParticipantDetails = array();
+ $contributionParams = ['skipCleanMoney' => TRUE];
+ $lineItem = [];
+ $additionalParticipantDetails = [];
if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
$eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
- if ($eventStartDate) {
+ if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
$contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
}
}
@@ -972,16 +1032,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]
);
@@ -1016,7 +1076,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) {
@@ -1036,13 +1096,12 @@ public function postProcess() {
}
$this->_params = $params;
+ parent::beginPostProcess();
$amountOwed = NULL;
if (isset($params['amount'])) {
$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
@@ -1064,6 +1123,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 '));
@@ -1078,10 +1139,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'];
@@ -1091,8 +1152,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;
@@ -1116,7 +1176,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;
@@ -1129,7 +1189,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);
@@ -1151,10 +1211,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.
@@ -1167,9 +1225,6 @@ public function postProcess() {
$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['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
- $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
- $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
$this->_params['amount'] = $params['fee_amount'];
$this->_params['amount_level'] = $params['amount_level'];
$this->_params['currencyID'] = $config->defaultCurrency;
@@ -1188,7 +1243,7 @@ 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'];
@@ -1219,9 +1274,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']
@@ -1229,10 +1282,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']
@@ -1251,17 +1309,16 @@ public function postProcess() {
'Participant'
);
//add participant payment
- $paymentParticipant = array(
+ $paymentParticipant = [
'participant_id' => $participants[0]->id,
'contribution_id' => $contribution->id,
- );
- $ids = array();
+ ];
- CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
+ CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
$this->_contactIds[] = $this->_contactId;
}
else {
- $participants = array();
+ $participants = [];
if ($this->_single) {
if ($params['role_id']) {
$params['role_id'] = $roleIdWithSeparator;
@@ -1296,7 +1353,7 @@ public function postProcess() {
$this->_contactIds[] = $this->_contactId;
}
- $contributions = array();
+ $contributions = [];
if (!empty($params['record_contribution'])) {
if (!empty($params['id'])) {
if ($this->_onlinePendingContributionId) {
@@ -1315,10 +1372,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'];
@@ -1328,20 +1385,22 @@ public function postProcess() {
$contributionParams['currency'] = $config->defaultCurrency;
$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;
+ $contributionParams['receive_date'] = CRM_Utils_Array::value('receive_date', $params, 'null');
- $recordContribution = array(
- 'contact_id',
+ $recordContribution = [
'financial_type_id',
'payment_instrument_id',
'trxn_id',
'contribution_status_id',
- 'receive_date',
'check_number',
'campaign_id',
- );
+ 'pan_truncation',
+ 'card_type_id',
+ ];
foreach ($recordContribution as $f) {
- $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
+ $contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
if ($f == 'trxn_id') {
$this->assign('trxn_id', $contributionParams[$f]);
}
@@ -1358,10 +1417,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;
}
@@ -1383,7 +1442,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'];
}
}
@@ -1393,12 +1452,12 @@ 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);
@@ -1451,7 +1510,7 @@ public function postProcess() {
$lineItem[$this->_priceSetId][$lineKey] = $line;
}
CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
- CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
+ CRM_Contribute_BAO_Contribution::addPayments($contributions);
}
}
}
@@ -1469,8 +1528,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'];
@@ -1478,8 +1537,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);
@@ -1490,7 +1549,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];
}
@@ -1510,10 +1569,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);
}
@@ -1534,42 +1593,18 @@ 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);
$this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
}
if ($this->_mode) {
- if (!empty($params['billing_first_name'])) {
- $name = $params['billing_first_name'];
- }
-
- if (!empty($params['billing_middle_name'])) {
- $name .= " {$params['billing_middle_name']}";
- }
-
- if (!empty($params['billing_last_name'])) {
- $name .= " {$params['billing_last_name']}";
- }
- $this->assign('billingName', $name);
-
- // assign the address formatted up for display
- $addressParts = array(
- "street_address-{$this->_bltID}",
- "city-{$this->_bltID}",
- "postal_code-{$this->_bltID}",
- "state_province-{$this->_bltID}",
- "country-{$this->_bltID}",
- );
- $addressFields = array();
- foreach ($addressParts as $part) {
- list($n, $id) = explode('-', $part);
- if (isset($this->_params['billing_' . $part])) {
- $addressFields[$n] = $this->_params['billing_' . $part];
- }
- }
- $this->assign('address', CRM_Utils_Address::format($addressFields));
+ $this->assignBillingName($params);
+ $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
+ $this->_params,
+ $this->_bltID
+ ));
$date = CRM_Utils_Date::format($params['credit_card_exp_date']);
$date = CRM_Utils_Date::mysqlToIso($date);
@@ -1586,24 +1621,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);
+ }
}
}
@@ -1626,15 +1663,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'];
@@ -1652,30 +1689,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
@@ -1695,7 +1732,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;
}
@@ -1721,10 +1758,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) {
@@ -1733,46 +1798,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 d1a0a84e7e45..50511fba177e 100644
--- a/CRM/Event/Form/ParticipantFeeSelection.php
+++ b/CRM/Event/Form/ParticipantFeeSelection.php
@@ -1,9 +1,9 @@
_contributionId);
if (count($ids) > 1) {
- $total = 0;
- foreach ($ids as $val) {
- $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
- }
+ $total = CRM_Price_BAO_LineItem::getLineTotal($this->_contributionId);
$this->assign('totalLineTotal', $total);
-
- $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($this->_participantId, 'civicrm_participant');
- $this->assign('lineItemTotal', $lineItemTotal);
+ $this->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);
}
}
+ /**
+ * Set default values for the form.
+ *
+ * @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);
@@ -163,12 +163,12 @@ public function buildQuickForm() {
$this->assign('currencySymbol', $config->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 +181,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 +200,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 +230,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
return $errors;
}
@@ -239,11 +239,11 @@ 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);
+ $fetchParticipantVals = ['id' => $this->_participantId];
CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails, CRM_Core_DAO::$_nullArray);
$participantParams = array_merge($params, $participantDetails[$this->_participantId]);
$mailSent = $this->emailReceipt($participantParams);
@@ -252,13 +252,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');
@@ -278,8 +278,8 @@ public function postProcess() {
* @return mixed
*/
public function emailReceipt(&$params) {
- $updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', NULL, FALSE);
- $lineItem = array();
+ $updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', FALSE, FALSE);
+ $lineItem = [];
if ($updatedLineItem) {
$lineItem[] = $updatedLineItem;
}
@@ -292,8 +292,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 +304,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 +324,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 +366,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 ee52b4b3c747..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,
@@ -74,6 +74,8 @@ public function preProcess() {
$participantID, 'id', 'participant_id'
);
$this->assign('hasPayment', $paymentId);
+ $this->assign('componentId', $participantID);
+ $this->assign('component', 'event');
if ($parentParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
$participantID, 'registered_by_id'
@@ -98,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
@@ -131,23 +150,24 @@ public function preProcess() {
}
// get the option value for custom data type
- $roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
- $eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
- $eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
+ $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
+ $roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
+ $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;
}
@@ -172,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"
@@ -187,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;
@@ -211,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];
}
@@ -234,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 933cd4999985..2e60b956e41a 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);
@@ -369,9 +393,7 @@ 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']);
@@ -467,23 +489,7 @@ public function assignToTemplate() {
}
}
- // assign the address formatted up for display
- $addressParts = array(
- "street_address-{$this->_bltID}",
- "city-{$this->_bltID}",
- "postal_code-{$this->_bltID}",
- "state_province-{$this->_bltID}",
- "country-{$this->_bltID}",
- );
- $addressFields = array();
- foreach ($addressParts as $part) {
- list($n, $id) = explode('-', $part);
- if (isset($params['billing_' . $part])) {
- $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $params);
- }
- }
-
- $this->assign('address', CRM_Utils_Address::format($addressFields));
+ $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
// The concept of contributeMode is deprecated.
if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
@@ -755,8 +761,7 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
'participant_id' => $participant->id,
'contribution_id' => $contribution->id,
);
- $ids = array();
- $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
+ $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams);
}
//set only primary participant's params for transfer checkout.
@@ -785,12 +790,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';
}
@@ -1253,10 +1257,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;
@@ -1483,7 +1487,7 @@ public function checkValidEvent($redirect = NULL) {
$startDate &&
$startDate >= $now
) {
- CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect);
+ CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect, ts('Sorry'));
}
$regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
@@ -1495,7 +1499,7 @@ public function checkValidEvent($redirect = NULL) {
if (empty($regEndDate)) {
$endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
}
- CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect);
+ CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect, ts('Sorry'));
}
}
diff --git a/CRM/Event/Form/Registration/AdditionalParticipant.php b/CRM/Event/Form/Registration/AdditionalParticipant.php
index 771f2ad1aa36..afaaf1a4d4ff 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') {
@@ -180,19 +181,19 @@ public function buildQuickForm() {
CRM_Event_Form_Registration_Register::buildAmount($this);
}
$first_name = $last_name = NULL;
- $pre = $post = array();
- foreach (array(
- 'pre',
- 'post',
- ) as $keys) {
+ $pre = $post = [];
+ foreach ([
+ 'pre',
+ 'post',
+ ] as $keys) {
if (isset($this->_values['additional_custom_' . $keys . '_id'])) {
- $this->buildCustom($this->_values['additional_custom_' . $keys . '_id'], 'additionalCustom' . ucfirst($keys), TRUE);
+ $this->buildCustom($this->_values['additional_custom_' . $keys . '_id'], 'additionalCustom' . ucfirst($keys));
$$keys = CRM_Core_BAO_UFGroup::getFields($this->_values['additional_custom_' . $keys . '_id']);
}
- foreach (array(
- 'first_name',
- 'last_name',
- ) as $name) {
+ foreach ([
+ 'first_name',
+ 'last_name',
+ ] as $name) {
if (array_key_exists($name, $$keys) &&
CRM_Utils_Array::value('is_required', CRM_Utils_Array::value($name, $$keys))
) {
@@ -209,7 +210,7 @@ public function buildQuickForm() {
//add buttons
$js = NULL;
if ($this->isLastParticipant(TRUE) && empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $js = ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"];
}
//handle case where user might sart with waiting by group
@@ -262,23 +263,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 +345,38 @@ 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,
+ 'js' => $js,
+ ],
+ ]);
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 +394,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 +429,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 +473,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 +491,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,7 +549,7 @@ 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;
@@ -568,7 +567,7 @@ public function validatePaymentValues($self, $fields) {
return TRUE;
}
- $errors = array();
+ $errors = [];
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
@@ -583,7 +582,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;
}
@@ -610,9 +609,12 @@ public function postProcess() {
if (!$this->_allowConfirmation) {
// check if the participant is already registered
- $params['contact_id'] = CRM_Event_Form_Registration_Register::checkRegistration($params, $this, TRUE, TRUE);
+ $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 +687,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 +732,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 +754,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 28cfda5d4581..7ba4fdb95a08 100644
--- a/CRM/Event/Form/Registration/Confirm.php
+++ b/CRM/Event/Form/Registration/Confirm.php
@@ -1,9 +1,9 @@
_contributeMode == 'express') {
- $params = array();
+ $params = [];
// 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',
@@ -105,14 +115,14 @@ public function preProcess() {
// also merge all the other values from the profile fields
$values = $this->controller->exportValues('Register');
- $skipFields = array(
+ $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
@@ -199,9 +209,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 +223,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])
) {
@@ -274,7 +286,7 @@ public function buildQuickForm() {
}
if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
- $lineItemForTemplate = array();
+ $lineItemForTemplate = [];
$getTaxDetails = FALSE;
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
@@ -303,22 +315,21 @@ 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,
+ 'js' => ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"],
+ ],
+ ]);
+
+ $defaults = [];
+ $fields = [];
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
@@ -354,7 +365,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 +378,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 +409,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,7 +442,8 @@ public function postProcess() {
if ($this->_values['event']['is_monetary']) {
$this->set('finalAmount', $this->_amount);
}
- $participantCount = array();
+ $participantCount = [];
+ $taxAmount = $totalTaxAmount = 0;
//unset the skip participant from params.
//build the $participantCount array.
@@ -442,7 +456,10 @@ public function postProcess() {
elseif ($participantNum) {
$participantCount[$participantNum] = 'participant';
}
-
+ $totalTaxAmount += CRM_Utils_Array::value('tax_amount', $record, 0);
+ if (CRM_Utils_Array::value('is_primary', $record)) {
+ $taxAmount = &$params[$participantNum]['tax_amount'];
+ }
//lets get additional participant id to cancel.
if ($this->_allowConfirmation && is_array($cancelledIds)) {
$additonalId = CRM_Utils_Array::value('participant_id', $record);
@@ -451,12 +468,12 @@ public function postProcess() {
}
}
}
-
+ $taxAmount = $totalTaxAmount;
$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();
+ $this->participantIDS = [];
+ $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
@@ -469,7 +486,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',
@@ -482,7 +499,7 @@ public function postProcess() {
"billing_country-{$this->_bltID}",
"billing_country_id-{$this->_bltID}",
"address_name-{$this->_bltID}",
- );
+ ];
foreach ($billingFields as $field) {
unset($value[$field]);
}
@@ -510,8 +527,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'];
@@ -530,13 +546,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'];
}
@@ -569,14 +584,10 @@ public function postProcess() {
}
if (is_object($payment)) {
- try {
- $result = $payment->doPayment($value);
- $value = array_merge($value, $result);
- }
- catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
- CRM_Core_Session::singleton()->setStatus($e->getMessage());
- CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
- }
+ // Not quite sure why we don't just user $value since it contains the data
+ // from result
+ // @todo ditch $result & retest.
+ list($result, $value) = $this->processPayment($payment, $value);
}
else {
CRM_Core_Error::fatal($paymentObjError);
@@ -608,7 +619,7 @@ public function postProcess() {
}
//passing contribution id is already registered.
- $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
+ $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount, $this->_paymentProcessor);
$value['contributionID'] = $contribution->id;
$value['contributionTypeID'] = $contribution->financial_type_id;
$value['receive_date'] = $contribution->receive_date;
@@ -639,9 +650,9 @@ public function postProcess() {
!$this->_allowWaitlist && !$this->_requireApproval
) {
// transactionID & receive date required while building email template
- $this->assign('trxn_id', $value['trxn_id']);
- $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
- $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
+ $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $value));
+ $this->assign('receive_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $value)));
+ $this->set('receiveDate', CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $value)));
$this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
}
}
@@ -685,14 +696,14 @@ 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;
@@ -786,13 +797,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 +811,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,13 +825,13 @@ 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
- $payment->doPayment($primaryParticipant, 'event');
+
+ $this->processPayment($payment, $primaryParticipant);
}
else {
CRM_Core_Error::fatal($paymentObjError);
@@ -836,14 +847,14 @@ public function postProcess() {
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) {
@@ -882,8 +893,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];
@@ -891,7 +902,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'];
@@ -899,7 +910,7 @@ public function postProcess() {
}
if ($this->_lineItem) {
$lineItems = $this->_lineItem;
- $lineItem = array();
+ $lineItem = [];
if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
$lineItem[] = $lineItemValue;
}
@@ -909,7 +920,7 @@ public function postProcess() {
$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);
}
@@ -938,12 +949,15 @@ public function postProcess() {
* @param int $contactID
* @param bool $pending
* @param bool $isAdditionalAmount
+ * @param array $paymentProcessor
*
* @return \CRM_Contribute_BAO_Contribution
+ * @throws \CRM_Core_Exception
*/
public static function processContribution(
&$form, $params, $result, $contactID,
- $pending = FALSE, $isAdditionalAmount = FALSE
+ $pending = FALSE, $isAdditionalAmount = FALSE,
+ $paymentProcessor = NULL
) {
$transaction = new CRM_Core_Transaction();
@@ -958,7 +972,10 @@ public static function processContribution(
$params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR;
}
- $contribParams = array(
+ // CRM-20264: fetch CC type ID and number (last 4 digit) and assign it back to $params
+ CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
+
+ $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,
@@ -970,19 +987,22 @@ public static function processContribution(
'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
'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 (empty($params['is_pay_later'])) {
- $contribParams['payment_instrument_id'] = 1;
+ if ($paymentProcessor) {
+ $contribParams['payment_instrument_id'] = $paymentProcessor['payment_instrument_id'];
+ $contribParams['payment_processor'] = $paymentProcessor['id'];
}
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');
@@ -996,21 +1016,14 @@ 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')) {
$eventStartDate = CRM_Utils_Array::value(
'start_date',
@@ -1019,7 +1032,7 @@ public static function processContribution(
$form->_values
)
);
- if ($eventStartDate) {
+ if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
$contribParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
}
}
@@ -1030,10 +1043,10 @@ public static function processContribution(
$contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
}
- $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params);
$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));
@@ -1071,7 +1084,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)) {
@@ -1117,7 +1130,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) {
@@ -1189,7 +1202,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
}
//get email primary first if exist
- $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
+ $subscribtionEmail = ['email' => CRM_Utils_Array::value('email-Primary', $params)];
if (!$subscribtionEmail['email']) {
$subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
}
@@ -1208,7 +1221,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
*/
public static function assignProfiles(&$form) {
$participantParams = $form->_params;
- $formattedValues = $profileFields = array();
+ $formattedValues = $profileFields = [];
$count = 1;
foreach ($participantParams as $participantNum => $participantValue) {
if ($participantNum) {
@@ -1222,7 +1235,7 @@ public static function assignProfiles(&$form) {
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,
@@ -1237,9 +1250,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,
@@ -1277,4 +1290,68 @@ public static function assignProfiles(&$form) {
}
}
+ /**
+ * Submit in test mode.
+ *
+ * @param $params
+ */
+ public static function testSubmit($params) {
+ $form = new CRM_Event_Form_Registration_Confirm();
+ // This way the mocked up controller ignores the session stuff.
+ $_SERVER['REQUEST_METHOD'] = 'GET';
+ $_REQUEST['id'] = $form->_eventId = $params['id'];
+ $form->controller = new CRM_Event_Controller_Registration();
+ $form->_params = $params['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'] = [];
+ $form->_values['custom_post_id'] = [];
+ $form->_values['event'] = CRM_Utils_Array::value('event', $params);
+ $form->_contributeMode = $params['contributeMode'];
+ $eventParams = ['id' => $params['id']];
+ CRM_Event_BAO_Event::retrieve($eventParams, $form->_values['event']);
+ $form->set('registerByID', $params['registerByID']);
+ if (!empty($params['paymentProcessorObj'])) {
+ $form->_paymentProcessor = $params['paymentProcessorObj'];
+ }
+ $form->postProcess();
+ }
+
+ /**
+ * Process the payment, redirecting back to the page on error.
+ *
+ * @param $payment
+ * @param $value
+ *
+ * @return array
+ */
+ private function processPayment($payment, $value) {
+ try {
+ $result = $payment->doPayment($value, 'event');
+ 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 [];
+ }
+
+ /**
+ * 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 2daf0d8cd20e..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 9ec3fb30fc67..fd5a218f3e8e 100644
--- a/CRM/Event/Form/Registration/Register.php
+++ b/CRM/Event/Form/Registration/Register.php
@@ -1,9 +1,9 @@
getContactID();
+ }
+ if (!$contactID && is_array($fields) && $fields) {
+ $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.
@@ -95,7 +123,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;
@@ -125,7 +153,7 @@ public function preProcess() {
* Set default values for the form.
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
if (!$this->_allowConfirmation && $this->_requireApproval) {
$this->_defaults['bypass_payment'] = 1;
}
@@ -202,7 +230,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'])) {
@@ -280,7 +308,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;
@@ -289,7 +317,7 @@ public function buildQuickForm() {
ts('How many people are you registering?'),
$additionalOptions,
NULL,
- array('onChange' => "allowParticipant()")
+ ['onChange' => "allowParticipant()"]
);
$isAdditionalParticipants = TRUE;
}
@@ -310,7 +338,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'],
@@ -338,7 +366,7 @@ 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;
@@ -373,7 +401,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);
@@ -391,7 +419,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'];
@@ -436,7 +464,7 @@ public function buildQuickForm() {
$js = NULL;
if (empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $js = ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"];
}
// CRM-11182 - Optional confirmation screen
@@ -452,19 +480,18 @@ 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,
+ 'js' => $js,
+ ],
+ ]);
}
- $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
@@ -476,14 +503,14 @@ 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.
*/
- 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) {
@@ -514,7 +541,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.
@@ -545,6 +572,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' ||
@@ -562,40 +594,54 @@ 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))) {
$isRequire = FALSE;
}
-
- //build the element.
- CRM_Price_BAO_PriceField::addQuickFormElement($form,
- $elementName,
- $fieldId,
- FALSE,
- $isRequire,
- NULL,
- $options,
- $optionFullIds
- );
+ if (!empty($options)) {
+ //build the element.
+ CRM_Price_BAO_PriceField::addQuickFormElement($form,
+ $elementName,
+ $fieldId,
+ FALSE,
+ $isRequire,
+ NULL,
+ $options,
+ $optionFullIds
+ );
+ }
}
}
$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'];
@@ -621,12 +667,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'];
@@ -639,7 +685,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,
@@ -664,7 +710,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;
@@ -714,7 +760,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.
@@ -730,40 +776,40 @@ public static function formatFieldsForOptionFull(&$form) {
* The input form values.
* @param array $files
* The uploaded files if any.
- * @param $self
+ * @param CRM_Event_Form_Registration $form
*
*
* @return bool|array
* true if no errors, else array of errors
*/
- 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.");
}
@@ -777,16 +823,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'])) {
@@ -794,24 +840,31 @@ 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).', [
+ 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 && !isset
- ($fields['payment_processor_id'])) {
+ 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');
}
@@ -822,28 +875,28 @@ public static function formRule($fields, $files, $self) {
}
}
elseif (!empty($fields['amount']) &&
- (isset($self->_values['discount'][$fields['amount']])
- && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
+ (isset($form->_values['discount'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_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
+ (isset($form->_values['fee'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_values['fee'][$fields['amount']]) == 0
)
) {
$isZeroAmount = TRUE;
}
- if ($isZeroAmount && !($self->_forcePayement && !empty($fields['additional_participants']))) {
+ if ($isZeroAmount && !($form->_forcePayement && !empty($fields['additional_participants']))) {
$skipPaymentValidation = TRUE;
}
// 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;
}
@@ -851,16 +904,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))]
);
}
}
@@ -884,7 +937,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;
@@ -923,7 +976,7 @@ public function postProcess() {
if (!$this->_allowConfirmation) {
// check if the participant is already registered
if (!$this->_skipDupeRegistrationCheck) {
- $params['contact_id'] = self::checkRegistration($params, $this, FALSE, TRUE, TRUE);
+ $params['contact_id'] = self::getRegistrationContactID($params, $this, FALSE);
}
}
@@ -996,7 +1049,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']);
@@ -1006,10 +1059,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']);
@@ -1056,7 +1110,7 @@ public function postProcess() {
$this->_params[0] = $params;
}
else {
- $this->_params = array();
+ $this->_params = [];
$this->_params[] = $params;
}
$this->set('params', $this->_params);
@@ -1095,7 +1149,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');
@@ -1104,13 +1158,14 @@ 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);
}
@@ -1129,91 +1184,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.
- * @param bool $returnContactId
- * Just find and return the contactID match to use.
- * @param bool $useDedupeRules
- * Force usage of dedupe rules.
*
* @return int
*/
- public static function checkRegistration($fields, &$self, $isAdditional = FALSE, $returnContactId = FALSE, $useDedupeRules = FALSE) {
+ public static function checkRegistration($fields, $form, $isAdditional = FALSE) {
// CRM-3907, skip check for preview registrations
// CRM-4320 participant need to walk wizard
- if (!$returnContactId &&
- ($self->_mode == 'test' || $self->_allowConfirmation)
+ if (
+ ($form->_mode == 'test' || $form->_allowConfirmation)
) {
return FALSE;
}
- $contactID = NULL;
- $session = CRM_Core_Session::singleton();
- if (!$isAdditional) {
- $contactID = $self->getContactID();
- }
-
- if (!$contactID && is_array($fields) && $fields) {
-
- //CRM-14134 use Unsupervised rule for everyone
- $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
-
- // disable permission based on cache since event registration is public page/feature.
- $dedupeParams['check_permission'] = FALSE;
-
- // find event dedupe rule
- if (CRM_Utils_Array::value('dedupe_rule_group_id', $self->_values['event'], 0) > 0) {
- $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised', array(), $self->_values['event']['dedupe_rule_group_id']);
- }
- else {
- $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised');
- }
- $contactID = CRM_Utils_Array::value(0, $ids);
-
- }
-
- if ($returnContactId) {
- // CRM-7377
- // return contactID if contact already exists
- return $contactID;
- }
+ $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));
- $session->setStatus($status, ts('Oops.'), 'alert');
+ $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);
@@ -1221,7 +1243,7 @@ public static function checkRegistration($fields, &$self, $isAdditional = FALSE,
if ($isAdditional) {
$status = ts("It looks like this participant is 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.");
- $session->setStatus($status, ts('Oops.'), 'alert');
+ CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
return $participant->id;
}
}
diff --git a/CRM/Event/Form/Registration/ThankYou.php b/CRM/Event/Form/Registration/ThankYou.php
index e1f986353775..7c13ada6f6a8 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);
+ $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
$getTaxDetails = FALSE;
$taxAmount = 0;
- $lineItemForTemplate = array();
+ $lineItemForTemplate = [];
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
if (!empty($value) && $value != 'skip') {
@@ -129,7 +127,7 @@ public function buildQuickForm() {
if ($invoicing) {
$this->assign('getTaxDetails', $getTaxDetails);
$this->assign('totalTaxAmount', $taxAmount);
- $this->assign('taxTerm', $taxTerm);
+ $this->assign('taxTerm', CRM_Invoicing_Utils::getTaxTerm());
}
$this->assign('totalAmount', $this->_totalAmount);
@@ -148,8 +146,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 +177,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 bb5d79940d7e..27a01a0e58f0 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', CRM_Core_DAO::$_nullObject);
- $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 +105,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,
@@ -168,17 +143,13 @@ public function preProcess() {
*/
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 +165,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 +186,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 +202,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 +242,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 +300,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 +323,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,
@@ -378,6 +360,42 @@ public function postProcess() {
$controller->run();
}
+ /**
+ * 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
+ */
+ 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);
+ }
+
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
@@ -396,7 +414,7 @@ public function addRules() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults = $this->_formValues;
return $defaults;
}
@@ -405,17 +423,13 @@ public function fixFormValues() {
// if this search has been forced
// then see if there are any get values, and if so over-ride the post values
// note that this means that GET over-rides POST :)
- $event = CRM_Utils_Request::retrieve('event', 'Positive',
- CRM_Core_DAO::$_nullObject
- );
+ $event = CRM_Utils_Request::retrieve('event', 'Positive');
if ($event) {
$this->_formValues['event_id'] = $event;
$this->_formValues['event_name'] = CRM_Event_PseudoConstant::event($event, TRUE);
}
- $status = CRM_Utils_Request::retrieve('status', 'String',
- CRM_Core_DAO::$_nullObject
- );
+ $status = CRM_Utils_Request::retrieve('status', 'String');
if (isset($status)) {
if ($status === 'true') {
@@ -430,12 +444,10 @@ 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',
- CRM_Core_DAO::$_nullObject
- );
+ $role = CRM_Utils_Request::retrieve('role', 'String');
if (isset($role)) {
if ($role === 'true') {
@@ -450,9 +462,7 @@ public function fixFormValues() {
$this->_formValues['participant_role_id'] = is_array($roleTypes) ? array_keys($roleTypes) : $roleTypes;
}
- $type = CRM_Utils_Request::retrieve('type', 'Positive',
- CRM_Core_DAO::$_nullObject
- );
+ $type = CRM_Utils_Request::retrieve('type', 'Positive');
if ($type) {
$this->_formValues['event_type'] = $type;
}
diff --git a/CRM/Event/Form/SearchEvent.php b/CRM/Event/Form/SearchEvent.php
index 2a1232ce4a90..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 e5c6cf1bad5b..c3af950956bf 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-2016 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -29,7 +29,7 @@
/**
*
* @package CRM
- * @copyright CiviCRM LLC (c) 2004-2016
+ * @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'), 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([
+ [
'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'];
}
- $from_participant = $params = array();
+ 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 = [];
$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;
@@ -339,7 +373,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 +384,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 +395,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 +411,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 +433,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 +471,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 +488,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 +499,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 +530,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 +558,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 f41b458d9289..de7e8090fc23 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);
+ $isBackOfficeArg = $this->isBackoffice ? '&is_backoffice=1' : '';
+ CRM_Utils_System::redirect(CRM_Utils_System::url(
+ 'civicrm/event/selfsvctransfer',
+ [
+ 'reset' => 1,
+ 'action' => 'add',
+ 'pid' => $this->_participant_id,
+ 'cs' => $this->_userChecksum,
+ ]
+ ));
}
/**
@@ -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 5aa34ce0f027..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 cc678a9d8acc..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 b78c17e10b77..3f7d87586d5e 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 2a5965be2ccb..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',
@@ -158,9 +158,10 @@ public function buildQuickForm() {
//fix for CRM-2752
// get the option value for custom data type
- $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
- $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
- $this->_eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
+ $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);
// build custom data getFields array
$customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID);
@@ -181,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']
@@ -224,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)'));
@@ -241,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');
@@ -269,85 +270,17 @@ public function setDefaultValues() {
/**
* Process the form after the input has been submitted and validated.
- *
- *
- * @return void
*/
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_register_date'])) {
- $value['register_date'] = CRM_Utils_Date::processDate($value['participant_register_date'], $value['participant_register_date_time']);
- }
-
- if (!empty($value['participant_role'])) {
- $participantRoles = CRM_Event_PseudoConstant::participantRole();
- 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;
- }
- }
-
- if (!empty($value['participant_source'])) {
- $value['source'] = $value['participant_source'];
- }
- unset($value['participant_register_date']);
- unset($value['participant_status']);
- unset($value['participant_source']);
-
- CRM_Event_BAO_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) {
@@ -381,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);
@@ -417,7 +350,7 @@ public static function updateContributionStatus($params) {
return NULL;
}
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
//get the required ids.
$ids['contribution'] = $contributionId;
@@ -462,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);
@@ -485,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;
}
@@ -507,6 +440,8 @@ public static function updateContributionStatus($params) {
}
//complete the contribution.
+ // @todo use the api - ie civicrm_api3('Contribution', 'completetransaction', $input);
+ // as this method is not preferred / supported.
$baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
// reset template values before processing next transactions
@@ -519,14 +454,86 @@ 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());
- $statuses = implode(', ', $notifyingStatuses);
- $status = ts('Participants whose status is changed FROM Pending Pay Later TO Registered or Attended will receive a confirmation email and their payment status will be set to completed. If this is not you want to do, you can change their participant status by editing their event registration record directly.');
+ $this->assign('status', TRUE);
if (!empty($notifyingStatuses)) {
- $status .= '
' . ts("Participants whose status is changed TO any of the following will be automatically notified via email: %1", array(1 => $statuses));
+ $s = '' . implode(', ', $notifyingStatuses) . '';
+ $this->assign('notifyingStatuses', $s);
+ }
+ }
+
+ /**
+ * @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');
}
- $this->assign('status', $status);
}
}
diff --git a/CRM/Event/Form/Task/Cancel.php b/CRM/Event/Form/Task/Cancel.php
index 511303563105..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 80c964d8a064..ad9acdbddb70 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');
}
}
@@ -408,11 +405,9 @@ public function postProcess() {
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
+ $seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
- $config = CRM_Core_Config::singleton();
- $seperator = $config->fieldSeparator;
-
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
@@ -463,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 98cfa592d40d..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));
@@ -113,16 +113,14 @@ public function preProcess() {
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
+ $seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
- $config = CRM_Core_Config::singleton();
- $seperator = $config->fieldSeparator;
-
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
+ $mapperKeys = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -133,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]];
}
@@ -154,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 e2d6c1b760b5..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 4ac571b88fef..ba14c1bc2d7f 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 +196,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 +257,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 +312,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 +417,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 181472f38f69..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 a92c94933860..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 60718f37a543..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 b035f8a06aa1..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.'));
@@ -148,6 +152,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 +178,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 +192,7 @@ public function run() {
}
//retrieve custom field information
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_id, 0, $values['event']['event_type_id']);
+ $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,27 +223,27 @@ 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) {
$mapURL = CRM_Utils_System::url('civicrm/contact/map/event',
"eid={$this->_id}&reset=1&action=preview",
- TRUE, NULL, TRUE,
+ FALSE, NULL, TRUE,
TRUE
);
}
else {
$mapURL = CRM_Utils_System::url('civicrm/contact/map/event',
"eid={$this->_id}&reset=1",
- TRUE, NULL, TRUE,
+ FALSE, NULL, TRUE,
TRUE
);
}
@@ -242,9 +252,7 @@ public function run() {
$this->assign('mapURL', $mapURL);
}
- if (CRM_Core_Permission::check('view event participants') &&
- CRM_Core_Permission::check('view all contacts')
- ) {
+ if (CRM_Core_Permission::check('view event participants')) {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
$statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
$findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
@@ -256,7 +264,7 @@ public function run() {
if ($participantListingID) {
$participantListingURL = CRM_Utils_System::url('civicrm/event/participant',
"reset=1&id={$this->_id}",
- TRUE, NULL, TRUE, TRUE
+ FALSE, NULL, TRUE, TRUE
);
$this->assign('participantListingURL', $participantListingURL);
}
@@ -268,13 +276,14 @@ 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',
"id={$this->_id}&reset=1{$action_query}",
- TRUE, NULL, TRUE,
+ FALSE, NULL, TRUE,
TRUE
);
if (!$eventFullMessage || $hasWaitingList) {
@@ -289,7 +298,7 @@ public function run() {
$link = CRM_Event_Cart_BAO_EventInCart::get_registration_link($this->_id);
$registerText = $link['label'];
- $url = CRM_Utils_System::url($link['path'], $link['query'] . $action_query, TRUE, NULL, TRUE, TRUE);
+ $url = CRM_Utils_System::url($link['path'], $link['query'] . $action_query, FALSE, NULL, TRUE, TRUE);
}
//Fixed for CRM-4855
@@ -308,11 +317,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;
@@ -325,7 +334,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]);
}
}
}
@@ -335,8 +344,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 f49ad3296c0c..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,74 @@ 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)) {
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 +251,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,7 +307,7 @@ public function browse() {
$this->search();
- $params = array();
+ $params = [];
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean',
$this, FALSE
);
@@ -275,7 +316,7 @@ public function browse() {
$whereClause = $this->whereClause($params, FALSE, $this->_force);
$this->pagerAToZ($whereClause, $params);
- $params = array();
+ $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 +326,7 @@ public function browse() {
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
// get all custom groups sorted by weight
- $manageEvent = array();
+ $manageEvent = [];
$query = "
SELECT *
@@ -295,13 +336,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 +354,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 +378,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 +409,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,15 +433,15 @@ 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]);
}
}
$manageEvent['tab'] = self::tabs($enableCart);
$this->assign('rows', $manageEvent);
- $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
- $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0');
+ $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
+ $statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
$findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
$findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
$this->assign('findParticipants', $findParticipants);
@@ -397,6 +452,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 +493,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 +505,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 +517,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,18 +528,18 @@ 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 {
$curDate = date('YmdHis');
- $clauses[5] = "(end_date >= {$curDate} OR end_date IS NULL)";
+ $clauses[] = "(end_date >= {$curDate} OR end_date IS NULL)";
}
}
else {
@@ -499,7 +556,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 d798d6307c7d..e58790c2a115 100644
--- a/CRM/Event/Page/ParticipantListing.php
+++ b/CRM/Event/Page/ParticipantListing.php
@@ -1,9 +1,9 @@
assign('displayRecent', FALSE);
}
+ /**
+ * Run listing page.
+ *
+ * @throws \Exception
+ */
public function run() {
$this->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 c8e8c3f2741e..d21bcddaef25 100644
--- a/CRM/Event/Page/ParticipantListing/Name.php
+++ b/CRM/Event/Page/ParticipantListing/Name.php
@@ -1,9 +1,9 @@
_participantListingType == 'Name';
+ $this->_participantListingType = 'Name';
parent::preProcess();
}
diff --git a/CRM/Event/Page/ParticipantListing/NameAndEmail.php b/CRM/Event/Page/ParticipantListing/NameAndEmail.php
index f994a6bb8004..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 a660e5883450..c2bf4eb3e229 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,7 +98,7 @@ public function run() {
ORDER BY $orderBy
LIMIT $offset, $rowCount";
- $rows = array();
+ $rows = [];
$object = CRM_Core_DAO::executeQuery($query, $params);
$statusLookup = CRM_Event_PseudoConstant::participantStatus();
while ($object->fetch()) {
@@ -106,13 +106,13 @@ public function run() {
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 +127,7 @@ public function run() {
*/
public function pager($fromClause, $whereClause, $whereParams) {
- $params = array();
+ $params = [];
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
@@ -154,22 +154,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 838e1da2c728..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 6e6cd47ab5bf..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 4f0a1a172c4f..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'),
- );
+ ];
}
/**
@@ -199,7 +199,7 @@ public static function &participantStatusClass() {
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;
@@ -229,7 +229,7 @@ public static function &participantRole($id = NULL, $cond = NULL) {
*/
public static function &participantListing($id = NULL) {
if (!self::$participantListing) {
- self::$participantListing = array();
+ self::$participantListing = [];
self::$participantListing = CRM_Core_OptionGroup::values('participant_listing');
}
@@ -250,7 +250,7 @@ public static function &participantListing($id = NULL) {
*/
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 c92482bd24a6..fb79e008db8e 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,37 +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] = [
+ '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',
@@ -410,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];
}
@@ -444,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);
}
}
@@ -502,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 91ef1fa4b448..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 33072d0ee650..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 683bd46039e5..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(
- 'title' => ts('Participant status - change (emails sent)'),
+ ],
+ 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);
- 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'];
- }
+ parent::tasks();
}
- 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;
+ return self::$_tasks;
}
/**
@@ -189,28 +155,30 @@ public static function &optionalTaskTitle() {
* 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 4be77944cc83..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-2016 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -44,44 +44,48 @@ class CRM_Event_Tokens extends \Civi\Token\AbstractTokenSubscriber {
* Class constructor.
*/
public function __construct() {
- parent::__construct('event', array(
- 'event_type' => ts('Event Type'),
- 'title' => ts('Event Title'),
- 'event_id' => ts('Event ID'),
- 'start_date' => ts('Event Start Date'),
- 'end_date' => ts('Event End Date'),
- 'summary' => ts('Event Summary'),
- 'description' => ts('Event Description'),
- 'location' => ts('Event Location'),
- 'info_url' => ts('Event Info URL'),
- 'registration_url' => ts('Event Registration URL'),
- 'fee_amount' => ts('Event Fee'),
- 'contact_email' => ts('Event Contact (Email)'),
- 'contact_phone' => ts('Event Contact (Phone)'),
- 'balance' => ts('Event Balance'),
+ parent::__construct('event', array_merge(
+ [
+ 'event_type' => ts('Event Type'),
+ 'title' => ts('Event Title'),
+ 'event_id' => ts('Event ID'),
+ 'start_date' => ts('Event Start Date'),
+ 'end_date' => ts('Event End Date'),
+ 'summary' => ts('Event Summary'),
+ 'description' => ts('Event Description'),
+ 'location' => ts('Event Location'),
+ 'info_url' => ts('Event Info URL'),
+ 'registration_url' => ts('Event Registration URL'),
+ 'fee_amount' => ts('Event Fee'),
+ 'contact_email' => ts('Event Contact (Email)'),
+ 'contact_phone' => ts('Event Contact (Phone)'),
+ 'balance' => ts('Event Balance'),
+ ],
+ CRM_Utils_Token::getCustomFieldTokens('Event')
));
}
/**
- * Check something about being active.
- *
- * @param \Civi\Token\TokenProcessor $processor
- *
- * @return bool
+ * @inheritDoc
*/
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';
}
+ /**
+ * Alter action schedule query.
+ *
+ * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
+ */
public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e) {
if ($e->mapping->getEntity() !== 'civicrm_participant') {
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
@@ -95,23 +99,13 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
}
/**
- * Evaluate the content of a single token.
- *
- * @param \Civi\Token\TokenRow $row
- * The record for which we want token values.
- * @param string $entity
- * @param string $field
- * The name of the token field.
- * @param mixed $prefetch
- * Any data that was returned by the prefetch().
- *
- * @return mixed
+ * @inheritDoc
*/
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$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;
@@ -128,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') {
@@ -148,6 +142,9 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
elseif (isset($actionSearchResult->$field)) {
$row->tokens($entity, $field, $actionSearchResult->$field);
}
+ elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
+ $row->customToken($entity, $cfID, $actionSearchResult->entity_id);
+ }
else {
$row->tokens($entity, $field, '');
}
diff --git a/CRM/Event/xml/Menu/Event.xml b/CRM/Event/xml/Menu/Event.xml
index f9d1d464eff6..7cc9a3ba6894 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 (merging > 2 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);
@@ -420,7 +415,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 +480,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);
if (!empty($mappings)) {
- $this->add('select', 'mapping', ts('Use Saved Field Mapping'), array('' => '-select-') + $mappings);
+ $this->add('select', 'mapping', ts('Use Saved Field Mapping'), ['' => '-select-'] + $mappings);
}
}
@@ -498,22 +492,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 +521,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 d779309daf70..15b5a84c558f 100644
--- a/CRM/Extension/Browser.php
+++ b/CRM/Extension/Browser.php
@@ -1,9 +1,9 @@
cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE;
- $json = file_get_contents($filename);
+ $filename = $this->cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE . '.' . md5($this->getRepositoryUrl());
+ $json = NULL;
+ if (file_exists($filename)) {
+ $json = file_get_contents($filename);
+ }
if (empty($json)) {
$json = $this->grabRemoteJson();
}
@@ -246,7 +249,7 @@ private function grabRemoteJson() {
return array();
}
- $filename = $this->cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE;
+ $filename = $this->cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE . '.' . md5($this->getRepositoryUrl());
$url = $this->getRepositoryUrl() . $this->indexPath;
$status = CRM_Utils_HttpClient::singleton()->fetch($url, $filename);
diff --git a/CRM/Extension/ClassLoader.php b/CRM/Extension/ClassLoader.php
index 92061c4fe7a6..bba8731510ec 100644
--- a/CRM/Extension/ClassLoader.php
+++ b/CRM/Extension/ClassLoader.php
@@ -1,9 +1,9 @@
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;
diff --git a/CRM/Extension/Container/Basic.php b/CRM/Extension/Container/Basic.php
index bcb741d4b2a8..42277242767a 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 +146,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 +202,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,9 +210,9 @@ 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;
}
@@ -272,7 +272,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 065a6955da68..0258c3689690 100644
--- a/CRM/Extension/Container/Collection.php
+++ b/CRM/Extension/Container/Collection.php
@@ -1,9 +1,9 @@
containers as $container) {
$errors = array_merge($errors, $container->checkRequirements());
}
@@ -163,7 +163,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 9672db9ab97b..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 b5257a2e8e5b..64f83178a425 100644
--- a/CRM/Extension/Downloader.php
+++ b/CRM/Extension/Downloader.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 e2de1c72eafe..7770d5a8e143 100644
--- a/CRM/Extension/Manager.php
+++ b/CRM/Extension/Manager.php
@@ -1,9 +1,9 @@
_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 +153,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:
@@ -210,7 +212,8 @@ public function install($keys) {
// keys/statuses/types before doing anything
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:
@@ -222,6 +225,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 +237,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 +257,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:
@@ -292,17 +306,27 @@ public function disable($keys) {
// 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 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);
@@ -347,14 +371,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);
@@ -401,7 +427,7 @@ public function getStatus($key) {
*/
public function getStatuses() {
if (!is_array($this->statuses)) {
- $this->statuses = array();
+ $this->statuses = [];
foreach ($this->fullContainer->getKeys() as $key) {
$this->statuses[$key] = self::STATUS_UNINSTALLED;
@@ -433,7 +459,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();
}
@@ -449,9 +476,10 @@ public function refresh() {
* (0 => CRM_Extension_Info, 1 => 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);
@@ -471,7 +499,7 @@ 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 +571,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 +596,98 @@ 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.
+ * @return array
+ * List of extension keys, including dependencies, in order of installation.
+ */
+ public function findInstallRequirements($keys) {
+ $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 ($this->getStatus($key) === self::STATUS_INSTALLED) {
+ $sorter->add($key, []);
+ }
+ elseif ($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 9cd223d26d37..4fed2bc68eeb 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 f2f5e6eb520b..3302ec291824 100644
--- a/CRM/Extension/Manager/Report.php
+++ b/CRM/Extension/Manager/Report.php
@@ -1,9 +1,9 @@
groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
@@ -64,10 +67,10 @@ public function onPreInstall(CRM_Extension_Info $info) {
CRM_Core_Error::fatal("Component for which you're trying to install the extension (" . $info->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,
@@ -76,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 9c4e4c6df630..1f0b291bf80c 100644
--- a/CRM/Extension/Manager/Search.php
+++ b/CRM/Extension/Manager/Search.php
@@ -1,9 +1,9 @@
groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
@@ -55,10 +58,10 @@ public function onPreInstall(CRM_Extension_Info $info) {
}
$weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
- array('option_group_id' => $this->groupId)
+ ['option_group_id' => $this->groupId]
);
- $params = array(
+ $params = [
'option_group_id' => $this->groupId,
'weight' => $weight,
'description' => $info->label . ' (' . $info->key . ')',
@@ -66,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 729bb009ec10..b9cc7ed18210 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,19 @@ 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)) {
// Check canonical module list
- $moduleExtensions = array();
+ $moduleExtensions = [];
$sql = '
SELECT full_name, file
FROM civicrm_extension
@@ -297,25 +297,25 @@ public function getActiveModuleFiles($fresh = FALSE) {
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
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 +329,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 +340,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 +410,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 +458,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 98937ff27422..6aeaa30baed7 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 +109,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 +122,7 @@ public function __construct($parameters = array()) {
*/
public function getFullContainer() {
if ($this->fullContainer === NULL) {
- $containers = array();
+ $containers = [];
if ($this->getDefaultContainer()) {
$containers['default'] = $this->getDefaultContainer();
@@ -144,7 +146,7 @@ public function getFullContainer() {
if (is_dir($vendorPath)) {
$containers['cmsvendor'] = new CRM_Extension_Container_Basic(
$vendorPath,
- $this->parameters['userFrameworkBaseURL'] . DIRECTORY_SEPARATOR . 'vendor',
+ CRM_Utils_File::addTrailingSlash($this->parameters['userFrameworkBaseURL'], '/') . 'vendor',
$this->getCache(),
'cmsvendor'
);
@@ -204,12 +206,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 +225,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 +244,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 +256,13 @@ public function getDownloader() {
*/
public function getCache() {
if ($this->cache === NULL) {
- $cacheGroup = md5(serialize(array('ext', $this->parameters)));
+ $cacheGroup = md5(serialize(['ext', $this->parameters]));
// 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,4 +288,69 @@ 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'];
+ }
+
+ /**
+ * Take an extension's raw XML info and add information about the
+ * extension's status on the local system.
+ *
+ * The result format resembles the old CRM_Core_Extensions_Extension.
+ *
+ * @param CRM_Extension_Info $obj
+ *
+ * @return array
+ */
+ public static function createExtendedInfo(CRM_Extension_Info $obj) {
+ $mapper = CRM_Extension_System::singleton()->getMapper();
+ $manager = CRM_Extension_System::singleton()->getManager();
+
+ $extensionRow = (array) $obj;
+ try {
+ $extensionRow['path'] = $mapper->keyToBasePath($obj->key);
+ }
+ catch (CRM_Extension_Exception $e) {
+ $extensionRow['path'] = '';
+ }
+ $extensionRow['status'] = $manager->getStatus($obj->key);
+
+ switch ($extensionRow['status']) {
+ case CRM_Extension_Manager::STATUS_UNINSTALLED:
+ // ts('Uninstalled');
+ $extensionRow['statusLabel'] = '';
+ break;
+
+ case CRM_Extension_Manager::STATUS_DISABLED:
+ $extensionRow['statusLabel'] = ts('Disabled');
+ break;
+
+ case CRM_Extension_Manager::STATUS_INSTALLED:
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled');
+ break;
+
+ case CRM_Extension_Manager::STATUS_DISABLED_MISSING:
+ $extensionRow['statusLabel'] = ts('Disabled (Missing)');
+ break;
+
+ case CRM_Extension_Manager::STATUS_INSTALLED_MISSING:
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled (Missing)');
+ break;
+
+ default:
+ $extensionRow['statusLabel'] = '(' . $extensionRow['status'] . ')';
+ }
+ return $extensionRow;
+ }
+
}
diff --git a/CRM/Extension/Upgrades.php b/CRM/Extension/Upgrades.php
index 6bcf470bd9e8..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 8f08c3bc6130..1f465383698b 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']);
@@ -199,7 +210,7 @@ public static function createActivityExport($batchIds, $fileName) {
// create activity.
$subject .= ' ' . ts('Batch') . '[' . $values['title'] . ']';
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
- $activityParams = array(
+ $activityParams = [
'activity_type_id' => array_search('Export Accounting Batch', $activityTypes),
'subject' => $subject,
'status_id' => 2,
@@ -208,13 +219,13 @@ public static function createActivityExport($batchIds, $fileName) {
'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);
}
@@ -226,12 +237,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 +253,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 3030e40bea86..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 88e42f317658..8ff0ef4b9b0d 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,13 @@ 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 +300,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 af7d05e28231..02ff4d9de89d 100644
--- a/CRM/Financial/BAO/FinancialAccount.php
+++ b/CRM/Financial/BAO/FinancialAccount.php
@@ -1,9 +1,9 @@
id = $params['id'];
$financialAccount->find(TRUE);
}
$financialAccount->copyValues($params);
- //CRM-16189
- $accountType = CRM_Core_PseudoConstant::accountOptionValues(
- 'financial_account_type',
- NULL,
- " AND v.name IN ('Liability', 'Asset') "
- );
- if (empty($params['id']) && !CRM_Utils_Array::value($financialAccount->financial_account_type_id, $accountType)) {
- $financialAccount->opening_balance = $financialAccount->current_period_opening_balance = '0.00';
- }
$financialAccount->save();
+
+ // invoke post hook
+ $op = 'create';
+ if (!empty($params['id'])) {
+ $op = 'edit';
+ }
+ CRM_Utils_Hook::post($op, 'FinancialAccount', $financialAccount->id, $financialAccount);
+
return $financialAccount;
}
@@ -144,6 +146,7 @@ public static function del($financialAccountId) {
$dependency = array(
array('Core', 'FinancialTrxn', 'to_financial_account_id'),
array('Financial', 'FinancialTypeAccount', 'financial_account_id'),
+ array('Financial', 'FinancialItem', 'financial_account_id'),
);
foreach ($dependency as $name) {
require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
@@ -157,13 +160,14 @@ public static function del($financialAccountId) {
if ($check) {
CRM_Core_Session::setStatus(ts('This financial account cannot be deleted since it is being used as a header account. Please remove it from being a header account before trying to delete it again.'));
- return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialAccount', "reset=1&action=browse"));
+ return FALSE;
}
// delete from financial Type table
$financialAccount = new CRM_Financial_DAO_FinancialAccount();
$financialAccount->id = $financialAccountId;
$financialAccount->delete();
+ return TRUE;
}
/**
@@ -259,7 +263,9 @@ public static function getFinancialAccountForFinancialTypeByRelationship($financ
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];
}
@@ -417,137 +423,55 @@ public static function checkFinancialTypeHasDeferred($params, $contributionID =
}
if ($isError) {
- $error = ts('Revenue recognition date can only be specified if the financial type selected has a deferred revenue account configured. Please have an administrator set up the deferred revenue account at Administer > CiviContribute > Financial Accounts, then configure it for financial types at Administer > CiviContribution > Financial Types, Accounts');
+ $error = ts('Revenue Recognition Date cannot be processed unless there is a Deferred Revenue account setup for the Financial Type. Please remove Revenue Recognition Date, select a different Financial Type with a Deferred Revenue account setup for it, or setup a Deferred Revenue account for this Financial Type.');
throw new CRM_Core_Exception($error);
}
return $isError;
}
/**
- * Check if financial type has Deferred Revenue Account is relationship
- * with Financial Account.
- *
- * @param int $financialTypeId
- * Financial Type Id.
- *
- * @param int $entityID
- * Holds id for PriceSet/PriceField/PriceFieldValue.
- *
- * @param string $entity
- * Entity like PriceSet/PriceField/PriceFieldValue.
- *
- * @return bool
+ * Retrieve all Deferred Financial Accounts.
*
- */
- public static function validateFinancialType($financialTypeId, $entityID = NULL, $entity = NULL) {
- if (!CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
- return FALSE;
- }
- if ($entityID) {
- $query = ' SELECT ps.extends FROM civicrm_price_set ps';
- $params = array(
- 1 => array('ps', 'Text'),
- 2 => array($entityID, 'Integer'),
- );
- if ($entity == 'PriceField') {
- $params[1] = array('pf', 'Text');
- $query .= ' INNER JOIN civicrm_price_field pf ON pf.price_set_id = ps.id ';
- }
- $query .= ' WHERE %1.id = %2';
- $extends = CRM_Core_DAO::singleValueQuery($query, $params);
- $extends = explode('', $extends);
- if (!(in_array(CRM_Core_Component::getComponentID('CiviEvent'), $extends)
- || in_array(CRM_Core_Component::getComponentID('CiviMember'), $extends))
- ) {
- return FALSE;
- }
- }
- $deferredFinancialType = self::getDeferredFinancialType();
- if (!array_key_exists($financialTypeId, $deferredFinancialType)) {
- throw new CRM_Core_Exception(ts('Deferred revenue account is not configured for selected financial type. Please have an administrator set up the deferred revenue account at Administer > CiviContribute > Financial Accounts, then configure it for financial types at Administer > CiviContribution > Financial Types, Accounts'));
- }
- return FALSE;
- }
-
- /**
- * Validate if Deferred Account is set for Financial Type
- * when Deferred Revenue is enabled
*
- * @return string
+ * @return array of Deferred Financial Account
*
*/
- public static function validateTogglingDeferredRevenue() {
- $deferredFinancialType = self::getDeferredFinancialType();
- $message = ts('Before Deferred Revenue can be enabled, a Deferred Revenue Account relationship must be defined for all financial types currently used for Memberships and Events, including
-
-
-In other words, please create deferred revenue accounts at Administer > CiviContribute > Financial Accounts, then configure them for the following financial types at Administer > CiviContribute > Financial Types, accounts:');
- $tables = array(
- 'civicrm_membership_type',
- 'civicrm_event',
- 'civicrm_price_set',
- 'civicrm_price_field_value',
- );
- $params[2] = array('', 'Text');
- if (!empty($deferredFinancialType)) {
- $params[2] = array(' AND financial_type_id NOT IN (' . implode(',', array_keys($deferredFinancialType)) . ') ', 'Text');
- }
- $query_1 = 'SELECT %5.id FROM %4 WHERE %5.is_active = 1';
- $query_2 = $query_1 . ' %2';
- foreach ($tables as $table) {
- $params[4] = array($table, 'Text');
- $params[5] = array($table, 'Text');
- $dao = CRM_Core_DAO::executeQuery($query_1, $params);
- if ($dao->N) {
- if (in_array($table, array('civicrm_price_set', 'civicrm_price_field_value'))) {
- $query_2 .= " AND civicrm_price_set.name NOT IN ('default_contribution_amount', 'default_membership_type_amount') AND (civicrm_price_set.extends LIKE '%1%' OR civicrm_price_set.extends like '3')";
- if ($table == 'civicrm_price_field_value') {
- $string = $table . ' INNER JOIN civicrm_price_field ON civicrm_price_field.id = civicrm_price_field_value.price_field_id INNER JOIN civicrm_price_set ON civicrm_price_set.id = civicrm_price_field.price_set_id ';
- $params[4] = array($string, 'Text');
- $params[2][0] = str_replace('financial_type_id', "{$table}.financial_type_id", $params[2][0]);
- }
- }
- $dao = CRM_Core_DAO::executeQuery($query_2, $params);
- if ($dao->N) {
- $message .= '';
- $financialTypes = CRM_Contribute_PseudoConstant::financialType();
- $financialTypes = array_diff_key($financialTypes, $deferredFinancialType);
- foreach ($financialTypes as $financialType) {
- $message .= "
';
- return $message;
- }
+ public static function getAllDeferredFinancialAccount() {
+ $financialAccount = array();
+ $result = civicrm_api3('EntityFinancialAccount', 'get', array(
+ 'sequential' => 1,
+ 'return' => array("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'] . ')';
}
}
- return NULL;
+ return $financialAccount;
}
/**
- * Retrieve all Deferred Financial Accounts.
+ * Get Organization Name associated with Financial Account.
*
+ * @param bool $checkPermissions
*
- * @return array of Deferred Financial Account
+ * @return array
*
*/
- public static function getAllDeferredFinancialAccount() {
- $query = "SELECT cfa.id, cfa.name FROM civicrm_entity_financial_account ce
-INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
-WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_active = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
- $deferredAccountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
- $queryParams = array(1 => array($deferredAccountRel, 'Integer'));
- $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
- $financialAccount = array();
- while ($dao->fetch()) {
- $financialAccount[$dao->id] = $dao->name;
+ public static function getOrganizationNames($checkPermissions = TRUE) {
+ $result = civicrm_api3('FinancialAccount', 'get', array(
+ 'return' => array("contact_id.organization_name", "contact_id"),
+ 'contact_id.is_deleted' => 0,
+ 'options' => array('limit' => 0),
+ 'check_permissions' => $checkPermissions,
+ ));
+ $organizationNames = array();
+ foreach ($result['values'] as $values) {
+ $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
}
- return $financialAccount;
+ return $organizationNames;
}
}
diff --git a/CRM/Financial/BAO/FinancialItem.php b/CRM/Financial/BAO/FinancialItem.php
index 28e51b70d396..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,
'currency' => $contribution->currency,
'entity_table' => 'civicrm_line_item',
'entity_id' => $lineItem->id,
- 'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $lineItem->label,
+ '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)) {
- $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE);
- $trxnId['id'] = $trxn['financialTrxnId'];
+ $trxnId['id'] = CRM_Contribute_BAO_Contribution::$_trxnIDs;
+ if (empty($trxnId['id'])) {
+ $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE);
+ $trxnId['id'] = $trxn['financialTrxnId'];
+ }
}
$financialItem = self::create($params, NULL, $trxnId);
return $financialItem;
@@ -161,20 +158,23 @@ public static function create(&$params, $ids = NULL, $trxnIds = NULL) {
}
$financialItem->save();
- if (!empty($trxnIds['id'])) {
- $entity_financial_trxn_params = array(
- 'entity_table' => "civicrm_financial_item",
- 'entity_id' => $financialItem->id,
- 'financial_trxn_id' => $trxnIds['id'],
- 'amount' => $params['amount'],
- );
-
- $entity_trxn = new CRM_Financial_DAO_EntityFinancialTrxn();
- $entity_trxn->copyValues($entity_financial_trxn_params);
- if (!empty($ids['entityFinancialTrxnId'])) {
- $entity_trxn->id = $ids['entityFinancialTrxnId'];
+ $financialtrxnIDS = CRM_Utils_Array::value('id', $trxnIds);
+ if (!empty($financialtrxnIDS)) {
+ if (!is_array($financialtrxnIDS)) {
+ $financialtrxnIDS = [$financialtrxnIDS];
+ }
+ foreach ($financialtrxnIDS as $tID) {
+ $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'];
+ }
+ self::createEntityTrxn($entity_financial_trxn_params);
}
- $entity_trxn->save();
}
if (!empty($ids['id'])) {
CRM_Utils_Hook::post('edit', 'FinancialItem', $financialItem->id, $financialItem);
@@ -189,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();
@@ -204,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
*/
@@ -220,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;
@@ -247,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)) {
@@ -280,25 +280,25 @@ public static function checkContactPresent($contactIds, &$error) {
}
/**
- * Get last financial item data.
+ * Get most relevant previous financial item relating to the line item.
*
- * @param int $entityId
+ * This function specifically excludes sales tax.
*
- * @param string $entityTable
+ * @param int $entityId
*
- * @return object CRM_Core_DAO
+ * @return array
*/
- public static function getPreviousFinancialItem($entityId, $entityTable = 'civicrm_line_item') {
- $queryParams = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entityTable, 'String'),
- );
- $query = 'SELECT id, description, status_id, financial_account_id
- FROM civicrm_financial_item
- WHERE entity_id = %1 AND entity_table = %2 ORDER BY id DESC LIMIT 1';
- $prevFinancialItem = CRM_Core_DAO::executeQuery($query, $queryParams);
- $prevFinancialItem->fetch();
- return $prevFinancialItem;
+ public static function getPreviousFinancialItem($entityId) {
+ $params = [
+ 'entity_id' => $entityId,
+ 'entity_table' => 'civicrm_line_item',
+ 'options' => ['limit' => 1, 'sort' => 'id DESC'],
+ ];
+ $salesTaxFinancialAccounts = civicrm_api3('FinancialAccount', 'get', ['is_tax' => 1]);
+ if ($salesTaxFinancialAccounts['count']) {
+ $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 1122981648bb..1d49d6193199 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,
@@ -220,14 +218,14 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
}
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
$prefix = ts('CiviCRM') . ': ';
- $actions = array('add', 'view', 'edit', 'delete');
+ $actions = ['add', 'view', 'edit', 'delete'];
foreach ($financialTypes as $id => $type) {
foreach ($actions as $action) {
if ($descriptions) {
- $permissions[$action . ' contributions of type ' . $type] = array(
+ $permissions[$action . ' contributions of type ' . $type] = [
$prefix . ts($action . ' contributions of type ') . $type,
ts(ucfirst($action) . ' contributions of type ') . $type,
- );
+ ];
}
else {
$permissions[$action . ' contributions of type ' . $type] = $prefix . ts($action . ' contributions of type ') . $type;
@@ -238,13 +236,45 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
$permissions['administer CiviCRM Financial Types'] = $prefix . ts('administer CiviCRM Financial Types');
}
else {
- $permissions['administer CiviCRM Financial Types'] = array(
+ $permissions['administer CiviCRM Financial Types'] = [
$prefix . ts('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 +284,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 +332,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 +348,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 +380,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 +395,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') {
@@ -370,6 +422,7 @@ public static function buildPermissionedClause(&$whereClauses, $component = NULL
* the mode of operation, can be add, view, edit, delete
* @param bool $force
*
+ * @return bool
*/
public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
if (!self::isACLFinancialTypeStatus()) {
@@ -394,20 +447,47 @@ public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
}
/**
- * Check if FT-ACL is turned on or off
+ * Check if the logged in user has permission to edit the given financial type.
+ *
+ * This is called when determining if they can edit things like option values
+ * in price sets. At the moment it is not possible to change an option value from
+ * a type you do not have permission to to a type that you do.
+ *
+ * @todo it is currently not possible to edit disabled types if you have ACLs on.
+ * Do ACLs still apply once disabled? That question should be resolved if tackling
+ * that gap.
+ *
+ * @param int $financialTypeID
*
* @return bool
*/
- public static function isACLFinancialTypeStatus() {
- if (array_key_exists('acl_financial_type', self::$_statusACLFt)) {
- return self::$_statusACLFt['acl_financial_type'];
+ public static function checkPermissionToEditFinancialType($financialTypeID) {
+ if (!self::isACLFinancialTypeStatus()) {
+ return TRUE;
}
- $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;
+ $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(CRM_Core_Action::UPDATE);
+ return isset($financialTypes[$financialTypeID]);
+ }
+
+ /**
+ * Check if FT-ACL is turned on or off.
+ *
+ * @todo rename this function e.g isFinancialTypeACLsEnabled.
+ *
+ * @return bool
+ */
+ public static function isACLFinancialTypeStatus() {
+ 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 (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
+ \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 4ec5dd6a0eb4..faa84e3f69f6 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,35 +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])));
- }
-
- /**
- * Get Financial Account Name.
- *
- * @param int $entityId
- *
- * @param string $entityTable
- *
- * @param string $columnName
- * Column to fetch.
- *
- * @return null|string
- */
- public static function getFinancialAccount($entityId, $entityTable, $columnName = 'name') {
- $join = $columnName == 'name' ? 'LEFT JOIN civicrm_financial_account ON civicrm_entity_financial_account.financial_account_id = civicrm_financial_account.id' : NULL;
- $query = "
-SELECT {$columnName}
-FROM civicrm_entity_financial_account
-{$join}
-WHERE entity_table = %1
-AND entity_id = %2";
-
- $params = array(
- 1 => array($entityTable, 'String'),
- 2 => array($entityId, 'Integer'),
- );
- return CRM_Core_DAO::singleValueQuery($query, $params);
+ CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', [1 => $relationValues[$financialType->account_relationship]]));
}
/**
@@ -185,30 +151,30 @@ public static function getFinancialAccount($entityId, $entityTable, $columnName
* @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];
}
/**
@@ -221,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') {
@@ -291,7 +257,7 @@ public static function createDefaultFinancialAccounts($financialType) {
self::add($params);
}
if (!empty($existingFinancialAccount)) {
- $titles = array();
+ $titles = [];
}
return $titles;
}
@@ -301,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..fbb3e58de800
--- /dev/null
+++ b/CRM/Financial/BAO/Payment.php
@@ -0,0 +1,498 @@
+ $params['contribution_id']]);
+ $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($contribution['contribution_status_id'], 'name');
+
+ $isPaymentCompletesContribution = self::isPaymentCompletesContribution($params['contribution_id'], $params['total_amount']);
+
+ // For legacy reasons Pending payments are completed through completetransaction.
+ // @todo completetransaction should transition components but financial transactions
+ // should be handled through Payment.create.
+ $isSkipRecordingPaymentHereForLegacyHandlingReasons = ($contributionStatus == 'Pending' && $isPaymentCompletesContribution);
+
+ if (!$isSkipRecordingPaymentHereForLegacyHandlingReasons) {
+ $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
+
+ if (CRM_Utils_Array::value('line_item', $params) && !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)) {
+ CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution['total_amount']);
+ }
+ }
+
+ if ($isPaymentCompletesContribution) {
+ civicrm_api3('Contribution', 'completetransaction', ['id' => $contribution['id']]);
+ // Get the trxn
+ $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
+ $ftParams = ['id' => $trxnId['financialTrxnId']];
+ $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams, CRM_Core_DAO::$_nullArray);
+ }
+ elseif ($contributionStatus === 'Pending') {
+ civicrm_api3('Contribution', 'create',
+ [
+ 'id' => $contribution['id'],
+ 'contribution_status_id' => 'Partially paid',
+ ]
+ );
+ }
+
+ 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),
+ ];
+ return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
+ }
+
+ /**
+ * 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]
+ */
+ 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
+ *
+ * @todo - make this protected once recordAdditionalPayment no longer calls it.
+ *
+ * @return CRM_Financial_DAO_FinancialTrxn
+ */
+ public 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);
+ }
+ // add financial item entry
+ $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id);
+ if (!empty($lineItems)) {
+ foreach ($lineItems as $lineItemId => $lineItemValue) {
+ // don't record financial item for cancelled line-item
+ if ($lineItemValue['qty'] == 0) {
+ continue;
+ }
+ $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount);
+ $addFinancialEntry = [
+ 'transaction_date' => $financialTrxn->trxn_date,
+ 'contact_id' => $contributionDAO->contact_id,
+ 'amount' => round($paid, 2),
+ 'currency' => $contributionDAO->currency,
+ 'status_id' => $paidStatus,
+ 'entity_id' => $lineItemId,
+ 'entity_table' => 'civicrm_line_item',
+ ];
+ $trxnIds = ['id' => $financialTrxn->id];
+ CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
+ }
+ }
+ 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, CRM_Core_DAO::$_nullArray);
+
+ // 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);
+ }
+
+}
diff --git a/CRM/Financial/BAO/PaymentProcessor.php b/CRM/Financial/BAO/PaymentProcessor.php
index b2e13d985d6e..fbf922c7c695 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);
}
+ if (isset($params['id']) && isset($params['is_active']) && !isset($params['is_test'])) {
+ // check if is_active has changed & if so update test instance is_active too.
+ $test_id = self::getTestProcessorId($params['id']);
+ $testDAO = new CRM_Financial_DAO_PaymentProcessor();
+ $testDAO->id = $test_id;
+ if ($testDAO->find(TRUE)) {
+ $testDAO->is_active = $params['is_active'];
+ $testDAO->save();
+ }
+ }
+
Civi\Payment\System::singleton()->flushProcessors();
return $processor;
}
@@ -90,6 +104,22 @@ public function __construct() {
parent::__construct();
}
+ /**
+ * Retrieve array of allowed credit cards for this payment processor.
+ * @param interger|null $paymentProcessorID id of processor.
+ * @return array
+ */
+ public static function getCreditCards($paymentProcessorID = NULL) {
+ if (!empty($paymentProcessorID)) {
+ $processor = new CRM_Financial_DAO_PaymentProcessor();
+ $processor->id = $paymentProcessorID;
+ $processor->find(TRUE);
+ $cards = json_decode($processor->accepted_credit_cards, TRUE);
+ return $cards;
+ }
+ return [];
+ }
+
/**
* Retrieve DB object based on input parameters.
*
@@ -121,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);
@@ -138,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;
@@ -187,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];
}
@@ -229,15 +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(),
- ));
+ ]);
}
/**
@@ -263,13 +265,15 @@ public static function defaultComparison($processor1, $processor2) {
* @param string|NULL $mode
* only return this mode - test|live or NULL for all
* @param bool $reset
+ * @param bool $isCurrentDomainOnly
+ * Do we only want to load payment processors associated with the current domain.
*
* @throws CiviCRM_API3_Exception
* @return array
*/
- public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
+ 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)) {
@@ -277,12 +281,14 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
}
}
- $retrievalParameters = array(
+ $retrievalParameters = [
'is_active' => TRUE,
- 'domain_id' => CRM_Core_Config::domainID(),
- 'options' => array('sort' => 'is_default DESC, name'),
+ 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
'api.payment_processor_type.getsingle' => 1,
- );
+ ];
+ if ($isCurrentDomainOnly) {
+ $retrievalParameters['domain_id'] = CRM_Core_Config::domainID();
+ }
if ($mode == 'test') {
$retrievalParameters['is_test'] = 1;
}
@@ -292,7 +298,25 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
$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])) {
@@ -304,7 +328,7 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
}
// 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,
@@ -314,12 +338,12 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
'name' => 'pay_later',
'billing_mode' => '',
'is_default' => 0,
- // This should ideally be retrieved from the DB but existing default is check so we'll code that for now.
- 'payment_instrument_id' => CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name'),
+ 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')),
// Making this optionally recur would give lots of options -but it should
// 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']);
@@ -343,10 +367,14 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE) {
* @return array
* available processors
*/
- public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
- $mode = NULL;
- $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
- $processors = self::getAllPaymentProcessors('all');
+ public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
+ $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : [];
+ if (is_array($ids)) {
+ $processors = self::getAllPaymentProcessors('all', FALSE, FALSE);
+ }
+ else {
+ $processors = self::getAllPaymentProcessors('all');
+ }
if (in_array('TestMode', $capabilities) && is_array($ids)) {
$possibleLiveIDs = array_diff($ids, array_keys($testProcessors));
@@ -364,18 +392,18 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
foreach ($processors as $index => $processor) {
if (is_array($ids) && !in_array($processor['id'], $ids)) {
- unset ($processors[$index]);
+ unset($processors[$index]);
continue;
}
// Invalid processors will store a null value in 'object' (e.g. if not all required config fields are present).
// This is determined by calling when loading the processor via the $processorObject->checkConfig() function.
if (!is_a($processor['object'], 'CRM_Core_Payment')) {
- unset ($processors[$index]);
+ unset($processors[$index]);
continue;
}
foreach ($capabilities as $capability) {
if (($processor['object']->supports($capability)) == FALSE) {
- unset ($processors[$index]);
+ unset($processors[$index]);
continue 1;
}
}
@@ -386,13 +414,33 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
/**
* Is there a processor on this site with the specified capability.
+ *
+ * The capabilities are defined on CRM_Core_Payment and can be extended by
+ * processors.
+ *
+ * examples are
+ * - supportsBackOffice
+ * - supportsLiveMode
+ * - supportsFutureRecurDate
+ * - supportsRecurring
+ * - supportsCancelRecurring
+ * - supportsRecurContributionsForPledges
+ *
+ * They are passed as array('BackOffice');
+ *
+ * Details of specific functions are in the docblocks on the CRM_Core_Payment class.
+ *
* @param array $capabilities
*
* @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];
}
/**
@@ -427,11 +475,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;
}
@@ -455,6 +503,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
@@ -464,7 +513,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()) {
@@ -483,16 +532,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 5431461e18f1..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 cc86dd0df00b..672e3ed366e5 100644
--- a/CRM/Financial/DAO/Currency.php
+++ b/CRM/Financial/DAO/Currency.php
@@ -1,191 +1,199 @@
__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,
- ) ,
- 'name' => array(
+ 'title' => ts('Currency ID'),
+ 'description' => ts('Currency Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_currency',
+ 'entity' => 'Currency',
+ 'bao' => 'CRM_Financial_DAO_Currency',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_currency',
+ 'entity' => 'Currency',
+ 'bao' => 'CRM_Financial_DAO_Currency',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_currency',
+ 'entity' => 'Currency',
+ 'bao' => 'CRM_Financial_DAO_Currency',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'full_name' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_currency',
+ 'entity' => 'Currency',
+ 'bao' => 'CRM_Financial_DAO_Currency',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_currency',
+ 'entity' => 'Currency',
+ 'bao' => 'CRM_Financial_DAO_Currency',
+ '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
*
@@ -193,10 +201,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
*
@@ -204,8 +213,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 = [];
+ 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 886c229eaaf9..687db0a729a6 100644
--- a/CRM/Financial/DAO/EntityFinancialAccount.php
+++ b/CRM/Financial/DAO/EntityFinancialAccount.php
@@ -1,206 +1,215 @@
__table = 'civicrm_entity_financial_account';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Entity Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_account',
+ 'entity' => 'EntityFinancialAccount',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_account',
+ 'entity' => 'EntityFinancialAccount',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'account_relationship' => array(
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Links to an id in the entity_table, such as vid in civicrm_financial_type'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_account',
+ 'entity' => 'EntityFinancialAccount',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'title' => ts('Account Relationship'),
+ 'description' => ts('FK to a new civicrm_option_value (account_relationship)'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_account',
+ 'entity' => 'EntityFinancialAccount',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
+ 'localizable' => 0,
+ '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,
+ '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
*
@@ -208,10 +217,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
*
@@ -219,8 +229,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 = [
+ 'index_entity_id_entity_table_account_relationship' => [
+ 'name' => 'index_entity_id_entity_table_account_relationship',
+ 'field' => [
+ 0 => 'entity_id',
+ 1 => 'entity_table',
+ 2 => 'account_relationship',
+ ],
+ '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 bc3478fea642..dd5940494d7c 100644
--- a/CRM/Financial/DAO/EntityFinancialTrxn.php
+++ b/CRM/Financial/DAO/EntityFinancialTrxn.php
@@ -1,195 +1,202 @@
__table = 'civicrm_entity_financial_trxn';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Entity Financial Transaction ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_trxn',
+ 'entity' => 'EntityFinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_trxn',
+ 'entity' => 'EntityFinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
+ 'localizable' => 0,
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'required' => true,
- ) ,
- 'financial_trxn_id' => array(
+ 'title' => ts('Entity ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_entity_financial_trxn',
+ 'entity' => 'EntityFinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
+ 'localizable' => 0,
+ ],
+ 'financial_trxn_id' => [
'name' => 'financial_trxn_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction Id') ,
+ 'title' => ts('Financial Transaction 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,
+ ],
+ '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
*
@@ -197,10 +204,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
*
@@ -208,8 +216,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 = [
+ 'UI_entity_financial_trxn_entity_table' => [
+ 'name' => 'UI_entity_financial_trxn_entity_table',
+ 'field' => [
+ 0 => 'entity_table',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_entity_financial_trxn::0::entity_table',
+ ],
+ 'UI_entity_financial_trxn_entity_id' => [
+ 'name' => 'UI_entity_financial_trxn_entity_id',
+ 'field' => [
+ 0 => 'entity_id',
+ ],
+ '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 c9fa2c037acc..c6aaa0097196 100644
--- a/CRM/Financial/DAO/FinancialAccount.php
+++ b/CRM/Financial/DAO/FinancialAccount.php
@@ -1,364 +1,393 @@
__table = 'civicrm_financial_account';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'name' => array(
+ 'title' => ts('Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'financial_account_contact_id' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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,
'default' => '3',
- 'html' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_financial_account.accounting_code',
'headerPattern' => '',
'dataPattern' => '',
- ) ,
- 'account_type_code' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_financial_account.account_type_code',
'headerPattern' => '',
'dataPattern' => '',
- ) ,
- 'description' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'parent_id' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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?',
- ) ,
- 'is_deductible' => array(
+ '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?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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?'),
'default' => '1',
- ) ,
- 'is_tax' => array(
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ 'is_tax' => [
'name' => 'is_tax',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Tax Financial Account?') ,
- 'description' => 'Is this account for taxes?',
- ) ,
- 'tax_rate' => array(
+ 'title' => ts('Tax Financial Account?'),
+ 'description' => ts('Is this account for taxes?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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
- ) ,
- ) ,
- 'is_reserved' => array(
+ ],
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Reserved Financial Account?') ,
- 'description' => 'Is this a predefined system object?',
- ) ,
- 'is_active' => array(
+ 'title' => ts('Reserved Financial Account?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Account is Active') ,
- 'description' => 'Is this property active?',
- ) ,
- 'is_default' => array(
+ 'title' => ts('Financial Account is Active'),
+ 'description' => ts('Is this property active?'),
+ 'table_name' => 'civicrm_financial_account',
+ 'entity' => 'FinancialAccount',
+ 'bao' => 'CRM_Financial_BAO_FinancialAccount',
+ 'localizable' => 0,
+ ],
+ '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?',
- ) ,
- 'opening_balance' => array(
- 'name' => 'opening_balance',
- 'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Opening Balance') ,
- 'description' => 'Contains the opening balance for this financial account',
- 'precision' => array(
- 20,
- 2
- ) ,
- ) ,
- 'current_period_opening_balance' => array(
- 'name' => 'current_period_opening_balance',
- 'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Current period opening Balance') ,
- 'description' => 'Contains the opening balance for the current period for this financial account',
- 'precision' => array(
- 20,
- 2
- ) ,
- ) ,
- );
+ 'title' => ts('Default Financial Account'),
+ 'description' => ts('Is this account the default one (or default tax one) for its financial_account_type?'),
+ '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
*
@@ -366,10 +395,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
*
@@ -377,8 +407,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 = [
+ 'UI_name' => [
+ 'name' => 'UI_name',
+ 'field' => [
+ 0 => 'name',
+ ],
+ '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 68a607ebe035..d25859144de4 100644
--- a/CRM/Financial/DAO/FinancialItem.php
+++ b/CRM/Financial/DAO/FinancialItem.php
@@ -1,303 +1,342 @@
__table = 'civicrm_financial_item';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'created_date' => array(
+ 'title' => ts('Financial Item ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'CURRENT_TIMESTAMP',
- ) ,
- 'transaction_date' => array(
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'contact_id' => array(
+ 'title' => ts('Financial Item Transaction Date'),
+ 'description' => ts('Date and time of the source transaction'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_financial_item.contact_id',
'headerPattern' => '',
'dataPattern' => '',
+ '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,
- ) ,
- 'amount' => array(
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ 'default' => '0',
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_financial_item.currency',
'headerPattern' => '',
'dataPattern' => '',
- 'html' => array(
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'financial_account_id' => array(
+ ]
+ ],
+ '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'),
+ '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)'),
+ 'export' => TRUE,
'where' => 'civicrm_financial_item.status_id',
'headerPattern' => '',
'dataPattern' => '',
- 'html' => array(
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_financial_item',
+ 'entity' => 'FinancialItem',
+ 'bao' => 'CRM_Financial_BAO_FinancialItem',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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
*
@@ -305,10 +344,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
*
@@ -316,8 +356,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 = [
+ 'IX_created_date' => [
+ 'name' => 'IX_created_date',
+ 'field' => [
+ 0 => 'created_date',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_financial_item::0::created_date',
+ ],
+ 'IX_transaction_date' => [
+ 'name' => 'IX_transaction_date',
+ 'field' => [
+ 0 => 'transaction_date',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_financial_item::0::transaction_date',
+ ],
+ 'index_entity_id_entity_table' => [
+ 'name' => 'index_entity_id_entity_table',
+ 'field' => [
+ 0 => 'entity_id',
+ 1 => 'entity_table',
+ ],
+ '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 cef23c730aca..f89106a691d2 100644
--- a/CRM/Financial/DAO/FinancialTrxn.php
+++ b/CRM/Financial/DAO/FinancialTrxn.php
@@ -1,378 +1,490 @@
__table = 'civicrm_financial_trxn';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'from_financial_account_id' => array(
+ 'title' => ts('Financial Transaction ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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.'),
+ '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.'),
+ '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'),
'default' => 'NULL',
- ) ,
- 'total_amount' => array(
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ '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
- ) ,
- ) ,
- 'fee_amount' => array(
+ ],
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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
- ) ,
- ) ,
- 'net_amount' => array(
+ ],
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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',
- 'html' => array(
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_payment' => array(
+ ]
+ ],
+ '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,
- ) ,
- 'trxn_id' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'trxn_result_code' => array(
+ 'size' => 10,
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'status_id' => array(
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ ],
+ '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,
- 'pseudoconstant' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ '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'),
+ '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',
- 'html' => array(
+ 'title' => ts('Payment Method'),
+ 'description' => ts('FK to payment_instrument option group values'),
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- 'financial_trxn_check_number' => array(
+ ]
+ ],
+ 'financial_trxn_card_type_id' => [
+ 'name' => 'card_type_id',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Card Type ID'),
+ 'description' => ts('FK to accept_creditcard option group values'),
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
+ 'optionGroupName' => 'accept_creditcard',
+ 'optionEditPath' => 'civicrm/admin/options/accept_creditcard',
+ ]
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_financial_trxn',
+ 'entity' => 'FinancialTrxn',
+ 'bao' => 'CRM_Financial_DAO_FinancialTrxn',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ 'financial_trxn_pan_truncation' => [
+ 'name' => 'pan_truncation',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Pan Truncation'),
+ 'description' => ts('Last 4 digits of credit card'),
+ 'maxlength' => 4,
+ 'size' => 4,
+ '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
*
@@ -380,10 +492,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
*
@@ -391,8 +504,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 = [
+ 'UI_ftrxn_trxn_id' => [
+ 'name' => 'UI_ftrxn_trxn_id',
+ 'field' => [
+ 0 => 'trxn_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_financial_trxn::0::trxn_id',
+ ],
+ 'UI_ftrxn_payment_instrument_id' => [
+ 'name' => 'UI_ftrxn_payment_instrument_id',
+ 'field' => [
+ 0 => 'payment_instrument_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_financial_trxn::0::payment_instrument_id',
+ ],
+ 'UI_ftrxn_check_number' => [
+ 'name' => 'UI_ftrxn_check_number',
+ 'field' => [
+ 0 => 'check_number',
+ ],
+ '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 33397a5d6866..611c7b6506bd 100644
--- a/CRM/Financial/DAO/FinancialType.php
+++ b/CRM/Financial/DAO/FinancialType.php
@@ -1,187 +1,220 @@
__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,
- ) ,
- 'financial_type' => array(
+ '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,
+ 'table_name' => 'civicrm_financial_type',
+ 'entity' => 'FinancialType',
+ 'bao' => 'CRM_Financial_BAO_FinancialType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'description' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_financial_type',
+ 'entity' => 'FinancialType',
+ 'bao' => 'CRM_Financial_BAO_FinancialType',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'is_deductible' => array(
+ 'table_name' => 'civicrm_financial_type',
+ 'entity' => 'FinancialType',
+ 'bao' => 'CRM_Financial_BAO_FinancialType',
+ 'localizable' => 0,
+ '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.'),
'default' => '1',
- ) ,
- 'is_reserved' => array(
+ 'table_name' => 'civicrm_financial_type',
+ 'entity' => 'FinancialType',
+ 'bao' => 'CRM_Financial_BAO_FinancialType',
+ 'localizable' => 0,
+ '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?',
- ) ,
- 'is_active' => array(
+ 'title' => ts('Financial Type is Reserved?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'table_name' => 'civicrm_financial_type',
+ 'entity' => 'FinancialType',
+ 'bao' => 'CRM_Financial_BAO_FinancialType',
+ 'localizable' => 0,
+ '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?'),
+ '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
*
@@ -189,10 +222,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
*
@@ -200,8 +234,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 = [
+ 'UI_id' => [
+ 'name' => 'UI_id',
+ 'field' => [
+ 0 => 'id',
+ ],
+ '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 4a78e522b371..eccbc23fc1cc 100644
--- a/CRM/Financial/DAO/PaymentProcessor.php
+++ b/CRM/Financial/DAO/PaymentProcessor.php
@@ -1,391 +1,540 @@
__table = 'civicrm_payment_processor';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Payment Processor ID'),
+ 'description' => ts('Payment Processor ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- ) ,
- 'description' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ '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,
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 1,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ '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,
- ) ,
- 'payment_processor_type_id' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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?',
- ) ,
- 'is_default' => array(
+ 'title' => ts('Processor is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Is Default?') ,
- 'description' => 'Is this processor the default?',
- ) ,
- 'is_test' => array(
+ 'title' => ts('Processor Is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ 'is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Test Processor?') ,
- 'description' => 'Is this processor for a test site?',
- ) ,
- 'user_name' => array(
+ 'title' => ts('Is Test Processor?'),
+ 'description' => ts('Is this processor for a test site?'),
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'password' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'password' => [
'name' => 'password',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Password') ,
+ 'title' => ts('Password'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- ) ,
- 'signature' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Password',
+ ],
+ ],
+ 'signature' => [
'name' => 'signature',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Signature') ,
- ) ,
- 'url_site' => array(
+ 'title' => ts('Signature'),
+ 'rows' => 4,
+ 'cols' => 40,
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'TextArea',
+ ],
+ ],
+ '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,
- ) ,
- 'url_api' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ '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,
- ) ,
- 'url_recur' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ '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,
- ) ,
- 'url_button' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ '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,
- ) ,
- 'subject' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'subject' => [
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
+ 'title' => ts('Subject'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- ) ,
- 'class_name' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ '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,
- ) ,
- 'billing_mode' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Processor Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
- ) ,
- 'is_recur' => array(
+ 'title' => ts('Processor Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ 'is_recur' => [
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Supports Recurring?') ,
- 'description' => 'Can process recurring contributions',
- ) ,
- 'payment_type' => array(
+ 'title' => ts('Processor Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ '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)'),
'default' => '1',
- ) ,
- 'payment_instrument_id' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => '1',
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 0,
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- );
+ ]
+ ],
+ 'accepted_credit_cards' => [
+ 'name' => 'accepted_credit_cards',
+ 'type' => CRM_Utils_Type::T_TEXT,
+ 'title' => ts('Accepted Credit Cards'),
+ 'description' => ts('array of accepted credit card types'),
+ '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
*
@@ -393,10 +542,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
*
@@ -404,8 +554,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 = [
+ 'UI_name_test_domain_id' => [
+ 'name' => 'UI_name_test_domain_id',
+ 'field' => [
+ 0 => 'name',
+ 1 => 'is_test',
+ 2 => 'domain_id',
+ ],
+ '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 fffa67a0c21a..e5de98746e41 100644
--- a/CRM/Financial/DAO/PaymentProcessorType.php
+++ b/CRM/Financial/DAO/PaymentProcessorType.php
@@ -1,399 +1,484 @@
__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,
- ) ,
- 'name' => array(
+ 'title' => ts('Payment Processor Type ID'),
+ 'description' => ts('Payment Processor Type ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'title' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'description' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'is_active' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type Is Active?') ,
- 'description' => 'Is this processor active?',
- ) ,
- 'is_default' => array(
+ 'title' => ts('Processor Type Is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type is Default?') ,
- 'description' => 'Is this processor the default?',
- ) ,
- 'user_name_label' => array(
+ 'title' => ts('Processor Type is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'password_label' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'signature_label' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'subject_label' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'class_name' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_site_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_api_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_recur_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_button_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_site_test_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_api_test_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_recur_test_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'url_button_test_default' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'billing_mode' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
- 'html' => array(
+ 'title' => ts('Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ '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',
- ) ,
- 'payment_type' => array(
+ 'title' => ts('Processor Type Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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)'),
'default' => '1',
- ) ,
- 'payment_instrument_id' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => '1',
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_payment_processor_type',
+ 'entity' => 'PaymentProcessorType',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
+ 'localizable' => 0,
+ '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
*
@@ -401,10 +486,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
*
@@ -412,8 +498,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 = [
+ 'UI_name' => [
+ 'name' => 'UI_name',
+ 'field' => [
+ 0 => 'name',
+ ],
+ '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 8bd69afe2ce4..923f2fb4fb2e 100644
--- a/CRM/Financial/DAO/PaymentToken.php
+++ b/CRM/Financial/DAO/PaymentToken.php
@@ -1,295 +1,343 @@
__table = 'civicrm_payment_token';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'contact_id' => array(
+ 'title' => ts('Payment Token ID'),
+ 'description' => ts('Payment Token ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
+ '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,
- ) ,
- 'created_date' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => 'CURRENT_TIMESTAMP',
- ) ,
- 'created_id' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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',
- ) ,
- 'email' => array(
+ 'title' => ts('Expiry Date'),
+ 'description' => ts('Date this token expires'),
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'billing_first_name' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'billing_middle_name' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'billing_last_name' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'masked_account_number' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'ip_address' => array(
+ 'table_name' => 'civicrm_payment_token',
+ 'entity' => 'PaymentToken',
+ 'bao' => 'CRM_Financial_DAO_PaymentToken',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- );
+ '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
*
@@ -297,10 +345,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
*
@@ -308,8 +357,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 = [];
+ 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 e16d446fa366..584ed6a338cb 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,13 +95,17 @@ 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'));
+ 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'));
+ }
+ }
// text for sort_name
$this->addElement('text',
@@ -117,14 +121,14 @@ public function buildQuickForm() {
// multiselect for groups
if ($this->_group) {
$this->add('select', 'group', ts('Groups'), $this->_group, FALSE,
- array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
$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')
+ ['id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
CRM_Contribute_BAO_Query::buildSearchForm($this);
@@ -133,37 +137,37 @@ public function buildQuickForm() {
$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);
@@ -171,14 +175,17 @@ public function buildQuickForm() {
$this->add('text', 'name', ts('Batch Name'));
}
+ /**
+ * Set the default values for the form.
+ */
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;
@@ -191,20 +198,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 c5d2059ea3e6..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 7e7ce26dd3be..6b38724a81c4 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);
$financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
if ($financialAccount->financial_account_type_id == $financialAccountTypeId
@@ -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?'));
@@ -104,25 +103,10 @@ public function buildQuickForm() {
$element->freeze();
}
- //CRM-16189
- if (CRM_Contribute_BAO_Contribution::checkContributeSettings('financial_account_bal_enable')) {
- $this->add('text', 'opening_balance', ts('Opening Balance'), $attributes['opening_balance']);
- $this->add('text', 'current_period_opening_balance', ts('Current Period Opening Balance'), $attributes['current_period_opening_balance']);
- $financialAccountType = CRM_Core_PseudoConstant::get(
- 'CRM_Financial_DAO_FinancialAccount',
- 'financial_account_type_id',
- array('labelColumn' => 'name')
- );
- $limitedAccount = array(
- array_search('Asset', $financialAccountType),
- array_search('Liability', $financialAccountType),
- );
- $this->assign('limitedAccount', json_encode($limitedAccount));
- }
$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();
@@ -136,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);
}
/**
@@ -153,7 +137,7 @@ 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) {
@@ -171,10 +155,10 @@ public static function formRule($values, $files, $self) {
if ($self->_action & CRM_Core_Action::UPDATE) {
if (!(isset($values['is_tax']))) {
$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');
@@ -192,7 +176,6 @@ public function setDefaultValues() {
$defaults = parent::setDefaultValues();
if ($this->_action & CRM_Core_Action::ADD) {
$defaults['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id');
- $defaults['opening_balance'] = $defaults['current_period_opening_balance'] = '0.00';
}
return $defaults;
}
@@ -202,8 +185,12 @@ public function setDefaultValues() {
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
- CRM_Financial_BAO_FinancialAccount::del($this->_id);
- CRM_Core_Session::setStatus(ts('Selected Financial Account has been deleted.'));
+ if (CRM_Financial_BAO_FinancialAccount::del($this->_id)) {
+ CRM_Core_Session::setStatus(ts('Selected Financial Account has been deleted.'));
+ }
+ else {
+ CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialAccount', "reset=1&action=browse"));
+ }
}
else {
// store the submitted values in an array
@@ -212,9 +199,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 24694be0a2cd..283db9a3a241 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,41 @@ 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 = [
+ '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 +251,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 +261,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 +290,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 e811895ab090..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 268a28abba3c..e0940a738af1 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,11 +237,12 @@ 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) {
$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');
@@ -285,7 +285,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 +299,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 9cfa0ca6f7cb..a559e5ec9274 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,
@@ -56,13 +70,16 @@ public function preProcess() {
$this->currency = CRM_Utils_Request::retrieve('currency', 'String', CRM_Core_DAO::$_nullObject,
TRUE);
+ $this->paymentInstrumentID = CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer');
+ $this->isBackOffice = CRM_Utils_Request::retrieve('is_back_office', 'Integer');
+
$this->assignBillingType();
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_paymentProcessorID);
CRM_Core_Payment_ProcessorForm::preProcess($this);
- self::addCreditCardJs();
+ self::addCreditCardJs($this->_paymentProcessorID);
$this->assign('paymentProcessorID', $this->_paymentProcessorID);
$this->assign('currency', $this->currency);
@@ -72,9 +89,14 @@ public function preProcess() {
}
/**
+ * Get currency
+ *
+ * @param array $submittedValues
+ * Required for consistency with other form methods.
+ *
* @return string
*/
- public function getCurrency() {
+ public function getCurrency($submittedValues = []) {
return $this->currency;
}
@@ -96,14 +118,77 @@ public function setDefaultValues() {
/**
* Add JS to show icons for the accepted credit cards.
+ *
+ * @param int $paymentProcessorID
+ * @param string $region
*/
- public static function addCreditCardJs() {
- $creditCardTypes = CRM_Core_Payment_Form::getCreditCardCSSNames();
+ public static function addCreditCardJs($paymentProcessorID = NULL, $region = 'billing-block') {
+ $creditCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($paymentProcessorID);
+ 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)
+ // 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) . ';');
+ ->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..105b98641c14
--- /dev/null
+++ b/CRM/Financial/Form/PaymentEdit.php
@@ -0,0 +1,324 @@
+_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);
+
+ CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath()));
+ }
+
+ /**
+ * 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 ce4438ea21db..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 2980b8b464c4..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);
@@ -94,42 +94,42 @@ public static function jqFinancialRelation($config) {
if ($_GET['_value'] != 'select') {
$financialAccountType = CRM_Financial_BAO_FinancialAccount::getfinancialAccountRelations(TRUE);
- $financialAccountId = CRM_Utils_Request::retrieve('_value', 'Positive', CRM_Core_DAO::$_nullObject);
+ $financialAccountId = CRM_Utils_Request::retrieve('_value', 'Positive');
$financialAccountTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $financialAccountId, 'financial_account_type_id');
}
$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,
- );
+ ];
}
}
}
@@ -145,7 +145,7 @@ public static function jqFinancialType($config) {
) {
CRM_Utils_System::civiExit();
}
- $productId = CRM_Utils_Request::retrieve('_value', 'Positive', CRM_Core_DAO::$_nullObject);
+ $productId = CRM_Utils_Request::retrieve('_value', 'Positive');
$elements = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Product', $productId, 'financial_type_id');
CRM_Utils_JSON::output($elements);
}
@@ -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',
- 'name',
- 'civicrm_contribution.currency as currency',
+ '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 1c656baef670..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 7db65b0edc85..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 4e60cac172b3..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 1bb6a3319561..6bb3b325ff79 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,17 +107,17 @@ 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';
@@ -177,7 +153,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 1a2f76f4f395..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 9e2fe8763472..b817cae90911 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;
}
@@ -89,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,
@@ -128,69 +133,66 @@ 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'];
- $value['check_permission'] = FALSE;
- $contact = CRM_Core_BAO_UFGroup::findContact($value, NULL, 'Individual');
+ $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($value, 'Individual', 'Supervised', [], FALSE);
- if (!$contact) {
- $contact = self::add($value);
+ if (!$contactID) {
+ $contactID = self::add($value);
}
// attempt to save activity targets
- $targetParams = array(
+ $targetParams = [
'activity_id' => $activity->id,
- 'contact_id' => $contact,
+ 'contact_id' => $contactID,
'record_type_id' => $targetID,
- );
+ ];
// See if it already exists
$activityContact = new CRM_Activity_DAO_ActivityContact();
$activityContact->activity_id = $activity->id;
- $activityContact->contact_id = $contact;
+ $activityContact->contact_id = $contactID;
$activityContact->find(TRUE);
if (empty($activityContact->id)) {
- $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
+ CRM_Activity_BAO_ActivityContact::create($targetParams);
}
}
$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'];
}
@@ -199,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'];
}
@@ -219,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
@@ -256,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
@@ -265,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) {
@@ -285,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
@@ -299,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);
}
}
}
@@ -338,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 94b1f249f9a3..568c648d3344 100644
--- a/CRM/Friend/DAO/Friend.php
+++ b/CRM/Friend/DAO/Friend.php
@@ -1,270 +1,302 @@
__table = 'civicrm_tell_friend';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Friend ID'),
+ 'description' => ts('Friend ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 0,
+ ],
+ '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' => array(
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Foreign key to the referenced item.'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 0,
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Title') ,
+ 'title' => ts('Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'html' => array(
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 1,
+ '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.',
- 'html' => array(
+ 'title' => ts('Intro'),
+ 'description' => ts('Introductory message to contributor or participant displayed on the Tell a Friend form.'),
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 1,
+ '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.',
- 'html' => array(
+ 'title' => ts('Suggested Message'),
+ 'description' => ts('Suggested message to friends, provided as default on the Tell A Friend form.'),
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 1,
+ '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.',
- 'html' => array(
+ 'title' => ts('Thank You Text'),
+ 'description' => ts('Thank you message displayed on success page.'),
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'html' => array(
+ 'title' => ts('Enabled?'),
+ 'table_name' => 'civicrm_tell_friend',
+ 'entity' => 'Friend',
+ 'bao' => 'CRM_Friend_BAO_Friend',
+ '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
*
@@ -272,10 +304,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
*
@@ -283,8 +316,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 = [];
+ 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 ff7322e6b015..70cd21086dc5 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,7 +125,7 @@ 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;
@@ -152,7 +160,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['entity_id'] = $this->_entityId;
$defaults['entity_table'] = $this->_entityTable;
@@ -197,7 +205,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 +218,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 +244,7 @@ public function buildQuickForm() {
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
$valid = FALSE;
foreach ($fields['friend'] as $key => $val) {
@@ -285,7 +292,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 99ee54f9b71e..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 e90d85541448..bf5b6cb51828 100644
--- a/CRM/Friend/Form/Event.php
+++ b/CRM/Friend/Form/Event.php
@@ -1,9 +1,9 @@
assign('selectedChild', '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 fbc2ec867e29..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' => 'Grant Status',
- 'name' => 'grant_status',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_type' => array(
- 'title' => 'Grant Type',
- 'name' => 'grant_type',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_money_transfer_date' => array(
- 'title' => 'Grant Money Transfer Date',
- 'name' => 'grant_money_transfer_date',
- 'data_type' => CRM_Utils_Type::T_DATE,
- ),
- 'grant_amount_requested' => array(
- 'title' => 'Grant Amount Requested',
- 'name' => 'grant_amount_requested',
- 'data_type' => CRM_Utils_Type::T_FLOAT,
- ),
- 'grant_application_received_date' => array(
- 'title' => '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 b03b65c25d89..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;
@@ -267,15 +266,6 @@ public static function from($name, $mode, $side) {
return $from;
}
- /**
- * Getter for the qill object.
- *
- * @return string
- */
- public function qill() {
- return (isset($this->_qill)) ? $this->_qill : "";
- }
-
/**
* @param $mode
* @param bool $includeCustomFields
@@ -288,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,
@@ -300,88 +290,70 @@ 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->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->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->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');
- $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_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');
-
- // add all the custom searchable fields
- $grant = array('Grant');
- $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $grant);
- if ($groupDetails) {
- $form->assign('grantGroupTree', $groupDetails);
- foreach ($groupDetails as $group) {
- foreach ($group['fields'] as $field) {
- $fieldId = $field['id'];
- $elementName = 'custom_' . $fieldId;
- CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
- }
- }
- }
+ self::addCustomFormFields($form, ['Grant']);
$form->assign('validGrant', TRUE);
}
- /**
- * @param $row
- * @param int $id
- */
- public static function searchAction(&$row, $id) {
- }
-
- /**
- * @param $tables
- */
- public static function tableNames(&$tables) {
- }
-
}
diff --git a/CRM/Grant/Controller/Search.php b/CRM/Grant/Controller/Search.php
index 7514a7d6a309..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
+ * 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,
- ) ,
- 'grant_contact_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ ],
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_grant.contact_id',
'headerPattern' => '',
'dataPattern' => '',
+ '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' => '',
- ) ,
- 'decision_date' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Grant Report Due Date'),
+ 'description' => ts('Date on which grant report is due.'),
+ 'import' => TRUE,
+ 'where' => 'civicrm_grant.grant_due_date',
+ 'headerPattern' => '',
+ 'dataPattern' => '',
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
+ 'export' => TRUE,
'where' => 'civicrm_grant.grant_type_id',
'headerPattern' => '',
'dataPattern' => '',
- 'html' => array(
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_total',
'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_granted',
'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'rationale' => array(
+ ]
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => FALSE,
+ 'table_name' => 'civicrm_grant',
+ 'entity' => 'Grant',
+ 'bao' => 'CRM_Grant_BAO_Grant',
+ 'localizable' => 0,
+ '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.'),
'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
*
@@ -432,10 +504,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
*
@@ -443,8 +516,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 = [
+ 'index_grant_type_id' => [
+ 'name' => 'index_grant_type_id',
+ 'field' => [
+ 0 => 'grant_type_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_grant::0::grant_type_id',
+ ],
+ 'index_status_id' => [
+ 'name' => 'index_status_id',
+ 'field' => [
+ 0 => 'status_id',
+ ],
+ '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 927543463fe3..36d7afa24fe8 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,6 @@ 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();
}
return $defaults;
@@ -170,36 +154,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 +206,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(
- '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'),
- ),
- )
- );
+ $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'),
+ ],
+ ]);
if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Applicant'), array('create' => TRUE), TRUE);
+ $this->addEntityRef('contact_id', ts('Applicant'), ['create' => TRUE], TRUE);
}
}
@@ -276,7 +258,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 ba7cb835f211..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 5e58a6df1123..9cb7c8e397cc 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', CRM_Core_DAO::$_nullObject);
- $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()));
}
}
@@ -284,9 +263,7 @@ public function fixFormValues() {
return;
}
- $status = CRM_Utils_Request::retrieve('status', 'String',
- CRM_Core_DAO::$_nullObject
- );
+ $status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
$this->_formValues['grant_status_id'] = $status;
$this->_defaults['grant_status_id'] = $status;
@@ -321,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 3f5bf626eaa9..e868f4d64665 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');
$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 c07d2da8d686..925da7565f62 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 b606bf5a3017..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 aded9b163dc2..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 b06fb709bec5..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 ecd8ddddb006..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 ff42c27a8ed3..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 f0ec27412463..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();
@@ -198,10 +198,7 @@ public function setContext() {
}
$session->pushUserContext($url);
- if (CRM_Utils_Request::retrieve('confirmed', 'Boolean',
- CRM_Core_DAO::$_nullObject
- )
- ) {
+ if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
CRM_Grant_BAO_Grant::del($this->_id);
CRM_Utils_System::redirect($url);
}
diff --git a/CRM/Grant/Selector/Search.php b/CRM/Grant/Selector/Search.php
index 92a42f52dbdb..19ff51cd4fa6 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 c38316fada2a..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 8a8f50b68aa7..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]);
- }
- CRM_Utils_Hook::searchTasks('grant', self::$_tasks);
- asort(self::$_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'];
+ if (!CRM_Core_Permission::check('delete in CiviGrant')) {
+ unset(self::$_tasks[self::TASK_DELETE]);
+ }
+
+ parent::tasks();
}
- return $titles;
+
+ return self::$_tasks;
}
/**
@@ -118,26 +100,28 @@ 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 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;
}
@@ -151,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 debc2e7857ef..8e3f05464afc 100644
--- a/CRM/Group/Controller.php
+++ b/CRM/Group/Controller.php
@@ -1,9 +1,9 @@
_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 +165,6 @@ public function preProcess() {
*/
public function setDefaultValues() {
$defaults = array();
-
if (isset($this->_id)) {
$defaults = $this->_groupValues;
if (!empty($defaults['group_type'])) {
@@ -177,6 +181,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() &&
@@ -208,17 +215,16 @@ public function setDefaultValues() {
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'),
- ),
- )
- );
+ array(
+ 'type' => 'next',
+ 'name' => ts('Delete Group'),
+ 'isDefault' => TRUE,
+ ),
+ array(
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ),
+ ));
return;
}
@@ -254,34 +260,29 @@ public function buildQuickForm() {
//CRM-14190
$parentGroups = self::buildParentGroups($this);
-
- if (CRM_Core_Permission::check('administer Multiple Organizations') && CRM_Core_Permission::isMultisiteEnabled()) {
- //group organization Element
- $props = array('api' => array('params' => array('contact_type' => 'Organization')));
- $this->addEntityRef('organization_id', ts('Organization'), $props);
- }
+ self::buildGroupOrganizations($this);
// is_reserved property CRM-9936
$this->addElement('checkbox', 'is_reserved', ts('Reserved Group?'));
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'),
- ),
- )
- );
+ 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()) {
@@ -361,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) {
@@ -372,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;
}
@@ -383,19 +381,13 @@ public function postProcess() {
$params['group_organization'] = $this->_groupOrganizationID;
}
- $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
-
- $groupTypeIds = array();
- $groupType = CRM_Utils_Array::value('group_type', $params);
- if (is_array($groupType)) {
- foreach ($groupType as $type => $selected) {
- if ($selected) {
- $groupTypeIds[] = $type;
- }
- }
+ // 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['group_type'] = $groupTypeIds;
+ $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'
@@ -464,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];
@@ -478,10 +470,26 @@ 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;
}
+ /**
+ * Add the group organization checkbox to the form.
+ *
+ * Note this was traditionally a multisite thing - there is no particular reason why it is not available
+ * as a general field - it's historical use-case driven.
+ *
+ * @param CRM_Core_Form $form
+ */
+ public static function buildGroupOrganizations(&$form) {
+ if (CRM_Core_Permission::check('administer Multiple Organizations') && CRM_Core_Permission::isMultisiteEnabled()) {
+ //group organization Element
+ $props = array('api' => array('params' => array('contact_type' => 'Organization')));
+ $form->addEntityRef('organization_id', ts('Organization'), $props);
+ }
+ }
+
}
diff --git a/CRM/Group/Form/Search.php b/CRM/Group/Form/Search.php
index 7e07ae9916f0..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 c9bd98791c14..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 56468ce24833..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 6456f05f7f8b..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)')];
}
/**
@@ -66,14 +66,18 @@ public function buildQuickForm(&$form) {
$config = CRM_Core_Config::singleton();
$uploadFileSize = CRM_Utils_Number::formatUnitSize($config->maxFileSize . 'm', TRUE);
+ //Fetch uploadFileSize from php_ini when $config->maxFileSize is set to "no limit".
+ if (empty($uploadFileSize)) {
+ $uploadFileSize = CRM_Utils_Number::formatUnitSize(ini_get('upload_max_filesize'), TRUE);
+ }
$uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
$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');
@@ -127,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");
@@ -188,7 +192,7 @@ private static function _CsvToTable(
}
}
else {
- $columns = array();
+ $columns = [];
foreach ($firstrow as $i => $_) {
$columns[] = "col_$i";
}
@@ -235,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 27107e79b4a2..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 51a311a32b17..ae577f0c519c 100644
--- a/CRM/Import/Form/DataSource.php
+++ b/CRM/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
maxFileSize . 'm', TRUE);
+
+ //Fetch uploadFileSize from php_ini when $config->maxFileSize is set to "no limit".
+ if (empty($uploadFileSize)) {
+ $uploadFileSize = CRM_Utils_Number::formatUnitSize(ini_get('upload_max_filesize'), TRUE);
+ }
$uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
$this->assign('uploadSize', $uploadSize);
$this->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'),
- ),
- )
- );
+ ],
+ ]);
}
/**
@@ -111,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
@@ -132,9 +132,9 @@ protected function addContactTypeSelector() {
ts('Contact Type')
);
- $this->setDefaults(array(
+ $this->setDefaults([
'contactType' => CRM_Import_Parser::CONTACT_INDIVIDUAL,
- ));
+ ]);
}
/**
@@ -167,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 cb2a9c4c8b93..c6a82f7877a9 100644
--- a/CRM/Import/Form/MapField.php
+++ b/CRM/Import/Form/MapField.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 7dd9ddc0e017..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/Parser.php b/CRM/Import/Parser.php
index 295a839f7cf6..cf01fdd05482 100644
--- a/CRM/Import/Parser.php
+++ b/CRM/Import/Parser.php
@@ -1,9 +1,9 @@
_maxLinesToProcess = 0;
- $this->_maxErrorCount = self::MAX_ERRORS;
}
/**
@@ -279,7 +284,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 +297,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)) {
@@ -3080,11 +2934,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',
@@ -3095,7 +2949,7 @@ public static function getContactMailingSelector(&$params) {
array_push($contactMailings, $mailing);
}
- $contactMailingsDT = array();
+ $contactMailingsDT = [];
$contactMailingsDT['data'] = $contactMailings;
$contactMailingsDT['recordsTotal'] = $params['total'];
$contactMailingsDT['recordsFiltered'] = $params['total'];
@@ -3112,7 +2966,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'];
@@ -3131,7 +2985,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);
}
@@ -3145,43 +2999,55 @@ 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;
}
/**
- * Whitelist of possible values for the entity_table field
+ * White-list of possible values for the entity_table field.
+ *
* @return array
*/
public static function mailingGroupEntityTables() {
- $tables = array(
- CRM_Contact_BAO_Group::getTableName(),
- CRM_Mailing_BAO_Mailing::getTableName(),
- );
- // Identical keys & values
- return array_combine($tables, $tables);
+ return [
+ CRM_Contact_BAO_Group::getTableName() => 'Group',
+ CRM_Mailing_BAO_Mailing::getTableName() => 'Mailing',
+ ];
}
/**
@@ -3193,9 +3059,64 @@ 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') {
+ return CRM_Utils_System::url('civicrm/mailing/view', ['id' => $id], $absolute, NULL, TRUE, TRUE);
+ }
+ }
+
+ /**
+ * Get a list of template types which can be used as `civicrm_mailing.template_type`.
+ *
+ * @return array
+ * A list of template-types, keyed numerically. Each defines:
+ * - name: string, a short symbolic name
+ * - editorUrl: string, Angular template name
+ *
+ * Ex: $templateTypes[0] === array('name' => 'mosaico', 'editorUrl' => '~/crmMosaico/editor.html').
+ */
+ public static function getTemplateTypes() {
+ if (!isset(Civi::$statics[__CLASS__]['templateTypes'])) {
+ $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 = ['weight' => 0];
+ foreach (array_keys($types) as $typeName) {
+ $types[$typeName] = array_merge($defaults, $types[$typeName]);
+ }
+ usort($types, function ($a, $b) {
+ if ($a['weight'] === $b['weight']) {
+ return 0;
+ }
+ return $a['weight'] < $b['weight'] ? -1 : 1;
+ });
+
+ Civi::$statics[__CLASS__]['templateTypes'] = $types;
+ }
+
+ return Civi::$statics[__CLASS__]['templateTypes'];
+ }
+
+ /**
+ * Get a list of template types.
+ *
+ * @return array
+ * Array(string $name => string $label).
+ */
+ public static function getTemplateTypeNames() {
+ $r = [];
+ foreach (self::getTemplateTypes() as $type) {
+ $r[$type['name']] = $type['name'];
}
+ return $r;
}
}
diff --git a/CRM/Mailing/BAO/MailingAB.php b/CRM/Mailing/BAO/MailingAB.php
index 570a3c168ed9..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 9377e405f2ac..8f3dff95e2d4 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'])) {
+ CRM_Mailing_BAO_Mailing::getRecipients($params['mailing_id']);
+ }
+ CRM_Utils_Hook::post($op, 'MailingJob', $jobDAO->id, $jobDAO);
+ return $jobDAO;
}
/**
- * Initiate all pending/ready jobs
+ * Initiate all pending/ready jobs.
*
* @param array $testParams
- * @param null $mode
+ * @param string $mode
+ *
+ * @return bool|null
*/
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');
@@ -170,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();
}
@@ -185,11 +188,16 @@ 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
- $isComplete = $job->deliver($mailer, $testParams);
+ if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
+ $isComplete = Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER, [$job, $mailer, $testParams]);
+ }
+ else {
+ $isComplete = $job->deliver($mailer, $testParams);
+ }
CRM_Utils_Hook::post('create', 'CRM_Mailing_DAO_Spool', $job->id, $isComplete);
@@ -198,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
@@ -271,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);
@@ -299,7 +301,6 @@ public static function runJobs_post($mode = NULL) {
}
}
-
/**
* before we run jobs, we need to split the jobs
* @param int $offset
@@ -367,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
@@ -402,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( );
@@ -421,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);
}
}
+
}
/**
@@ -447,9 +446,15 @@ 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.
+ // Skip the recipient in this case.
+ if (empty($recipients->email_id) && empty($recipients->phone_id)) {
+ continue;
+ }
+
if ($recipients->phone_id) {
$recipients->email_id = "null";
}
@@ -457,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 = [];
}
}
@@ -480,74 +485,24 @@ 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')) {
+ throw new \RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
+ }
+
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->id = $this->mailing_id;
$mailing->find(TRUE);
$mailing->free();
- $eq = new CRM_Mailing_Event_BAO_Queue();
- $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
- $emailTable = CRM_Core_BAO_Email::getTableName();
- $phoneTable = CRM_Core_DAO_Phone::getTableName();
- $contactTable = CRM_Contact_BAO_Contact::getTableName();
- $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
- $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
-
- list($aclJoin, $aclWhere) = CRM_ACL_BAO_ACL::buildAcl($mailing->created_id);
-
- $query = " SELECT $eqTable.id,
- $emailTable.email as email,
- $eqTable.contact_id,
- $eqTable.hash,
- NULL as phone
- FROM $eqTable
- INNER JOIN $emailTable
- ON $eqTable.email_id = $emailTable.id
- INNER JOIN $contactTable contact_a
- ON contact_a.id = $emailTable.contact_id
- LEFT JOIN $edTable
- ON $eqTable.id = $edTable.event_queue_id
- LEFT JOIN $ebTable
- ON $eqTable.id = $ebTable.event_queue_id
- $aclJoin
- WHERE $eqTable.job_id = " . $this->id . "
- AND $edTable.id IS null
- AND $ebTable.id IS null
- AND contact_a.is_opt_out = 0
- $aclWhere";
-
- if ($mailing->sms_provider_id) {
- $query = "
- SELECT $eqTable.id,
- $phoneTable.phone as phone,
- $eqTable.contact_id,
- $eqTable.hash,
- NULL as email
- FROM $eqTable
- INNER JOIN $phoneTable
- ON $eqTable.phone_id = $phoneTable.id
- INNER JOIN $contactTable contact_a
- ON contact_a.id = $phoneTable.contact_id
- LEFT JOIN $edTable
- ON $eqTable.id = $edTable.event_queue_id
- LEFT JOIN $ebTable
- ON $eqTable.id = $ebTable.event_queue_id
- $aclJoin
- WHERE $eqTable.job_id = " . $this->id . "
- AND $edTable.id IS null
- AND $ebTable.id IS null
- AND ( contact_a.is_opt_out = 0
- OR contact_a.do_not_sms = 0 )
- $aclWhere";
- }
- $eq->query($query);
-
$config = NULL;
if ($config == NULL) {
@@ -559,7 +514,7 @@ public function deliver(&$mailer, $testParams = NULL) {
}
$job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
- $fields = array();
+ $fields = [];
if (!empty($testParams)) {
$mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
@@ -581,11 +536,8 @@ public function deliver(&$mailer, $testParams = NULL) {
// make sure that there's no more than $mailerBatchLimit mails processed in a run
$mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
+ $eq = self::findPendingTasks($this->id, $mailing->sms_provider_id ? 'sms' : 'email');
while ($eq->fetch()) {
- // if ( ( $mailsProcessed % 100 ) == 0 ) {
- // CRM_Utils_System::xMemory( "$mailsProcessed: " );
- // }
-
if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
if (!empty($fields)) {
$this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
@@ -595,20 +547,20 @@ public function deliver(&$mailer, $testParams = NULL) {
}
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 = [];
}
}
@@ -621,6 +573,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.
@@ -641,14 +595,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) {
@@ -668,7 +625,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.
@@ -693,11 +650,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]);
}
@@ -720,18 +677,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;
}
@@ -750,11 +706,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())
);
@@ -821,9 +777,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.
*
@@ -839,17 +836,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 = "
@@ -861,16 +854,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.
*
@@ -884,13 +920,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'));
}
@@ -906,10 +942,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 ";
}
@@ -938,7 +971,7 @@ public function writeToDB(
if (!empty($deliveredParams)) {
CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
- $deliveredParams = array();
+ $deliveredParams = [];
}
if ($writeActivity === NULL) {
@@ -954,25 +987,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),
@@ -983,7 +1009,7 @@ public function writeToDB(
'status_id' => 2,
'deleteActivityTarget' => FALSE,
'campaign_id' => $mailing->campaign_id,
- );
+ ];
//check whether activity is already created for this mailing.
//if yes then create only target contact record.
@@ -994,10 +1020,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) {
@@ -1007,7 +1033,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);
}
@@ -1031,8 +1057,92 @@ public function writeToDB(
$result = FALSE;
}
- $targetParams = array();
+ $targetParams = [];
+ }
+
+ return $result;
+ }
+
+ /**
+ * Search the mailing-event queue for a list of pending delivery tasks.
+ *
+ * @param int $jobId
+ * @param string $medium
+ * Ex: 'email' or 'sms'.
+ *
+ * @return \CRM_Mailing_Event_BAO_Queue
+ * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
+ */
+ public static function findPendingTasks($jobId, $medium) {
+ $eq = new CRM_Mailing_Event_BAO_Queue();
+ $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
+ $emailTable = CRM_Core_BAO_Email::getTableName();
+ $phoneTable = CRM_Core_BAO_Phone::getTableName();
+ $contactTable = CRM_Contact_BAO_Contact::getTableName();
+ $deliveredTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
+ $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
+
+ $query = " SELECT $queueTable.id,
+ $emailTable.email as email,
+ $queueTable.contact_id,
+ $queueTable.hash,
+ NULL as phone
+ FROM $queueTable
+ INNER JOIN $emailTable
+ ON $queueTable.email_id = $emailTable.id
+ INNER JOIN $contactTable
+ ON $contactTable.id = $emailTable.contact_id
+ LEFT JOIN $deliveredTable
+ ON $queueTable.id = $deliveredTable.event_queue_id
+ LEFT JOIN $bounceTable
+ ON $queueTable.id = $bounceTable.event_queue_id
+ WHERE $queueTable.job_id = " . $jobId . "
+ AND $deliveredTable.id IS null
+ AND $bounceTable.id IS null
+ AND $contactTable.is_opt_out = 0";
+
+ if ($medium === 'sms') {
+ $query = "
+ SELECT $queueTable.id,
+ $phoneTable.phone as phone,
+ $queueTable.contact_id,
+ $queueTable.hash,
+ NULL as email
+ FROM $queueTable
+ INNER JOIN $phoneTable
+ ON $queueTable.phone_id = $phoneTable.id
+ INNER JOIN $contactTable
+ ON $contactTable.id = $phoneTable.contact_id
+ LEFT JOIN $deliveredTable
+ ON $queueTable.id = $deliveredTable.event_queue_id
+ LEFT JOIN $bounceTable
+ ON $queueTable.id = $bounceTable.event_queue_id
+ WHERE $queueTable.job_id = " . $jobId . "
+ AND $deliveredTable.id IS null
+ AND $bounceTable.id IS null
+ AND ( $contactTable.is_opt_out = 0
+ OR $contactTable.do_not_sms = 0 )";
}
+ $eq->query($query);
+ 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 5e563472e21d..ff1e5a8dd078 100644
--- a/CRM/Mailing/BAO/Query.php
+++ b/CRM/Mailing/BAO/Query.php
@@ -1,9 +1,9 @@
'mailing_id',
- 'title' => 'Mailing ID',
+ 'title' => ts('Mailing ID'),
'where' => 'civicrm_mailing.id',
- );
+ ];
}
return self::$_mailingFields;
}
@@ -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,12 +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';
}
- $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;
@@ -293,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',
@@ -305,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;
@@ -336,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,
@@ -346,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,
@@ -356,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,
@@ -383,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;
@@ -402,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'));
@@ -506,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 80fb7f8425e7..608f83db67f5 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);
}
@@ -79,7 +79,7 @@ public static function mailingQuery(
WHERE mailing_id = %1
$limitString
";
- $params = array(1 => array($mailingID, 'Integer'));
+ $params = [1 => [$mailingID, 'Integer']];
return CRM_Core_DAO::executeQuery($sql, $params);
}
@@ -102,7 +102,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 513270d94c63..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 032ed680b4ed..6c5b6590f2d9 100644
--- a/CRM/Mailing/BAO/TrackableURL.php
+++ b/CRM/Mailing/BAO/TrackableURL.php
@@ -1,9 +1,9 @@
url = $url;
$tracker->mailing_id = $mailing_id;
- if (strlen($tracker->url) > 254) {
- return $url;
- }
+
if (!$tracker->find(TRUE)) {
$tracker->save();
}
@@ -99,7 +97,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 9924aa7d8e85..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 b5ba66f27c73..447451c0dc90 100644
--- a/CRM/Mailing/DAO/BouncePattern.php
+++ b/CRM/Mailing/DAO/BouncePattern.php
@@ -1,156 +1,154 @@
__table = 'civicrm_mailing_bounce_pattern';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'bounce_type_id' => array(
+ 'title' => ts('Bounce Pattern ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_bounce_pattern',
+ 'entity' => 'BouncePattern',
+ 'bao' => 'CRM_Mailing_BAO_BouncePattern',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- ) ,
- );
+ '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
*
@@ -158,10 +156,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
*
@@ -169,8 +168,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 = [];
+ 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 73647fc0f5c4..134ed3302e2b 100644
--- a/CRM/Mailing/DAO/BounceType.php
+++ b/CRM/Mailing/DAO/BounceType.php
@@ -1,156 +1,158 @@
__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,
- ) ,
- 'name' => array(
+ 'title' => ts('Bounce Type ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_bounce_type',
+ 'entity' => 'BounceType',
+ 'bao' => 'CRM_Mailing_DAO_BounceType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'description' => array(
+ 'table_name' => 'civicrm_mailing_bounce_type',
+ 'entity' => 'BounceType',
+ 'bao' => 'CRM_Mailing_DAO_BounceType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'hold_threshold' => array(
+ 'table_name' => 'civicrm_mailing_bounce_type',
+ 'entity' => 'BounceType',
+ 'bao' => 'CRM_Mailing_DAO_BounceType',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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
*
@@ -158,10 +160,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
*
@@ -169,8 +172,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 = [];
+ 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 10114d85ebbb..000000000000
--- a/CRM/Mailing/DAO/Component.php
+++ /dev/null
@@ -1,238 +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,
- ) ,
- '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,
- ) ,
- '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,
- '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,
- ) ,
- '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,
- '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,
- '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?',
- ) ,
- 'is_active' => array(
- 'name' => 'is_active',
- 'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Mailing Component Is Active?') ,
- 'description' => 'Is this property active?',
- ) ,
- );
- 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;
- }
-}
diff --git a/CRM/Mailing/DAO/Mailing.php b/CRM/Mailing/DAO/Mailing.php
index 0e657af7059d..e57dc5ced88d 100644
--- a/CRM/Mailing/DAO/Mailing.php
+++ b/CRM/Mailing/DAO/Mailing.php
@@ -1,710 +1,995 @@
__table = 'civicrm_mailing';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Mailing ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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.',
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'footer_id' => array(
+ 'title' => ts('Mailing Header'),
+ 'description' => ts('FK to the header component.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'footer_id' => [
'name' => 'footer_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Footer') ,
- 'description' => 'FK to the footer component.',
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'reply_id' => array(
+ 'title' => ts('Mailing Footer'),
+ 'description' => ts('FK to the footer component.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'reply_id' => [
'name' => 'reply_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Reply') ,
- 'description' => 'FK to the auto-responder component.',
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'unsubscribe_id' => array(
+ 'title' => ts('Mailing Reply'),
+ 'description' => ts('FK to the auto-responder component.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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.',
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'resubscribe_id' => array(
+ 'title' => ts('Mailing Unsubscribe'),
+ 'description' => ts('FK to the unsubscribe component.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'FKClassName' => 'CRM_Mailing_DAO_MailingComponent',
+ ],
+ 'resubscribe_id' => [
'name' => 'resubscribe_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Resubscribe') ,
- ) ,
- 'optout_id' => array(
+ 'title' => ts('Mailing Resubscribe'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ 'optout_id' => [
'name' => 'optout_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mailing Opt Out') ,
- 'description' => 'FK to the opt-out component.',
- 'FKClassName' => 'CRM_Mailing_DAO_Component',
- ) ,
- 'name' => array(
+ 'title' => ts('Mailing Opt Out'),
+ 'description' => ts('FK to the opt-out component.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'subject' => array(
+ ],
+ ],
+ 'template_type' => [
+ 'name' => 'template_type',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Template Type'),
+ 'description' => ts('The language/processing system used for email templates.'),
+ 'required' => TRUE,
+ 'maxlength' => 64,
+ 'size' => CRM_Utils_Type::BIG,
+ 'default' => 'traditional',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'pseudoconstant' => [
+ 'callback' => 'CRM_Mailing_BAO_Mailing::getTemplateTypeNames',
+ ]
+ ],
+ 'template_options' => [
+ 'name' => 'template_options',
+ 'type' => CRM_Utils_Type::T_LONGTEXT,
+ 'title' => ts('Template Options (JSON)'),
+ 'description' => ts('Advanced options used by the email templating system. (JSON encoded)'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'body_html' => array(
+ 'title' => ts('Body Text'),
+ 'description' => ts('Body of the mailing in text format.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ 'body_html' => [
'name' => 'body_html',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Body Html') ,
- 'description' => 'Body of the mailing in html format.',
- ) ,
- 'url_tracking' => array(
+ 'title' => ts('Body Html'),
+ 'description' => ts('Body of the mailing in html format.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ '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?',
- 'html' => array(
+ 'title' => ts('Url Tracking'),
+ 'description' => ts('Should we track URL click-throughs for this mailing?'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Forward Replies'),
+ 'description' => ts('Should we forward replies back to the author?'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Auto Responder'),
+ 'description' => ts('Should we enable the auto-responder?'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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?',
- ) ,
- 'is_completed' => array(
+ 'title' => ts('Track Mailing?'),
+ 'description' => ts('Should we track when recipients open/read this mailing?'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ '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?',
- 'html' => array(
+ 'title' => ts('Mailing Completed'),
+ 'description' => ts('Has at least one job associated with this mailing finished?'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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.'),
+ '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',
- 'html' => array(
+ 'title' => ts('Override Verp'),
+ 'description' => ts('Should we overrite VERP address in Reply-To'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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'),
+ '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_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Created Date') ,
- 'description' => 'Date and time this mailing was created.',
- 'html' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Created Date'),
+ 'description' => ts('Date and time this mailing was created.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'scheduled_id' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ '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,
+ 'export' => TRUE,
+ 'where' => 'civicrm_mailing.modified_date',
+ 'headerPattern' => '',
+ 'dataPattern' => '',
+ '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'),
+ '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_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Scheduled Date') ,
- 'description' => 'Date and time this mailing was scheduled.',
- ) ,
- 'approver_id' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Scheduled Date'),
+ 'description' => ts('Date and time this mailing was scheduled.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ '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'),
+ '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_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Approved Date') ,
- 'description' => 'Date and time this mailing was approved.',
- ) ,
- 'approval_status_id' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Approved Date'),
+ 'description' => ts('Date and time this mailing was approved.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ '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',
- 'html' => array(
+ 'title' => ts('Approval Status'),
+ 'description' => ts('The status of this mailing. Values: none, approved, rejected'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Approval Note'),
+ 'description' => ts('Note behind the decision.'),
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Is Mailing Archived?'),
+ 'description' => ts('Is this mailing archived?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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,
'default' => 'Public Pages',
- 'html' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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.'),
+ '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?',
- 'html' => array(
+ 'title' => ts('No Duplicate emails?'),
+ 'description' => ts('Remove duplicate emails?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ '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'),
+ '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,
- ) ,
- 'location_type_id' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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,
'default' => 'automatic',
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::emailSelectMethods',
- )
- ) ,
- );
+ ]
+ ],
+ 'language' => [
+ 'name' => 'language',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Mailing Language'),
+ 'description' => ts('Language of the content of the mailing. Useful for tokens.'),
+ 'maxlength' => 5,
+ 'size' => CRM_Utils_Type::SIX,
+ 'table_name' => 'civicrm_mailing',
+ 'entity' => 'Mailing',
+ 'bao' => 'CRM_Mailing_BAO_Mailing',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ '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
*
@@ -712,10 +997,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
*
@@ -723,8 +1009,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 = [
+ 'index_hash' => [
+ 'name' => 'index_hash',
+ 'field' => [
+ 0 => 'hash',
+ ],
+ '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 fe9472719b43..9d4ac8bff0e0 100644
--- a/CRM/Mailing/DAO/MailingAB.php
+++ b/CRM/Mailing/DAO/MailingAB.php
@@ -1,301 +1,353 @@
__table = 'civicrm_mailing_abtest';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'name' => array(
+ 'title' => ts('MailingAB ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'status' => array(
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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,
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ '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)',
- ) ,
- 'mailing_id_b' => array(
+ 'title' => ts('Mailing ID (A)'),
+ 'description' => ts('The first experimental mailing ("A" condition)'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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)',
- ) ,
- 'mailing_id_c' => array(
+ 'title' => ts('Mailing ID (B)'),
+ 'description' => ts('The second experimental mailing ("B" condition)'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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)',
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Mailing ID (C)'),
+ 'description' => ts('The final, general mailing (derived from A or B)'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Domain ID') ,
- 'description' => 'Which site is this mailing for',
- ) ,
- 'testing_criteria' => array(
+ 'title' => ts('Domain ID'),
+ 'description' => ts('Which site is this mailing for'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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,
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ '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,
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'declare_winning_time' => array(
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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',
- ) ,
- 'group_percentage' => array(
+ 'title' => ts('Declaration Time'),
+ 'description' => ts('In how much time to declare winner'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ 'group_percentage' => [
'name' => 'group_percentage',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Percentage') ,
- ) ,
- 'created_id' => array(
+ 'title' => ts('Group Percentage'),
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('AB Test Created Date') ,
- 'description' => 'When was this item created',
- 'html' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('AB Test Created Date'),
+ 'description' => ts('When was this item created'),
+ 'required' => FALSE,
+ 'default' => 'CURRENT_TIMESTAMP',
+ 'table_name' => 'civicrm_mailing_abtest',
+ 'entity' => 'MailingAB',
+ 'bao' => 'CRM_Mailing_BAO_MailingAB',
+ 'localizable' => 0,
+ '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
*
@@ -303,10 +355,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
*
@@ -314,8 +367,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 = [];
+ 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..6f2ba81e3139
--- /dev/null
+++ b/CRM/Mailing/DAO/MailingComponent.php
@@ -0,0 +1,274 @@
+__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,
+ '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,
+ '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,
+ '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,
+ '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,
+ '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,
+ '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?'),
+ '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?'),
+ '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 854d5aac4085..46f6a4033371 100644
--- a/CRM/Mailing/DAO/MailingGroup.php
+++ b/CRM/Mailing/DAO/MailingGroup.php
@@ -1,218 +1,236 @@
__table = 'civicrm_mailing_group';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'mailing_id' => array(
+ 'title' => ts('Mailing Group ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_group',
+ 'entity' => 'MailingGroup',
+ 'bao' => 'CRM_Mailing_DAO_MailingGroup',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing_group',
+ 'entity' => 'MailingGroup',
+ 'bao' => 'CRM_Mailing_DAO_MailingGroup',
+ 'localizable' => 0,
+ '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,
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_mailing_group',
+ 'entity' => 'MailingGroup',
+ 'bao' => 'CRM_Mailing_DAO_MailingGroup',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'search_id' => array(
+ 'title' => ts('Mailing Group Entity'),
+ 'description' => ts('Foreign key to the referenced item.'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_group',
+ 'entity' => 'MailingGroup',
+ 'bao' => 'CRM_Mailing_DAO_MailingGroup',
+ 'localizable' => 0,
+ ],
+ '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',
- ) ,
- 'search_args' => array(
+ 'title' => ts('Mailing Group Search'),
+ 'description' => ts('The filtering search. custom search id or -1 for civicrm api search'),
+ 'table_name' => 'civicrm_mailing_group',
+ 'entity' => 'MailingGroup',
+ 'bao' => 'CRM_Mailing_DAO_MailingGroup',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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
*
@@ -220,10 +238,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
*
@@ -231,8 +250,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 = [];
+ 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 5d7b7f99787f..a88d4abcf64e 100644
--- a/CRM/Mailing/DAO/MailingJob.php
+++ b/CRM/Mailing/DAO/MailingJob.php
@@ -1,263 +1,310 @@
__table = 'civicrm_mailing_job';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'mailing_id' => array(
+ 'title' => ts('Mailing Job ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Scheduled Date') ,
- 'description' => 'date on which this job was scheduled.',
- ) ,
- 'start_date' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Scheduled Date'),
+ 'description' => ts('date on which this job was scheduled.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ 'start_date' => [
'name' => 'start_date',
- 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Job Start Date') ,
- 'description' => 'date on which this job was started.',
- ) ,
- 'end_date' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Job Start Date'),
+ 'description' => ts('date on which this job was started.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ 'end_date' => [
'name' => 'end_date',
- 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Mailing Job End Date') ,
- 'description' => 'date on which this job ended.',
- ) ,
- 'status' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Mailing Job End Date'),
+ 'description' => ts('date on which this job ended.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ '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?',
- ) ,
- 'job_type' => array(
+ 'title' => ts('Mailing Job Is Test?'),
+ 'description' => ts('Is this job for a test mail?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'parent_id' => array(
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ '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'),
'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',
- ) ,
- 'job_limit' => array(
+ 'title' => ts('Mailing Job Offset'),
+ 'description' => ts('Offset of the child job'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_mailing_job',
+ 'entity' => 'MailingJob',
+ 'bao' => 'CRM_Mailing_BAO_MailingJob',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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
*
@@ -265,10 +312,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
*
@@ -276,8 +324,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 = [];
+ 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 02e15d4fe6a6..3b10af904ae9 100644
--- a/CRM/Mailing/DAO/Recipients.php
+++ b/CRM/Mailing/DAO/Recipients.php
@@ -1,187 +1,195 @@
__table = 'civicrm_mailing_recipients';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'mailing_id' => array(
+ 'title' => ts('Mailing Recipients ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_recipients',
+ 'entity' => 'Recipients',
+ 'bao' => 'CRM_Mailing_BAO_Recipients',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
+ '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'),
'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'),
'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
*
@@ -189,10 +197,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
*
@@ -200,8 +209,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 = [];
+ 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 133b1b15db67..bdc28b428d04 100644
--- a/CRM/Mailing/DAO/Spool.php
+++ b/CRM/Mailing/DAO/Spool.php
@@ -1,202 +1,224 @@
__table = 'civicrm_mailing_spool';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'job_id' => array(
+ 'title' => ts('Spool ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_spool',
+ 'entity' => 'Spool',
+ 'bao' => 'CRM_Mailing_BAO_Spool',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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.',
- ) ,
- 'headers' => array(
+ 'title' => ts('Recipient Email'),
+ 'description' => ts('The email of the receipients this mail is to be sent.'),
+ 'table_name' => 'civicrm_mailing_spool',
+ 'entity' => 'Spool',
+ 'bao' => 'CRM_Mailing_BAO_Spool',
+ 'localizable' => 0,
+ ],
+ 'headers' => [
'name' => 'headers',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Headers') ,
- 'description' => 'The header information of this mailing .',
- ) ,
- 'body' => array(
+ 'title' => ts('Headers'),
+ 'description' => ts('The header information of this mailing .'),
+ 'table_name' => 'civicrm_mailing_spool',
+ 'entity' => 'Spool',
+ 'bao' => 'CRM_Mailing_BAO_Spool',
+ 'localizable' => 0,
+ ],
+ 'body' => [
'name' => 'body',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Body') ,
- 'description' => 'The body of this mailing.',
- ) ,
- 'added_at' => array(
+ 'title' => ts('Body'),
+ 'description' => ts('The body of this mailing.'),
+ 'table_name' => 'civicrm_mailing_spool',
+ 'entity' => 'Spool',
+ 'bao' => 'CRM_Mailing_BAO_Spool',
+ 'localizable' => 0,
+ ],
+ 'added_at' => [
'name' => 'added_at',
- 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Added') ,
- 'description' => 'date on which this job was added.',
- ) ,
- 'removed_at' => array(
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Added'),
+ 'description' => ts('date on which this job was added.'),
+ 'required' => FALSE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_mailing_spool',
+ 'entity' => 'Spool',
+ 'bao' => 'CRM_Mailing_BAO_Spool',
+ 'localizable' => 0,
+ ],
+ 'removed_at' => [
'name' => 'removed_at',
- 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Removed') ,
- 'description' => 'date on which this job was removed.',
- ) ,
- );
+ 'type' => CRM_Utils_Type::T_TIMESTAMP,
+ 'title' => ts('Removed'),
+ 'description' => ts('date on which this job was removed.'),
+ 'required' => FALSE,
+ '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
*
@@ -204,10 +226,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
*
@@ -215,8 +238,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 = [];
+ 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 1a48f4922237..840f42c6b3d3 100644
--- a/CRM/Mailing/DAO/TrackableURL.php
+++ b/CRM/Mailing/DAO/TrackableURL.php
@@ -1,155 +1,153 @@
__table = 'civicrm_mailing_trackable_url';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'url' => array(
+ 'title' => ts('Trackable URL ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_trackable_url',
+ 'entity' => 'TrackableURL',
+ 'bao' => 'CRM_Mailing_BAO_TrackableURL',
+ 'localizable' => 0,
+ ],
+ 'url' => [
'name' => 'url',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Url') ,
- 'description' => 'The URL to be tracked.',
- 'required' => true,
- ) ,
- 'mailing_id' => array(
+ 'title' => ts('Url'),
+ 'description' => ts('The URL to be tracked.'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_mailing_trackable_url',
+ 'entity' => 'TrackableURL',
+ 'bao' => 'CRM_Mailing_BAO_TrackableURL',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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
*
@@ -157,10 +155,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
*
@@ -168,8 +167,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 = [];
+ 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 fc050f48ce88..9a162c83dea1 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,50 +77,27 @@ 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'] = substr($params['bounce_reason'], 0, 254);
+ $params['bounce_reason'] = mb_strcut($params['bounce_reason'], 0, 254);
$bounce->copyValues($params);
$bounce->save();
- $success = TRUE;
- $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
- $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
- $emailTable = CRM_Core_BAO_Email::getTableName();
- $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
+ CRM_Utils_Hook::post($action, 'MailingEventBounce', $bounce->id, $bounce);
- $bounce->reset();
- // might want to put distinct inside the count
- $query = "SELECT count($bounceTable.id) as bounces,
- $bounceType.hold_threshold as threshold
- FROM $bounceTable
- INNER JOIN $bounceType
- ON $bounceTable.bounce_type_id = $bounceType.id
- INNER JOIN $queueTable
- ON $bounceTable.event_queue_id = $queueTable.id
- INNER JOIN $emailTable
- ON $queueTable.email_id = $emailTable.id
- WHERE $emailTable.id = {$q->email_id}
- AND ($emailTable.reset_date IS NULL
- OR $bounceTable.time_stamp >= $emailTable.reset_date)
- GROUP BY $bounceTable.bounce_type_id
- ORDER BY threshold, bounces desc";
-
- $bounce->query($query);
-
- while ($bounce->fetch()) {
- if ($bounce->bounces >= $bounce->threshold) {
- $email = new CRM_Core_BAO_Email();
- $email->id = $q->email_id;
- $email->on_hold = TRUE;
- $email->hold_date = date('YmdHis');
- $email->save();
- break;
- }
+ if ($q->email_id) {
+ self::putEmailOnHold($q->email_id);
}
$transaction->commit();
- return $success;
+ return TRUE;
}
/**
@@ -238,7 +218,7 @@ public static function &getRows(
}
if ($is_distinct) {
- $query .= " GROUP BY $queue.id ";
+ $query .= " GROUP BY $queue.id, $bounce.time_stamp, $bounce.bounce_reason, $bounceType.name ";
}
$orderBy = "sort_name ASC, {$bounce}.time_stamp DESC";
@@ -279,4 +259,46 @@ public static function &getRows(
return $results;
}
+ /**
+ * Put the email on hold if it has met the threshold.
+ *
+ * @param int $email_id
+ */
+ protected static function putEmailOnHold($email_id) {
+
+ $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
+ $bounceType = CRM_Mailing_DAO_BounceType::getTableName();
+ $emailTable = CRM_Core_BAO_Email::getTableName();
+ $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
+
+ // might want to put distinct inside the count
+ $query = "SELECT count($bounceTable.id) as bounces,
+ $bounceType.hold_threshold as threshold
+ FROM $bounceTable
+ INNER JOIN $bounceType
+ ON $bounceTable.bounce_type_id = $bounceType.id
+ INNER JOIN $queueTable
+ ON $bounceTable.event_queue_id = $queueTable.id
+ INNER JOIN $emailTable
+ ON $queueTable.email_id = $emailTable.id
+ WHERE $emailTable.id = $email_id
+ AND ($emailTable.reset_date IS NULL
+ OR $bounceTable.time_stamp >= $emailTable.reset_date)
+ GROUP BY $bounceTable.bounce_type_id
+ ORDER BY threshold, bounces desc";
+
+ $dao = CRM_Core_DAO::executeQuery($query);
+
+ while ($dao->fetch()) {
+ if ($dao->bounces >= $dao->threshold) {
+ $email = new CRM_Core_BAO_Email();
+ $email->id = $email_id;
+ $email->on_hold = TRUE;
+ $email->hold_date = date('YmdHis');
+ $email->save();
+ break;
+ }
+ }
+ }
+
}
diff --git a/CRM/Mailing/Event/BAO/Confirm.php b/CRM/Mailing/Event/BAO/Confirm.php
index b190586ead79..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 42ba73ceef7f..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 8e2d79b5e47c..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' => 'Opt Out',
+ '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 ad434b966a0e..d2d6af941ea9 100644
--- a/CRM/Mailing/Form/Search.php
+++ b/CRM/Mailing/Form/Search.php
@@ -1,9 +1,9 @@
addElement('checkbox', 'status_unscheduled', NULL, ts('Draft / Unscheduled'));
$this->addYesNo('is_archived', ts('Mailing is Archived'), TRUE);
+ // Search by language, if multi-lingual
+ $enabledLanguages = CRM_Core_I18n::languages(TRUE);
+
+ if (count($enabledLanguages) > 1) {
+ $this->addElement('select', 'language', ts('Language'), ['' => ts('- all languages -')] + $enabledLanguages, ['class' => 'crm-select2']);
+ }
+
if ($parent->_sms) {
$this->addElement('hidden', 'sms', $parent->_sms);
}
$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')) {
@@ -108,7 +115,7 @@ public function postProcess() {
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array(
+ $fields = [
'mailing_name',
'mailing_from',
'mailing_to',
@@ -118,17 +125,17 @@ public function postProcess() {
'sms',
'status_unscheduled',
'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"]
- ) {
+ if (in_array($field, [
+ 'mailing_from',
+ 'mailing_to',
+ ]) && !$params["mailing_relative"]) {
$time = ($field == 'mailing_to') ? '235959' : NULL;
$parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
}
diff --git a/CRM/Mailing/Form/Subscribe.php b/CRM/Mailing/Form/Subscribe.php
index c4d89c3cdbf7..6a8feae66b2e 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;
@@ -153,18 +153,17 @@ public function buildQuickForm() {
$this->assign('isCaptcha', TRUE);
}
- $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 +177,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 4d53fd3cd6ff..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 454cad702aa1..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' => ['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 c21fa2e1456e..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 21ee4e734284..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' => 'Unsubscribe',
+ '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 1fdd0e27b12c..a674129e54aa 100644
--- a/CRM/Mailing/Info.php
+++ b/CRM/Mailing/Info.php
@@ -1,9 +1,9 @@
'CiviMail',
'translatedName' => ts('CiviMail'),
- 'title' => 'CiviCRM Mailing Engine',
+ 'title' => ts('CiviCRM Mailing Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -69,123 +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(
- 'civiMails' => $civiMails['values'],
+ ->addSetting([
+ 'crmMailing' => [
+ 'templateTypes' => CRM_Mailing_BAO_Mailing::getTemplateTypes(),
+ '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,
- ),
- ))
- ->addPermissions(array(
+ 'enabledLanguages' => $enabledLanguages,
+ 'isMultiLingual' => $isMultiLingual,
+ ],
+ ])
+ ->addPermissions([
'view all contacts',
'edit all contacts',
'access CiviMail',
@@ -194,7 +170,7 @@ public function getAngularModules() {
'approve mailings',
'delete in CiviMail',
'edit message templates',
- ));
+ ]);
return $result;
}
@@ -232,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) {
@@ -270,7 +246,6 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
return $permissions;
}
-
/**
* @inheritDoc
* @return null
@@ -293,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';
}
/**
@@ -306,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 1d9361fa19dc..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 129ca04e521f..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 fc5b69a78abf..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 9e62c511b83c..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 28124766f105..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 df5a9d8940ff..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 80df5a15c7c2..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 14dc2c135024..65bf2de542df 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)) {
@@ -255,15 +288,15 @@ public function run() {
CRM_Utils_System::setTitle(ts('Find Mass SMS'));
}
- $crmRowCount = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject);
- $crmPID = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
+ $crmRowCount = CRM_Utils_Request::retrieve('crmRowCount', 'Integer');
+ $crmPID = CRM_Utils_Request::retrieve('crmPID', 'Integer');
if ($crmRowCount || $crmPID) {
$urlParams .= '&force=1';
$urlParams .= $crmRowCount ? '&crmRowCount=' . $crmRowCount : '';
$urlParams .= $crmPID ? '&crmPID=' . $crmPID : '';
}
- $crmSID = CRM_Utils_Request::retrieve('crmSID', 'Integer', CRM_Core_DAO::$_nullObject);
+ $crmSID = CRM_Utils_Request::retrieve('crmSID', 'Integer');
if ($crmSID) {
$urlParams .= '&crmSID=' . $crmSID;
}
@@ -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 4260ad501d2d..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 e0b29749fd86..b126dac4281f 100644
--- a/CRM/Mailing/Page/Confirm.php
+++ b/CRM/Mailing/Page/Confirm.php
@@ -1,9 +1,9 @@
');
- $contact_id = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject);
- $subscribe_id = CRM_Utils_Request::retrieve('sid', 'Integer', CRM_Core_DAO::$_nullObject);
- $hash = CRM_Utils_Request::retrieve('h', 'String', CRM_Core_DAO::$_nullObject);
+ $contact_id = CRM_Utils_Request::retrieve('cid', 'Integer');
+ $subscribe_id = CRM_Utils_Request::retrieve('sid', 'Integer');
+ $hash = CRM_Utils_Request::retrieve('h', 'String');
if (!$contact_id ||
!$subscribe_id ||
diff --git a/CRM/Mailing/Page/Event.php b/CRM/Mailing/Page/Event.php
index 8bc84bb94b7d..762e015d359c 100644
--- a/CRM/Mailing/Page/Event.php
+++ b/CRM/Mailing/Page/Event.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 d5966d34cb83..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 83be7a1bd422..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 890595eddbeb..34da7195d930 100644
--- a/CRM/Mailing/Page/Unsubscribe.php
+++ b/CRM/Mailing/Page/Unsubscribe.php
@@ -1,9 +1,9 @@
_contactID = $contactID;
}
else {
- $this->_contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
+ $this->_contactID = CRM_Core_Session::getLoggedInContactID();
}
// mailing key check
@@ -132,59 +138,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);
}
}
@@ -221,17 +229,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',
@@ -244,7 +252,7 @@ public static function convertDayFormat(&$membershipType) {
'10' => 'Oct',
'11' => 'Nov',
'12' => 'Dec',
- );
+ ];
$membershipType[$id][$pDay] = $monthMap[$month] . ' ' . $day;
}
else {
@@ -263,7 +271,7 @@ public static function convertDayFormat(&$membershipType) {
* @return array
*/
public static function getMembershipTypes($public = TRUE) {
- $membershipTypes = array();
+ $membershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
$membershipType->is_active = 1;
if ($public) {
@@ -274,7 +282,6 @@ public static function getMembershipTypes($public = TRUE) {
while ($membershipType->fetch()) {
$membershipTypes[$membershipType->id] = $membershipType->name;
}
- $membershipType->free();
return $membershipTypes;
}
@@ -286,14 +293,13 @@ public static function getMembershipTypes($public = TRUE) {
* @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 {
@@ -321,11 +327,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');
}
@@ -433,11 +439,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;
}
@@ -454,7 +460,7 @@ public static function getDatesForMembershipType($membershipTypeId, $joinDate =
* @param string $actualStartDate
* @return bool is this in the window where the membership gets an extra part-period added
*/
- protected static function isDuringFixedAnnualRolloverPeriod($startDate, $membershipTypeDetails, $year, $actualStartDate) {
+ public static function isDuringFixedAnnualRolloverPeriod($startDate, $membershipTypeDetails, $year, $actualStartDate) {
$rolloverMonth = substr($membershipTypeDetails['fixed_period_rollover_day'], 0,
strlen($membershipTypeDetails['fixed_period_rollover_day']) - 2
@@ -500,6 +506,7 @@ protected static function isDuringFixedAnnualRolloverPeriod($startDate, $members
*
* @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
@@ -511,11 +518,11 @@ protected static function isDuringFixedAnnualRolloverPeriod($startDate, $members
* 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');
}
@@ -543,6 +550,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),
@@ -604,6 +613,10 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
$membershipDates['start_date'] = $renewalDates['start_date'];
$membershipDates['end_date'] = $renewalDates['end_date'];
$membershipDates['log_start_date'] = $renewalDates['start_date'];
+ // CRM-18503 - set join_date as today in case the membership type is fixed.
+ if ($membershipTypeDetails['period_type'] == 'fixed' && !isset($membershipDates['join_date'])) {
+ $membershipDates['join_date'] = $renewalDates['join_date'];
+ }
}
if (!isset($membershipDates['join_date'])) {
$membershipDates['join_date'] = $membershipDates['start_date'];
@@ -613,8 +626,8 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
}
/**
- * Retrieve all Membership Types associated.
- * with an Organization
+ * @deprecated Please use the Membership API
+ * Retrieve all Membership Types associated with an Organization
*
* @param int $orgID
* Id of Organization.
@@ -623,15 +636,14 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
* 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;
+ CRM_Core_Error::deprecatedFunctionWarning('membership_type api');
+ $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
+ 'member_of_contact_id' => $orgID,
+ 'options' => [
+ 'limit' => 0,
+ ],
+ ]);
+ return CRM_Utils_Array::value('values', $memberTypesSameParentOrg, []);
}
/**
@@ -643,7 +655,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;
}
@@ -664,7 +676,7 @@ public static function getMemberOfContactByMemTypes($membershipTypes) {
* @return array
*/
public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
- $allMembershipTypes = array();
+ $allMembershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
@@ -689,7 +701,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
@@ -700,12 +712,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
@@ -723,14 +734,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;
@@ -752,11 +763,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'];
@@ -764,14 +775,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) {
@@ -795,41 +806,39 @@ 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);
}
}
diff --git a/CRM/Member/BAO/Query.php b/CRM/Member/BAO/Query.php
index 7fb821ccb47f..3294569e6c52 100644
--- a/CRM/Member/BAO/Query.php
+++ b/CRM/Member/BAO/Query.php
@@ -1,9 +1,9 @@
_whereTables['civicrm_membership_status'] = 1;
}
+ if (!empty($query->_returnProperties['membership_is_current_member'])) {
+ $query->_select['is_current_member'] = "civicrm_membership_status.is_current_member as is_current_member";
+ $query->_element['is_current_member'] = 1;
+ $query->_tables['civicrm_membership_status'] = 1;
+ $query->_whereTables['civicrm_membership_status'] = 1;
+ }
+
if (!empty($query->_returnProperties['membership_status_id'])) {
$query->_select['status_id'] = "civicrm_membership_status.id as status_id";
$query->_element['status_id'] = 1;
@@ -164,18 +171,22 @@ public static function whereClauseSingle(&$values, &$query) {
);
return;
+ case 'membership_start_date':
case 'member_start_date_low':
case 'member_start_date_high':
+ $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':
+ $fldName = str_replace(['_low', '_high'], '', $name);
$query->dateQueryBuilder($values,
- 'civicrm_membership', 'member_end_date', 'end_date',
+ 'civicrm_membership', $fldName, 'end_date',
'End Date'
);
return;
@@ -186,7 +197,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;
@@ -197,7 +208,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;
@@ -219,10 +230,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) {
@@ -251,6 +263,13 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
return;
+ case 'membership_is_current_member':
+ // We don't want to include all tests for sql OR CRM-7827
+ $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership_status.is_current_member", $op, $value, "Boolean");
+ $query->_qill[$grouping][] = $value ? ts('Is a current member') : ts('Is a non-current member');
+ $query->_tables['civicrm_membership_status'] = $query->_whereTables['civicrm_membership_status'] = 1;
+ return;
+
case 'member_test':
// We don't want to include all tests for sql OR CRM-7827
if (!$value || $query->getOperator() != 'OR') {
@@ -264,7 +283,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';
@@ -416,7 +435,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,
@@ -436,7 +455,7 @@ public static function defaultReturnProperties(
'member_campaign_id' => 1,
'member_is_override' => 1,
'member_auto_renew' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom membership properties
@@ -459,20 +478,21 @@ public static function defaultReturnProperties(
*/
public static function buildSearchForm(&$form) {
$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'), ['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');
@@ -483,54 +503,34 @@ public static function buildSearchForm(&$form) {
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->addFormRule(['CRM_Member_BAO_Query', 'formRule'], $form);
+ $form->addYesNo('membership_is_current_member', ts('Current Member?'), TRUE);
$form->addYesNo('member_is_primary', ts('Primary Member?'), TRUE);
$form->addYesNo('member_pay_later', ts('Pay Later?'), TRUE);
$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);
- // add all the custom searchable fields
- $extends = array('Membership');
- $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
- if ($groupDetails) {
- $form->assign('membershipGroupTree', $groupDetails);
- foreach ($groupDetails as $group) {
- foreach ($group['fields'] as $field) {
- $fieldId = $field['id'];
- $elementName = 'custom_' . $fieldId;
- CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
- }
- }
- }
+ self::addCustomFormFields($form, ['Membership']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'member_campaign_id');
$form->assign('validCiviMember', TRUE);
- $form->setDefaults(array('member_test' => 0));
- }
-
- /**
- * Possibly un-required function.
- *
- * @param array $row
- * @param int $id
- */
- public static function searchAction(&$row, $id) {
+ $form->setDefaults(['member_test' => 0]);
}
/**
@@ -540,7 +540,7 @@ public static function searchAction(&$row, $id) {
*/
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);
+ $tables = array_merge(['civicrm_membership' => 1], $tables);
}
}
@@ -554,7 +554,7 @@ public static function tableNames(&$tables) {
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
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;
diff --git a/CRM/Member/Controller/Search.php b/CRM/Member/Controller/Search.php
index 46b46a4f6dc5..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
+ * 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,
- ) ,
- 'membership_contact_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ ],
+ '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(
+ ]
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'membership_start_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'membership_end_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'membership_source' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ '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(
+ ]
+ ],
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ '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',
+ 'headerPattern' => '',
+ 'dataPattern' => '',
+ '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.'),
+ 'export' => TRUE,
'where' => 'civicrm_membership.owner_membership_id',
'headerPattern' => '',
'dataPattern' => '',
+ '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).',
- 'html' => array(
+ 'title' => ts('Max Related'),
+ 'description' => ts('Maximum number of related memberships (membership_type override).'),
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'contribution_recur_id' => array(
+ ],
+ ],
+ 'contribution_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.'),
+ '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
*
@@ -425,10 +512,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
*
@@ -436,8 +524,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 = [
+ 'index_owner_membership_id' => [
+ 'name' => 'index_owner_membership_id',
+ 'field' => [
+ 0 => 'owner_membership_id',
+ ],
+ '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 a2fa788a1608..0b533176c33d 100644
--- a/CRM/Member/DAO/MembershipBlock.php
+++ b/CRM/Member/DAO/MembershipBlock.php
@@ -1,289 +1,340 @@
__table = 'civicrm_membership_block';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Membership Block ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- ) ,
- 'membership_type_default' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ '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'),
+ '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'),
'default' => '1',
- ) ,
- 'is_separate_payment' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => '1',
- ) ,
- 'new_title' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'new_text' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 1,
+ ],
+ 'new_text' => [
'name' => 'new_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block New Text') ,
- 'description' => 'Text to display below title',
- ) ,
- 'renewal_title' => array(
+ 'title' => ts('Membership Block New Text'),
+ 'description' => ts('Text to display below title'),
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 1,
+ ],
+ '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,
- ) ,
- 'renewal_text' => array(
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 1,
+ ],
+ 'renewal_text' => [
'name' => 'renewal_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block Renewal Text') ,
- 'description' => 'Text to display for member renewal',
- ) ,
- 'is_required' => array(
+ 'title' => ts('Membership Block Renewal Text'),
+ 'description' => ts('Text to display for member renewal'),
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 1,
+ ],
+ 'is_required' => [
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Required') ,
- 'description' => 'Is membership sign up optional',
- ) ,
- 'is_active' => array(
+ 'title' => ts('Is Required'),
+ 'description' => ts('Is membership sign up optional'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_membership_block',
+ 'entity' => 'MembershipBlock',
+ 'bao' => 'CRM_Member_BAO_MembershipBlock',
+ 'localizable' => 0,
+ ],
+ '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'),
'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
*
@@ -291,10 +342,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
*
@@ -302,8 +354,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 = [];
+ 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 f1a4f443e12c..306cd2064772 100644
--- a/CRM/Member/DAO/MembershipLog.php
+++ b/CRM/Member/DAO/MembershipLog.php
@@ -1,233 +1,261 @@
__table = 'civicrm_membership_log';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'membership_id' => array(
+ 'title' => ts('Membership Log ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_membership_log',
+ 'entity' => 'MembershipLog',
+ 'bao' => 'CRM_Member_BAO_MembershipLog',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
+ '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',
- ) ,
- 'end_date' => array(
+ 'title' => ts('Membership Log Start Date'),
+ 'description' => ts('New membership period start date'),
+ 'table_name' => 'civicrm_membership_log',
+ 'entity' => 'MembershipLog',
+ 'bao' => 'CRM_Member_BAO_MembershipLog',
+ 'localizable' => 0,
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Log End Date') ,
- 'description' => 'New membership period expiration date.',
- ) ,
- 'modified_id' => array(
+ 'title' => ts('Membership Log End Date'),
+ 'description' => ts('New membership period expiration date.'),
+ 'table_name' => 'civicrm_membership_log',
+ 'entity' => 'MembershipLog',
+ 'bao' => 'CRM_Member_BAO_MembershipLog',
+ 'localizable' => 0,
+ ],
+ '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.'),
+ '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.',
- ) ,
- 'membership_type_id' => array(
+ 'title' => ts('Membership Change Date'),
+ 'description' => ts('Date this membership modification action was logged.'),
+ 'table_name' => 'civicrm_membership_log',
+ 'entity' => 'MembershipLog',
+ 'bao' => 'CRM_Member_BAO_MembershipLog',
+ 'localizable' => 0,
+ ],
+ '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.'),
+ '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.'),
+ '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
*
@@ -235,10 +263,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
*
@@ -246,8 +275,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 = [];
+ 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 ed5546282e49..e1b4c7abe95a 100644
--- a/CRM/Member/DAO/MembershipPayment.php
+++ b/CRM/Member/DAO/MembershipPayment.php
@@ -1,156 +1,154 @@
__table = 'civicrm_membership_payment';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'membership_id' => array(
+ 'title' => ts('Membership Payment ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_membership_payment',
+ 'entity' => 'MembershipPayment',
+ 'bao' => 'CRM_Member_BAO_MembershipPayment',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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.'),
+ '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
*
@@ -158,10 +156,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
*
@@ -169,8 +168,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 = [
+ 'UI_contribution_membership' => [
+ 'name' => 'UI_contribution_membership',
+ 'field' => [
+ 0 => 'contribution_id',
+ 1 => 'membership_id',
+ ],
+ '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 7e72a3c16fcd..03d9b33b3081 100644
--- a/CRM/Member/DAO/MembershipStatus.php
+++ b/CRM/Member/DAO/MembershipStatus.php
@@ -1,324 +1,397 @@
__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,
- ) ,
- 'membership_status' => array(
+ 'title' => ts('Membership Status ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'label' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'start_event' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'end_event' => array(
+ 'title' => ts('Start Event Adjust Interval'),
+ 'description' => ts('Status range begins this many units from start_event.'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'is_current_member' => array(
+ 'title' => ts('End Event Adjust Interval'),
+ 'description' => ts('Status range ends this many units from end_event.'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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).',
- ) ,
- 'is_admin' => array(
+ '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).'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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.',
- ) ,
- 'weight' => array(
+ 'title' => ts('Administrator Only?'),
+ 'description' => ts('Is this status for admin/manual assignment only.'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- ) ,
- 'is_default' => array(
+ 'title' => ts('Order'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ ],
+ '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.',
- ) ,
- 'is_active' => array(
+ 'title' => ts('Default Status?'),
+ 'description' => ts('Assign this status to a membership record if no other status match is found.'),
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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.'),
'default' => '1',
- ) ,
- 'is_reserved' => array(
+ 'table_name' => 'civicrm_membership_status',
+ 'entity' => 'MembershipStatus',
+ 'bao' => 'CRM_Member_BAO_MembershipStatus',
+ 'localizable' => 0,
+ '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.'),
+ '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
*
@@ -326,10 +399,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
*
@@ -337,8 +411,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 = [];
+ 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 5e0f5d0b2d9e..e2f99222f0df 100644
--- a/CRM/Member/DAO/MembershipType.php
+++ b/CRM/Member/DAO/MembershipType.php
@@ -1,437 +1,554 @@
__table = 'civicrm_membership_type';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Membership Type ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- ) ,
- 'description' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 1,
+ '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,
+ '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,
+ '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
- ) ,
- ) ,
- 'duration_unit' => array(
+ 'title' => ts('Membership Type Minimum Fee'),
+ 'description' => ts('Minimum fee for this membership (0 for free/complimentary memberships).'),
+ 'precision' => [
+ 18,
+ 9
+ ],
+ 'default' => '0',
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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).',
- ) ,
- 'period_type' => array(
+ 'title' => ts('Membership Type Duration Interval'),
+ 'description' => ts('Number of duration units in membership period (e.g. 1 year, 12 months).'),
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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,
- 'pseudoconstant' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'fixed_period_rollover_day' => array(
+ '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.'),
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ ],
+ '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.',
- ) ,
- 'relationship_type_id' => array(
+ 'title' => ts('Fixed Period Rollover Day'),
+ 'description' => ts('For fixed period memberships, signups after this day (mmdd) rollover to next period.'),
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'relationship_direction' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'max_related' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Related Members for Type') ,
- 'description' => 'Maximum number of related memberships.',
- ) ,
- 'visibility' => array(
+ 'title' => ts('Max Related Members for Type'),
+ 'description' => ts('Maximum number of related memberships.'),
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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') ,
- ) ,
- 'receipt_text_signup' => array(
+ 'title' => ts('Order'),
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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;',
- 'pseudoconstant' => array(
+ 'title' => ts('Auto Renew'),
+ 'description' => ts('0 = No auto-renew option; 1 = Give option, but not required; 2 = Auto-renew required;'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_membership_type',
+ 'entity' => 'MembershipType',
+ 'bao' => 'CRM_Member_BAO_MembershipType',
+ 'localizable' => 0,
+ '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'),
'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
*
@@ -439,10 +556,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
*
@@ -450,8 +568,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 = [
+ 'index_relationship_type_id' => [
+ 'name' => 'index_relationship_type_id',
+ 'field' => [
+ 0 => 'relationship_type_id',
+ ],
+ '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 6c0e5eddf6b8..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.
if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
+ if (!CRM_Member_BAO_Membership::statusAvailabilty()) {
+ // all possible statuses are disabled - redirect back to contact form
+ CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
+ }
+
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;
@@ -124,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');
@@ -135,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) {
@@ -148,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;
}
@@ -155,15 +231,10 @@ 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}');")
- );
- CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE);
- }
+ $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.
if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
@@ -172,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();
@@ -184,53 +255,52 @@ public function buildQuickForm() {
ts('Membership renewed automatically')
);
- $this->assignPaymentRelatedVariables();
}
$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'),
- ),
- ));
+ ],
+ ]);
}
}
@@ -285,23 +355,19 @@ 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];
}
}
- if ($this->_mode) {
- $this->assignPaymentRelatedVariables();
- }
-
if ($this->_id) {
$this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
$this->_membershipIDs[] = $this->_id;
@@ -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']);
@@ -430,31 +496,13 @@ protected function setPriceSetParameters($formValues) {
return $formValues;
}
- /**
- * Assign billing name to the template.
- */
- protected function assignBillingName() {
- $name = '';
- if (!empty($this->_params['billing_first_name'])) {
- $name = $this->_params['billing_first_name'];
- }
-
- if (!empty($this->_params['billing_middle_name'])) {
- $name .= " {$this->_params['billing_middle_name']}";
- }
-
- if (!empty($this->_params['billing_last_name'])) {
- $name .= " {$this->_params['billing_last_name']}";
- }
- $this->assign('billingName', $name);
- }
-
/**
* Wrapper function for unit tests.
*
* @param array $formValues
*/
public function testSubmit($formValues) {
+ $this->setContextVariables($formValues);
$this->_memType = $formValues['membership_type_id'][1];
$this->_params = $formValues;
$this->submit();
diff --git a/CRM/Member/Form/Membership.php b/CRM/Member/Form/Membership.php
index 194fe67801f9..ec39152a4418 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)) {
@@ -1867,4 +1913,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 d29cc9b7dabb..83df3d77a151 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,23 @@ 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));
$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 +225,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 +281,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 +343,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 +392,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 +415,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 +470,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 ff2d804c1306..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 1de8b075d747..096e45e65254 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.
@@ -129,10 +134,6 @@ public function preProcess() {
// This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
$this->assign('formClass', 'membershiprenew');
parent::preProcess();
- // check for edit permission
- if (!CRM_Core_Permission::check('edit memberships')) {
- CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
- }
$this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$this->_id, 'end_date'
@@ -180,13 +181,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',
@@ -196,19 +195,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
@@ -229,9 +215,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));
@@ -249,19 +233,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();
@@ -290,19 +275,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']];
@@ -329,49 +315,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'),
@@ -383,7 +369,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);
@@ -408,10 +394,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]);
}
/**
@@ -419,12 +405,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.');
}
@@ -432,6 +420,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'])) {
@@ -458,24 +459,24 @@ public function postProcess() {
try {
$this->submit();
- $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
+ $statusMsg = ts('%1 membership for %2 has been renewed.', [1 => $this->membershipTypeName, 2 => $this->_memberDisplayName]);
if ($this->endDate) {
- $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(
+ $statusMsg .= ' ' . ts('The new membership End Date is %1.', [
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(
+ $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', [
1 => $this->_contributorEmail,
- ));
+ ]);
return $statusMsg;
}
return $statusMsg;
}
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}"
));
@@ -493,8 +494,7 @@ 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,
@@ -556,13 +556,12 @@ protected function submit() {
$this->_params['contribution_status_id'] = $result['payment_status_id'];
$this->_params['trxn_id'] = $result['trxn_id'];
- $this->_params['payment_instrument_id'] = 1;
$this->_params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
$this->set('params', $this->_params);
$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');
@@ -579,7 +578,7 @@ protected function submit() {
$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'])) {
@@ -588,7 +587,7 @@ protected function submit() {
$isPending = ($this->_params['contribution_status_id'] == 2) ? TRUE : FALSE;
- list($renewMembership) = CRM_Member_BAO_Membership::renewMembership(
+ list($membership) = CRM_Member_BAO_Membership::processMembership(
$this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
$renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
$isPending,
@@ -596,9 +595,9 @@ protected function submit() {
$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) {
@@ -606,7 +605,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
@@ -629,10 +628,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;
@@ -640,10 +639,14 @@ 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']);
+ }
CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
}
@@ -656,10 +659,10 @@ protected function submit() {
$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);
+ $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->_id, FALSE, $this->_memType);
// retrieve custom data
- $customFields = $customValues = $fo = array();
+ $customFields = $customValues = $fo = [];
foreach ($this->_groupTree as $groupID => $group) {
if ($groupID == 'info') {
continue;
@@ -669,10 +672,10 @@ protected function submit() {
$customFields["custom_{$k}"] = $field;
}
}
- $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
+ $members = [['member_id', '=', $this->_membershipId, 0, 0]];
// check whether its a test drive
if ($this->_mode == 'test') {
- $members[] = array('member_test', '=', 1, 0, 0);
+ $members[] = ['member_test', '=', 1, 0, 0];
}
CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
@@ -682,28 +685,16 @@ protected function submit() {
}
$this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
- $renewMembership->membership_type_id
+ $membership->membership_type_id
));
$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));
+ $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) {
- // assign the address formatted up for display
- $addressParts = array(
- "street_address-{$this->_bltID}",
- "city-{$this->_bltID}",
- "postal_code-{$this->_bltID}",
- "state_province-{$this->_bltID}",
- "country-{$this->_bltID}",
- );
- $addressFields = array();
- foreach ($addressParts as $part) {
- list($n) = explode('-', $part);
- if (isset($this->_params['billing_' . $part])) {
- $addressFields[$n] = $this->_params['billing_' . $part];
- }
- }
- $this->assign('address', CRM_Utils_Address::format($addressFields));
+ $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);
@@ -715,7 +706,7 @@ protected function submit() {
}
list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_membership',
'valueName' => 'membership_offline_receipt',
'contactId' => $this->_receiptContactId,
@@ -723,7 +714,7 @@ protected function submit() {
'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 909a637ab7be..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 baee601fb3bc..3e1c01588ee3 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,34 +293,29 @@ 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')) {
+ $deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
+ $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
+ }
}
/**
@@ -216,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.');
@@ -230,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')
) {
@@ -250,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'];
@@ -282,21 +394,12 @@ public static function formRule($params) {
}
}
- // CRM-16189
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($params['financial_type_id']);
- }
- catch (CRM_Core_Exception $e) {
- $errors['financial_type_id'] = $e->getMessage();
- }
-
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*
- *
* @return void
*/
public function postProcess() {
@@ -310,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 &&
@@ -363,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' &&
@@ -372,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;
@@ -401,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')
@@ -426,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 2c1f935f958c..05520fb1d342 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,13 @@ 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(
+ $ids = [];
+ $params = [
'contact_id' => CRM_Utils_Request::retrieve('rid', 'Positive', $this),
'membership_type_id' => $owner['membership_type_id'],
'owner_membership_id' => $owner['id'],
@@ -122,10 +135,10 @@ public function relAction($action, $owner) {
'status_id' => $owner['status_id'],
'skipStatusCal' => TRUE,
'createActivity' => TRUE,
- );
+ ];
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 +161,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 +194,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 +255,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 +272,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 +281,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 +294,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 +319,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 +340,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 +365,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 +387,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 +419,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 7e99b2ba139d..8eba67bfa9c7 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
@@ -153,7 +142,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Member_BAO_Query::buildSearchForm($this);
@@ -163,9 +152,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 +179,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.
*
@@ -296,26 +313,20 @@ public function fixFormValues() {
return;
}
- $status = CRM_Utils_Request::retrieve('status', 'String',
- CRM_Core_DAO::$_nullObject
- );
+ $status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
$status = explode(',', $status);
$this->_formValues['membership_status_id'] = $this->_defaults['membership_status_id'] = (array) $status;
}
- $membershipType = CRM_Utils_Request::retrieve('type', 'String',
- CRM_Core_DAO::$_nullObject
- );
+ $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',
- CRM_Core_DAO::$_nullObject
- );
+ $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
if ($cid) {
$cid = CRM_Utils_Type::escape($cid, 'Integer');
@@ -330,32 +341,24 @@ public function fixFormValues() {
}
}
- $fromDate = CRM_Utils_Request::retrieve('start', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $fromDate = CRM_Utils_Request::retrieve('start', 'Date');
if ($fromDate) {
list($date) = CRM_Utils_Date::setDateDefaults($fromDate);
$this->_formValues['member_start_date_low'] = $this->_defaults['member_start_date_low'] = $date;
}
- $toDate = CRM_Utils_Request::retrieve('end', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $toDate = CRM_Utils_Request::retrieve('end', 'Date');
if ($toDate) {
list($date) = CRM_Utils_Date::setDateDefaults($toDate);
$this->_formValues['member_start_date_high'] = $this->_defaults['member_start_date_high'] = $date;
}
- $joinDate = CRM_Utils_Request::retrieve('join', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $joinDate = CRM_Utils_Request::retrieve('join', 'Date');
if ($joinDate) {
list($date) = CRM_Utils_Date::setDateDefaults($joinDate);
$this->_formValues['member_join_date_low'] = $this->_defaults['member_join_date_low'] = $date;
}
- $joinEndDate = CRM_Utils_Request::retrieve('joinEnd', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $joinEndDate = CRM_Utils_Request::retrieve('joinEnd', 'Date');
if ($joinEndDate) {
list($date) = CRM_Utils_Date::setDateDefaults($joinEndDate);
$this->_formValues['member_join_date_high'] = $this->_defaults['member_join_date_high'] = $date;
@@ -366,9 +369,9 @@ public function fixFormValues() {
);
//LCD also allow restrictions to membership owner via GET
- $owner = CRM_Utils_Request::retrieve('owner', 'String', CRM_Core_DAO::$_nullObject);
- if ($owner) {
- $this->_formValues['member_is_primary'] = $this->_defaults['member_is_primary'] = 2;
+ $owner = CRM_Utils_Request::retrieve('owner', 'String');
+ 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 d8917a61dbdb..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 d7ffb0409f13..99d6af35a4e6 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,25 +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);
- $fileFieldExists = FALSE;
//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',
@@ -151,6 +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 = [];
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,9 +192,8 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_memberIds as $memberId) {
- $details[$memberId] = array();
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $memberId, 'Membership');
}
@@ -209,13 +208,16 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
- $dates = array(
+ // @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 = [
'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 64fb88b21b00..a6cbf2235b9b 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 ed2197d2e722..be38db71a038 100644
--- a/CRM/Member/Form/Task/Email.php
+++ b/CRM/Member/Form/Task/Email.php
@@ -1,9 +1,9 @@
addElement('checkbox', 'per_membership', ts('Print one label per Membership (rather than per contact)'));
}
@@ -68,7 +68,7 @@ public function buildQuickForm() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$format = CRM_Core_BAO_LabelFormat::getDefaultValues();
$defaults['label_name'] = CRM_Utils_Array::value('name', $format);
$defaults['merge_same_address'] = 0;
@@ -115,22 +115,22 @@ public function postProcess() {
if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
$val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
$comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
- $temp = array();
+ $temp = [];
foreach ($val as $vals) {
$temp[] = $comm[$vals];
}
$row['preferred_communication_method'] = implode(', ', $temp);
}
$row['id'] = $id;
- $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
- $rows[$id] = array($formatted);
+ $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $tokenFields);
+ $rows[$id] = [$formatted];
}
if ($isPerMembership) {
- $labelRows = array();
- $memberships = civicrm_api3('membership', 'get', array(
- 'id' => 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 65051f8ad3dc..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 14976f9d218c..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 a0d6e2a463a7..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 655fef15786a..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 abb05b9d86e6..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 74cdddea7fec..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 45bd206b27bb..93bb374bc825 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 3e5c371c4664..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 c8d4fe983c98..fa849f6449fd 100644
--- a/CRM/Member/Import/Form/MapField.php
+++ b/CRM/Member/Import/Form/MapField.php
@@ -1,9 +1,9 @@
controller->exportValue('DataSource', 'uploadFile');
+ $seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
- $config = CRM_Core_Config::singleton();
- $seperator = $config->fieldSeparator;
-
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
@@ -489,10 +484,7 @@ public function postProcess() {
$mappingParams = array(
'name' => $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 8a41e9e5b560..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));
@@ -113,18 +114,16 @@ public function preProcess() {
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
+ $seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
- $config = CRM_Core_Config::singleton();
- $seperator = $config->fieldSeparator;
-
$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
@@ -152,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]];
}
@@ -163,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 d751d6b3e7a9..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 77ec1821e2fb..cf7367687609 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 +158,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 +179,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 +205,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 +256,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 +312,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 +417,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 17dbf1c6b1b1..66147109a9b3 100644
--- a/CRM/Member/Import/Parser/Membership.php
+++ b/CRM/Member/Import/Parser/Membership.php
@@ -1,9 +1,9 @@
addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newMemberships = array();
+ $this->_newMemberships = [];
$this->setActiveFields($this->_mapperKeys);
@@ -211,6 +211,17 @@ 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':
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
if (!CRM_Utils_Array::crmInArray($val, $membershipTypes) &&
@@ -278,16 +289,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) {
@@ -341,7 +353,7 @@ public function import($onDuplicate, &$values) {
$indieFields = $tempIndieFields;
}
- $formatValues = array();
+ $formatValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -371,7 +383,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,10 +395,10 @@ public function import($onDuplicate, &$values) {
'Membership'
);
if ($dao->find(TRUE)) {
- $ids = array(
+ $ids = [
'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']);
@@ -415,12 +427,7 @@ public function import($onDuplicate, &$values) {
$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);
+ $error = $this->checkContactDuplicate($formatValues);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
@@ -478,10 +485,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 = '';
@@ -598,11 +605,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 +658,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 +686,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
);
@@ -750,11 +757,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])) {
diff --git a/CRM/Member/Info.php b/CRM/Member/Info.php
index cafeeb0d2928..059c72072607 100644
--- a/CRM/Member/Info.php
+++ b/CRM/Member/Info.php
@@ -1,9 +1,9 @@
'CiviMember',
'translatedName' => ts('CiviMember'),
- 'title' => 'CiviCRM Membership Engine',
+ '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 d6bff50bd3e7..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 23b622e5024b..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 7bfe1b1337ca..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 08771d8134e2..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..07661c9fb7f9
--- /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();
+
+ 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 de990fe970f1..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 005f2f4f36f6..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 10ecd2efe512..417de01f0f77 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' => 'Cancel Auto Renew Subscription',
- );
+ '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',
'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 eef87174c645..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 5470390e5b81..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]);
}
+
+ parent::tasks();
}
- CRM_Utils_Hook::searchTasks('membership', self::$_tasks);
- asort(self::$_tasks);
+
return self::$_tasks;
}
@@ -132,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();
}
/**
@@ -146,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;
}
@@ -182,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 d9e1662ad753..44100317acad 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-2016 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -44,31 +44,34 @@ class CRM_Member_Tokens extends \Civi\Token\AbstractTokenSubscriber {
* Class constructor.
*/
public function __construct() {
- parent::__construct('membership', array(
- 'fee' => ts('Membership Fee'),
- 'id' => ts('Membership ID'),
- 'join_date' => ts('Membership Join Date'),
- 'start_date' => ts('Membership Start Date'),
- 'end_date' => ts('Membership End Date'),
- 'status' => ts('Membership Status'),
- 'type' => ts('Membership Type'),
+ parent::__construct('membership', array_merge(
+ [
+ 'fee' => ts('Membership Fee'),
+ 'id' => ts('Membership ID'),
+ 'join_date' => ts('Membership Join Date'),
+ 'start_date' => ts('Membership Start Date'),
+ 'end_date' => ts('Membership End Date'),
+ 'status' => ts('Membership Status'),
+ 'type' => ts('Membership Type'),
+ ],
+ CRM_Utils_Token::getCustomFieldTokens('Membership')
));
}
/**
- * Is token active.
- *
- * @param \Civi\Token\TokenProcessor $processor
- *
- * @return bool
+ * @inheritDoc
*/
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';
}
+ /**
+ * Alter action schedule query.
+ *
+ * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
+ */
public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e) {
if ($e->mapping->getEntity() !== 'civicrm_membership') {
return;
@@ -83,27 +86,20 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
}
/**
- * Evaluate the content of a single token.
- *
- * @param \Civi\Token\TokenRow $row
- * The record for which we want token values.
- * @param string $entity
- * @param string $field
- * The name of the token field.
- * @param mixed $prefetch
- * Any data that was returned by the prefetch().
- *
- * @return mixed
+ * @inheritDoc
*/
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 (isset($actionSearchResult->$field)) {
$row->tokens($entity, $field, $actionSearchResult->$field);
}
+ elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
+ $row->customToken($entity, $cfID, $actionSearchResult->entity_id);
+ }
else {
$row->tokens($entity, $field, '');
}
diff --git a/CRM/Note/Form/Note.php b/CRM/Note/Form/Note.php
index b81ea64fbf84..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 1f15ae9df21b..367fa10429a3 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];
}
/**
@@ -231,7 +231,7 @@ public static function thermoMeter($pcpId) {
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";
- $params = array(1 => array($pcpId, 'Integer'));
+ $params = [1 => [$pcpId, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -254,7 +254,7 @@ public static function honorRoll($pcpId) {
AND contribution_status_id = 1
AND is_test = 0";
$dao = CRM_Core_DAO::executeQuery($query);
- $honor = array();
+ $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 +273,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 +360,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 +383,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 +407,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 +442,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 +476,16 @@ public static function handlePcp($pcpId, $component, $entity) {
return FALSE;
}
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
+ $pcpStatus = CRM_Core_PseudoConstant::get('CRM_PCP_BAO_PCP', 'status_id');
+ $approvedId = array_search('Approved', $pcpStatus);
- $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
-
- $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 +505,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 +529,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 +544,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 +588,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 +635,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 +688,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 +696,7 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
'from' => $receiptFrom,
'toName' => $name,
'toEmail' => $address,
- )
+ ]
);
return $sent;
}
@@ -709,7 +708,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 +734,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 +756,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 +774,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 +793,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 +825,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 +846,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 +863,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 +892,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 +915,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 c3ed984873de..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
+ * 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,
- ) ,
- 'pcp_contact_id' => array(
+ 'title' => ts('Personal Campaign Page ID'),
+ 'description' => ts('Personal Campaign Page ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- 'html' => array(
+ 'title' => ts('Personal Campaign Page Status'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
- 'type' => 'TexArea',
- ) ,
- ) ,
- 'page_text' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'TextArea',
+ ],
+ ],
+ 'page_text' => [
'name' => 'page_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Page Text') ,
+ 'title' => ts('Page Text'),
'default' => 'NULL',
- 'html' => array(
- 'type' => 'TexArea',
- ) ,
- ) ,
- 'donate_link_text' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'TextArea',
+ ],
+ ],
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'page_type' => array(
+ 'title' => ts('Contribution Page'),
+ 'description' => ts('The Contribution or Event Page which triggered this pcp'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'contribute',
- 'html' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'is_thermometer' => array(
+ 'title' => ts('PCP Block'),
+ 'description' => ts('The pcp block that this pcp page was created from'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ ],
+ 'is_thermometer' => [
'name' => 'is_thermometer',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Use Thermometer?') ,
- 'html' => array(
+ 'title' => ts('Use Thermometer?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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?') ,
- 'html' => array(
+ 'title' => ts('Show Honor Roll?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_active' => array(
+ ]
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'description' => 'Is Personal Campaign Page enabled/active?',
- 'html' => array(
+ 'title' => ts('Enabled?'),
+ 'description' => ts('Is Personal Campaign Page enabled/active?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Notify Owner?'),
+ 'description' => ts('Notify owner via email when someone donates to page?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pcp',
+ 'entity' => 'PCP',
+ 'bao' => 'CRM_PCP_BAO_PCP',
+ '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 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
*
@@ -370,10 +431,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
*
@@ -381,8 +443,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 = [];
+ 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 1efb5333996d..89b76af0be2c 100644
--- a/CRM/PCP/DAO/PCPBlock.php
+++ b/CRM/PCP/DAO/PCPBlock.php
@@ -1,301 +1,350 @@
__table = 'civicrm_pcp_block';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('PCP Block ID'),
+ 'description' => ts('PCP block Id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'target_entity_type' => array(
+ 'title' => ts('Entity'),
+ 'description' => ts('FK to civicrm_contribution_page.id OR civicrm_event.id'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'contribute',
- ) ,
- 'target_entity_id' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'supporter_profile_id' => array(
+ 'title' => ts('Target Entity ID'),
+ 'description' => ts('The entity that this pcp targets'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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)?'),
'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',
- 'html' => array(
+ 'title' => ts('Owner Notification'),
+ 'description' => ts('FK to civicrm_option_group with name = PCP owner notifications'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ '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)?'),
'default' => 'NULL',
- ) ,
- 'is_tellfriend_enabled' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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?'),
'default' => 'NULL',
- ) ,
- 'tellfriend_limit' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => 'NULL',
- ) ,
- 'link_text' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'NULL',
- ) ,
- 'is_active' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 1,
+ ],
+ '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?'),
'default' => '1',
- ) ,
- 'notify_email' => array(
+ 'table_name' => 'civicrm_pcp_block',
+ 'entity' => 'PCPBlock',
+ 'bao' => 'CRM_PCP_BAO_PCPBlock',
+ 'localizable' => 0,
+ ],
+ '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,
'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
*
@@ -303,10 +352,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
*
@@ -314,8 +364,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 = [];
+ 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 2e8a98aa4ba4..fe2bb9880fa9 100644
--- a/CRM/PCP/Form/Campaign.php
+++ b/CRM/PCP/Form/Campaign.php
@@ -1,9 +1,9 @@
assign('displayRecent', FALSE);
@@ -50,7 +50,7 @@ public function preProcess() {
$this->_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);
@@ -64,8 +64,14 @@ public function preProcess() {
parent::preProcess();
}
+ /**
+ * Set default form values.
+ *
+ * @return array
+ * Default values for the form.
+ */
public function setDefaultValues() {
- $dafaults = array();
+ $defaults = [];
$dao = new CRM_PCP_DAO_PCP();
if ($this->_pageId) {
@@ -97,8 +103,6 @@ public function setDefaultValues() {
/**
* Build the form object.
- *
- * @return void
*/
public function buildQuickForm() {
$this->add('text', 'pcp_title', ts('Title'), NULL, TRUE);
@@ -106,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;
@@ -129,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);
}
@@ -147,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);
}
/**
@@ -176,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.');
}
@@ -188,13 +192,10 @@ public static function formRule($fields, $files, $self) {
/**
* Process the form submission.
- *
- *
- * @return void
*/
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])) {
@@ -214,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]);
@@ -255,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);
@@ -269,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);
@@ -306,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);
@@ -315,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 ,
@@ -328,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) {
@@ -360,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 70c6504e459b..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 af1644163df9..da7802382bd5 100644
--- a/CRM/PCP/Form/Event.php
+++ b/CRM/PCP/Form/Event.php
@@ -1,9 +1,9 @@
assign('selectedChild', '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 641f1d40c2f3..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 ebdd3de7562d..ccac09cf5496 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,12 +266,8 @@ public function postProcess() {
}
}
- $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
- $dedupeParams['check_permission'] = FALSE;
- $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised');
- if ($ids) {
- $this->_contactID = $ids['0'];
- }
+ $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 2a643a42fa3e..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 2104b106a83c..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 6a1e4937bfad..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 6eb92d21422f..62b4dfa74043 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'],
@@ -748,22 +748,22 @@ public static function exportableFields($checkPermission = TRUE) {
$pledgeFields = array(
'pledge_status' => array(
- 'title' => 'Pledge Status',
+ 'title' => ts('Pledge Status'),
'name' => 'pledge_status',
'data_type' => CRM_Utils_Type::T_STRING,
),
'pledge_frequency_unit' => array(
- 'title' => 'Pledge Frequency Unit',
+ 'title' => ts('Pledge Frequency Unit'),
'name' => 'pledge_frequency_unit',
'data_type' => CRM_Utils_Type::T_ENUM,
),
'pledge_frequency_interval' => array(
- 'title' => 'Pledge Frequency Interval',
+ 'title' => ts('Pledge Frequency Interval'),
'name' => 'pledge_frequency_interval',
'data_type' => CRM_Utils_Type::T_INT,
),
'pledge_contribution_page_id' => array(
- 'title' => 'Pledge Contribution Page Id',
+ 'title' => ts('Pledge Contribution Page Id'),
'name' => 'pledge_contribution_page_id',
'data_type' => CRM_Utils_Type::T_INT,
),
@@ -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'],
@@ -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,30 +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 (!CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) {
- return date('Ymd', strtotime($value));
- }
- if (!CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
- return $date;
- }
- switch ($field) {
- case 'contribution_date':
- $date = date('Ymd');
- break;
+ foreach ($startDate as $field => $value) {
+ 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;
- 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;
}
@@ -1234,6 +1233,9 @@ public static function getPledgeStartDate($date, $pledgeBlock) {
/**
* Get first payment date for pledge.
*
+ * @param int $day
+ *
+ * @return bool|string
*/
public static function getPaymentDate($day) {
if ($day == 31) {
diff --git a/CRM/Pledge/BAO/PledgeBlock.php b/CRM/Pledge/BAO/PledgeBlock.php
index 357686bf4283..bbba0e145584 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)) {
$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('d/m/Y');
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
- $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->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;
- }
- $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 (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));
+ }
}
}
}
diff --git a/CRM/Pledge/BAO/PledgePayment.php b/CRM/Pledge/BAO/PledgePayment.php
index 6c9e037f172d..ec637d58b70b 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;
@@ -319,18 +317,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 +347,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 +367,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 +418,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 +451,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 +490,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 +512,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 +568,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 +604,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 +623,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 +670,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 +689,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 +721,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 +741,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 +770,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 +814,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 +892,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 f2aec40dfd02..902872d1c1b3 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;
@@ -298,15 +311,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 +331,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 +358,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 +369,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 +398,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 +422,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;
@@ -430,15 +447,6 @@ public static function from($name, $mode, $side) {
return $from;
}
- /**
- * Getter for the qill object.
- *
- * @return string
- */
- public function qill() {
- return (isset($this->_qill)) ? $this->_qill : "";
- }
-
/**
* Ideally this function should include fields that are displayed in the selector.
*
@@ -454,7 +462,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,
@@ -475,7 +483,7 @@ public static function defaultReturnProperties(
'pledge_frequency_unit' => 1,
'pledge_currency' => 1,
'pledge_campaign_id' => 1,
- );
+ ];
}
return $properties;
}
@@ -491,7 +499,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,
@@ -502,7 +510,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');
@@ -528,80 +536,61 @@ public static function buildSearchForm(&$form) {
CRM_Core_Form_Date::buildDateRange($form, 'pledge_payment_date', 1, '_low', '_high', ts('From'), FALSE);
$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('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->add('select', 'pledge_status_id',
ts('Pledge Status'), CRM_Pledge_BAO_Pledge::buildOptions('status_id'),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
);
$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
);
- // add all the custom searchable fields
- $pledge = array('Pledge');
- $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $pledge);
- if ($groupDetails) {
- $form->assign('pledgeGroupTree', $groupDetails);
- foreach ($groupDetails as $group) {
- foreach ($group['fields'] as $field) {
- $fieldId = $field['id'];
- $elementName = 'custom_' . $fieldId;
- CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
- }
- }
- }
+ self::addCustomFormFields($form, ['Pledge']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id');
$form->assign('validCiviPledge', TRUE);
- $form->setDefaults(array('pledge_test' => 0));
- }
-
- /**
- * @param $row
- * @param int $id
- */
- public static function searchAction(&$row, $id) {
+ $form->setDefaults(['pledge_test' => 0]);
}
/**
@@ -610,7 +599,7 @@ public static function searchAction(&$row, $id) {
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 e5004478b81e..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
+ * 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,
- ) ,
- 'pledge_contact_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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'),
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge.amount',
'headerPattern' => '',
'dataPattern' => '',
- 'export' => true,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'export' => TRUE,
+ 'where' => 'civicrm_pledge.original_installment_amount',
+ 'headerPattern' => '',
+ 'dataPattern' => '',
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_frequency_unit' => array(
+ ]
+ ],
+ '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,
'default' => 'month',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
'default' => '3',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.'),
+ 'export' => TRUE,
+ 'where' => 'civicrm_pledge.installments',
+ 'headerPattern' => '',
+ 'dataPattern' => '',
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'start_date' => array(
+ ],
+ ],
+ '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,
- 'html' => array(
+ 'title' => ts('Pledge Start Date'),
+ 'description' => ts('The date the first scheduled pledge occurs.'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.',
- 'html' => array(
+ 'title' => ts('Pledge Acknowledged'),
+ 'description' => ts('When a pledge acknowledgement message was sent to the contributor.'),
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'cancel_date' => array(
+ 'title' => ts('Pledge Modified Date'),
+ 'description' => ts('Last updated date for this pledge record.'),
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ ],
+ '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.',
- 'html' => array(
+ 'title' => ts('Pledge Cancelled Date'),
+ 'description' => ts('Date this pledge was cancelled by contributor.'),
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'end_date' => array(
+ ],
+ ],
+ '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).',
- 'html' => array(
+ 'title' => ts('Pledge End Date'),
+ 'description' => ts('Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).'),
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.'),
'default' => '5',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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.'),
'default' => '5',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
- 'pseudoconstant' => array(
- 'optionGroupName' => 'contribution_status',
- 'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- 'pledge_is_test' => array(
+ 'export' => FALSE,
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_pledge',
+ 'entity' => 'Pledge',
+ 'bao' => 'CRM_Pledge_BAO_Pledge',
+ 'localizable' => 0,
+ '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
*
@@ -545,10 +652,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
*
@@ -556,8 +664,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 = [
+ 'index_status' => [
+ 'name' => 'index_status',
+ 'field' => [
+ 0 => 'status_id',
+ ],
+ '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 a161cd5562dc..381f297a2c12 100644
--- a/CRM/Pledge/DAO/PledgeBlock.php
+++ b/CRM/Pledge/DAO/PledgeBlock.php
@@ -1,262 +1,305 @@
__table = 'civicrm_pledge_block';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Pledge Block ID'),
+ 'description' => ts('Pledge ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'pledge_frequency_unit' => array(
+ 'title' => ts('Entity Id'),
+ 'description' => ts('FK to entity table specified in entity_table column.'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'is_pledge_interval' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ '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.',
- ) ,
- 'max_reminders' => array(
+ 'title' => ts('Expose Frequency Interval?'),
+ 'description' => ts('Is frequency interval exposed on the contribution form.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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.'),
'default' => '1',
- ) ,
- 'initial_reminder_day' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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.'),
'default' => '5',
- ) ,
- 'additional_reminder_day' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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.'),
'default' => '5',
- ) ,
- 'pledge_start_date' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'is_pledge_start_date_visible' => array(
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'is_pledge_start_date_editable' => array(
+ 'title' => ts('Show Recurring Donation Start Date?'),
+ 'description' => ts('If true - recurring start date is shown.'),
+ 'required' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_pledge_block',
+ 'entity' => 'PledgeBlock',
+ 'bao' => 'CRM_Pledge_BAO_PledgeBlock',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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
*
@@ -264,10 +307,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
*
@@ -275,8 +319,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 = [
+ 'index_entity' => [
+ 'name' => 'index_entity',
+ 'field' => [
+ 0 => 'entity_table',
+ 1 => 'entity_id',
+ ],
+ '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 50059dd86b08..d43a0f779135 100644
--- a/CRM/Pledge/DAO/PledgePayment.php
+++ b/CRM/Pledge/DAO/PledgePayment.php
@@ -1,299 +1,336 @@
__table = 'civicrm_pledge_payment';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'pledge_id' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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.'),
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.scheduled_amount',
'headerPattern' => '',
'dataPattern' => '',
- 'export' => true,
- ) ,
- 'pledge_payment_actual_amount' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ ],
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.actual_amount',
'headerPattern' => '',
'dataPattern' => '',
- 'export' => true,
- ) ,
- 'currency' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ ],
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_payment_scheduled_date' => array(
+ ]
+ ],
+ '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,
- ) ,
- 'pledge_payment_reminder_date' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'pledge_payment_reminder_count' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'pledge_payment_status_id' => array(
+ 'export' => TRUE,
+ 'default' => '0',
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ ],
+ '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,
- 'pseudoconstant' => array(
+ 'export' => FALSE,
+ 'table_name' => 'civicrm_pledge_payment',
+ 'entity' => 'PledgePayment',
+ 'bao' => 'CRM_Pledge_BAO_PledgePayment',
+ 'localizable' => 0,
+ '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
*
@@ -301,10 +338,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
*
@@ -312,8 +350,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 = [
+ 'index_contribution_pledge' => [
+ 'name' => 'index_contribution_pledge',
+ 'field' => [
+ 0 => 'contribution_id',
+ 1 => 'pledge_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_pledge_payment::0::contribution_id::pledge_id',
+ ],
+ 'index_status' => [
+ 'name' => 'index_status',
+ 'field' => [
+ 0 => 'status_id',
+ ],
+ '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 72bb5cab44bc..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 555c4b0a4fb2..e7478f8b1310 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)) {
@@ -100,14 +103,14 @@ public function preProcess() {
// 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 +122,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 +129,6 @@ public function preProcess() {
public function setDefaultValues() {
$defaults = $this->_values;
- $fields = array();
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
@@ -137,25 +138,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');
@@ -165,9 +154,8 @@ public function setDefaultValues() {
}
else {
// 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 +167,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 +196,43 @@ 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);
+ $this->addEntityRef('contact_id', ts('Contact'), [
+ 'create' => TRUE,
+ 'api' => ['extra' => ['email']],
+ ], TRUE);
}
$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,93 +259,68 @@ 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']);
+ }
+ elseif (!empty($this->_submitValues['currency'])) {
+ $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('currency', $this->_values['currency']);
$this->assign('eachPaymentAmount', $eachPaymentAmount);
- $this->assign('hideCalender', TRUE);
}
if (CRM_Utils_Array::value('status_id', $this->_values) !=
@@ -366,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');
@@ -404,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();
@@ -445,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.');
@@ -486,7 +447,7 @@ public function postProcess() {
$session = CRM_Core_Session::singleton();
- $fields = array(
+ $fields = [
'frequency_unit',
'frequency_interval',
'frequency_day',
@@ -497,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);
}
@@ -507,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,7 +551,7 @@ public function postProcess() {
) = 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) {
@@ -604,13 +565,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 fd1f15e9239c..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 8f48b5901e55..e4a0354e0147 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', CRM_Core_DAO::$_nullObject);
- $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
@@ -145,7 +137,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Pledge_BAO_Query::buildSearchForm($this);
@@ -155,9 +147,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 +174,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.
*
@@ -212,7 +232,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,25 +311,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;
+ $this->addFormRule(['CRM_Pledge_Form_Search', 'formRule']);
}
/**
@@ -320,7 +322,7 @@ public static function formRule($fields) {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults = $this->_formValues;
return $defaults;
}
@@ -333,8 +335,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 +362,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;
}
@@ -369,17 +371,13 @@ public function fixFormValues() {
$this->_defaults['pledge_status_id'] = $statuses;
}
- $pledgeFromDate = CRM_Utils_Request::retrieve('pstart', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $pledgeFromDate = CRM_Utils_Request::retrieve('pstart', 'Date');
if ($pledgeFromDate) {
list($date) = CRM_Utils_Date::setDateDefaults($pledgeFromDate);
$this->_formValues['pledge_create_date_low'] = $this->_defaults['pledge_create_date_low'] = $date;
}
- $pledgeToDate = CRM_Utils_Request::retrieve('pend', 'Date',
- CRM_Core_DAO::$_nullObject
- );
+ $pledgeToDate = CRM_Utils_Request::retrieve('pend', 'Date');
if ($pledgeToDate) {
list($date) = CRM_Utils_Date::setDateDefaults($pledgeToDate);
$this->_formValues['pledge_create_date_high'] = $this->_defaults['pledge_create_date_high'] = $date;
diff --git a/CRM/Pledge/Form/Task.php b/CRM/Pledge/Form/Task.php
index 9ba19f17b63d..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 0594789a18f5..deb28e3e3911 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 e6525b559c5b..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 f4afa881f654..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 a6cde292d241..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 b5cc49a780df..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 6dcb2d1220be..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 a071e84b5f98..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 5b5af4f27189..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 7c1009362a81..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 5588fb19f56a..94551d9544ae 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 5ed3c0e14fa3..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 b1a6d339cd36..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);
- 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'];
+ parent::tasks();
}
- 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;
+ return self::$_tasks;
}
/**
@@ -122,26 +84,28 @@ public static function &optionalTaskTitle() {
* 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;
}
@@ -156,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 9b0ef7cc06a1..4524376162f0 100644
--- a/CRM/Price/BAO/LineItem.php
+++ b/CRM/Price/BAO/LineItem.php
@@ -1,9 +1,9 @@
- * $Id$
+ * @copyright CiviCRM LLC (c) 2004-2019
*/
/**
@@ -51,7 +42,10 @@ class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
* @param array $params
* (reference) an assoc array of name/value pairs.
*
- * @return CRM_Price_DAO_LineItem
+ * @return \CRM_Price_DAO_LineItem
+ *
+ * @throws \CiviCRM_API3_Exception
+ * @throws \Exception
*/
public static function create(&$params) {
$id = CRM_Utils_Array::value('id', $params);
@@ -67,8 +61,15 @@ 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 {
+ if (!isset($params['unit_price'])) {
+ $params['unit_price'] = 0;
+ }
+ }
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
if (empty($params['financial_type_id'])) {
throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
@@ -84,16 +85,19 @@ 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)) {
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 {
@@ -135,7 +139,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'])) {
@@ -145,7 +149,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 {
@@ -154,18 +158,16 @@ public static function getAPILineItemParams(&$params) {
}
/**
- * @param int $entityId
- * @param $entityTable
+ * @param int $contributionId
*
* @return null|string
*/
- public static function getLineTotal($entityId, $entityTable) {
+ public static function getLineTotal($contributionId) {
$sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
FROM civicrm_line_item li
-WHERE li.entity_table = '{$entityTable}'
-AND li.entity_id = {$entityId}
-";
- $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
+WHERE li.contribution_id = %1";
+ $params = [1 => [$contributionId, 'Integer']];
+ $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
return $lineItemTotal;
}
@@ -176,7 +178,7 @@ public static function getLineTotal($entityId, $entityTable) {
* @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);
}
/**
@@ -188,20 +190,15 @@ public static function getLineItemsByContributionID($contributionID) {
* @param string $entity
* participant/contribution.
*
- * @param null $isQuick
+ * @param bool $isQuick
* @param bool $isQtyZero
* @param bool $relatedEntity
*
- * @param string $overrideWhereClause
- * E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
- * this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even
- * when we don't want it's entity-id magix
- *
* @param bool $invoice
* @return array
* Array of line items
*/
- public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE) {
+ public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
$whereClause = $fromClause = NULL;
$selectClause = "
SELECT li.id,
@@ -214,6 +211,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
li.entity_id,
pf.label as field_title,
pf.html_type,
+ pf.price_set_id,
pfv.membership_type_id,
pfv.membership_num_terms,
li.price_field_id,
@@ -255,30 +253,27 @@ 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');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- if ($overrideWhereClause) {
- $whereClause = $overrideWhereClause;
- }
$dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
while ($dao->fetch()) {
if (!$dao->id) {
continue;
}
- $lineItems[$dao->id] = array(
+ $lineItems[$dao->id] = [
'qty' => (float) $dao->qty,
'label' => $dao->label,
'unit_price' => $dao->unit_price,
@@ -289,23 +284,32 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
'field_title' => $dao->field_title,
'html_type' => $dao->html_type,
'description' => $dao->description,
- // the entity id seems prone to randomness but not sure if it has a reason - so if we are overriding the Where clause we assume
- // we also JUST WANT TO KNOW the the entity_id in the DB
- 'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id,
+ 'entity_id' => $dao->entity_id,
'entity_table' => $dao->entity_table,
'contribution_id' => $dao->contribution_id,
'financial_type_id' => $dao->financial_type_id,
+ 'financial_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id),
'membership_type_id' => $dao->membership_type_id,
'membership_num_terms' => $dao->membership_num_terms,
'tax_amount' => $dao->tax_amount,
- );
- $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
+ '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)) {
+ // 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
+ $lineItems[$dao->id]['tax_rate'] = FALSE;
+ }
$lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
if ($lineItems[$dao->id]['tax_amount'] != '') {
$getTaxDetails = TRUE;
}
}
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);
@@ -329,6 +333,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}"])) {
@@ -337,7 +346,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'];
}
@@ -352,13 +361,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]),
@@ -375,7 +380,8 @@ public static function format($fid, $params, $fields, &$values, $amount_override
'html_type' => $fields['html_type'],
'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');
@@ -397,7 +403,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'";
@@ -432,7 +438,9 @@ public static function processPriceSet($entityId, $lineItem, $contributionDetail
}
foreach ($values as &$line) {
- $line['entity_table'] = $entityTable;
+ if (empty($line['entity_table'])) {
+ $line['entity_table'] = $entityTable;
+ }
if (empty($line['entity_id'])) {
$line['entity_id'] = $entityId;
}
@@ -447,8 +455,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']);
+ }
}
}
@@ -493,16 +504,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 .= "
@@ -512,10 +523,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 = "
@@ -542,10 +553,9 @@ 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('total_amount', $params);
+ $totalAmount = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
$financialType = CRM_Utils_Array::value('financial_type_id', $params);
foreach ($priceSetDetails as $values) {
if ($entityTable == 'membership') {
@@ -557,7 +567,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'],
@@ -566,7 +576,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
'line_total' => $totalAmount,
'financial_type_id' => $financialType,
'membership_type_id' => $values['membership_type_id'],
- );
+ ];
break;
}
}
@@ -577,7 +587,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
$isRelatedID = TRUE;
}
foreach ($entityId as $id) {
- $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
+ $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
foreach ($lineItems as $key => $values) {
if (!$setID && $values['price_field_id']) {
$setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
@@ -596,25 +606,736 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
}
/**
- * Calculate tax rate in percentage.
+ * 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 array $lineItemId
- * An assoc array of lineItem.
+ * @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]
*
- * @return int|void
- * tax rate
*/
- public static function calculateTaxRate($lineItemId) {
- if ($lineItemId['unit_price'] == 0 || $lineItemId['qty'] == 0) {
- return FALSE;
+ 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 (!empty($updateFinancialItemInfoValues['link-financial-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,
+ ]);
+ unset($updateFinancialItemInfoValues['link-financial-trxn']);
+ }
+ }
+ }
+
+ // @todo - it may be that trxn_id is always empty - flush out scenarios. Add tests.
+ $trxnId = !empty($trxn->id) ? ['id' => $trxn->id] : [];
+ $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxnId);
+
+ // 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) &&
+ $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text' &&
+ $updateFinancialItemInfoValues['amount'] > 0
+ ) {
+ // calculate the amount difference, considered as financial item amount
+ $updateFinancialItemInfoValues['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
+ // add a flag, later used to link financial trxn and this new financial item
+ $updateFinancialItemInfoValues['link-financial-trxn'] = TRUE;
+ 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 $isCreateAdditionalFinancialTrxn
+ * Is there a change to the total balance requiring additional transactions to be created.
+ */
+ protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $isCreateAdditionalFinancialTrxn) {
+ $updatedContribution = new CRM_Contribute_BAO_Contribution();
+ $updatedContribution->id = $contributionID;
+ $updatedContribution->find(TRUE);
+
+ foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
+ $lineParams = array_merge($lineParams, [
+ 'entity_table' => $entityTable,
+ 'entity_id' => $entityID,
+ 'contribution_id' => $contributionID,
+ ]);
+ $this->addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution);
+ }
+ }
+
+ /**
+ * 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,
+ ];
}
- if ($lineItemId['html_type'] == 'Text') {
- $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
+ 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],
+ CRM_Core_DAO::$_nullArray,
+ CRM_Core_DAO::$_nullArray
+ );
+ $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 {
- $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);
+ 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;
+ }
+ elseif ($isCreateAdditionalFinancialTrxn) {
+ // This routine & the return below is super uncomfortable.
+ // I have refactored to here but don't understand how this would be hit
+ // and it is how it would be a good thing, given the odd return below which
+ // does not seem consistent with what is going on.
+ // I'm tempted to add an e-deprecated into it to confirm my suspicion it only exists to
+ // cause mental anguish.
+ // 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);
+ $tempFinancialTrxnID = ['id' => $adjustedTrxn->id];
+ }
+ }
+ $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
+ // insert financial items
+ // ensure entity_financial_trxn table has a linking of it.
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
+ if (isset($lineObj->tax_amount)) {
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
+ }
+ }
+
+ /**
+ * 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 $tax;
+ 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 5ae349b305e4..0085d6ec89d1 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.
*
@@ -75,6 +82,7 @@ public static function add(&$params) {
* (reference) an assoc array of name/value pairs.
*
* @return CRM_Price_DAO_PriceField
+ * @throws \CRM_Core_Exception
*/
public static function create(&$params) {
if (empty($params['id']) && empty($params['name'])) {
@@ -89,21 +97,29 @@ public static function create(&$params) {
return $priceField;
}
- $optionsIds = array();
+ if (!empty($params['id']) && empty($priceField->html_type)) {
+ $priceField->html_type = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
+ }
+ $optionsIds = [];
$maxIndex = CRM_Price_Form_Field::NUM_OPTION;
-
if ($priceField->html_type == 'Text') {
$maxIndex = 1;
-
- $fieldValue = new CRM_Price_DAO_PriceFieldValue();
- $fieldValue->price_field_id = $priceField->id;
-
- // update previous field values( if any )
- if ($fieldValue->find(TRUE)) {
- $optionsIds['id'] = $fieldValue->id;
+ $fieldOptions = civicrm_api3('price_field_value', 'get', [
+ 'price_field_id' => $priceField->id,
+ 'sequential' => 1,
+ ]);
+ foreach ($fieldOptions['values'] as $option) {
+ $optionsIds['id'] = $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();
+ $fieldValue->label = $priceField->label;
+ $fieldValue->id = $option['id'];
+ $fieldValue->save();
+ }
}
}
- $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']);
@@ -125,11 +141,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),
@@ -138,10 +154,13 @@ public static function create(&$params) {
'is_active' => 1,
'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);
+ $options['is_default'] = CRM_Utils_Array::value($params['membership_type_id'][$index], $defaultArray) ? $defaultArray[$params['membership_type_id'][$index]] : 0;
}
if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
@@ -150,7 +169,6 @@ public static function create(&$params) {
elseif (!empty($params['financial_type_id'])) {
$options['financial_type_id'] = $params['financial_type_id'];
}
-
if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
if ($opId = CRM_Utils_Array::value($index, $opIds)) {
$optionsIds['id'] = $opId;
@@ -159,7 +177,25 @@ public static function create(&$params) {
$optionsIds['id'] = NULL;
}
}
- CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
+ try {
+ CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
+ }
+ catch (Exception $e) {
+ $transaction->rollback();
+ throw new CRM_Core_Exception($e->getMessage());
+ }
+ }
+ 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 {
+ CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
+ }
+ catch (Exception $e) {
+ $transaction->rollback();
+ throw new CRM_Core_Exception($e->getMessage());
+ }
}
}
@@ -189,8 +225,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);
@@ -252,7 +288,7 @@ public static function addQuickFormElement(
$useRequired = TRUE,
$label = NULL,
$fieldOptions = NULL,
- $freezeOptions = array()
+ $freezeOptions = []
) {
$field = new CRM_Price_DAO_PriceField();
@@ -312,13 +348,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;
}
@@ -328,21 +364,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
@@ -358,7 +394,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.
@@ -366,7 +402,7 @@ public static function addQuickFormElement(
break;
case 'Radio':
- $choice = array();
+ $choice = [];
if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
$qf->assign('contriPriceset', $elementName);
@@ -377,10 +413,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) {
@@ -403,27 +439,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
@@ -435,11 +478,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();',
- )
+ ]
);
}
@@ -456,7 +499,7 @@ public static function addQuickFormElement(
}
$choice[] = $qf->createElement('radio', NULL, '', $none, '0',
- array('price' => json_encode(array($elementName, '0')))
+ ['price' => json_encode([$elementName, '0'])]
);
}
@@ -470,12 +513,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);
@@ -492,7 +535,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'];
@@ -506,16 +549,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
@@ -527,7 +575,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, '');
@@ -550,16 +598,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
@@ -571,7 +620,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;
}
@@ -589,22 +638,23 @@ public static function addQuickFormElement(
* Include inactive options.
* @param bool $reset
* Discard stored values.
+ * @param bool $isDefaultContributionPriceSet
+ * Discard tax amount calculation for price set = default_contribution_amount.
*
* @return array
* array of options
*/
- public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
- static $options = array();
- if ($reset) {
- $options = array();
+ public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
+ 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();
@@ -612,15 +662,16 @@ public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FA
// ToDo - Code for Hook Invoke
foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
- if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
+ if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
$options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
$taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
$options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
}
}
+ Civi::$statics[__CLASS__]['priceOptions'][$fieldId] = $options[$fieldId];
}
- return $options[$fieldId];
+ return Civi::$statics[__CLASS__]['priceOptions'][$fieldId];
}
/**
@@ -647,10 +698,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;
@@ -675,7 +726,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);
@@ -692,12 +743,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;
}
@@ -722,10 +773,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()) {
@@ -751,15 +802,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)) {
@@ -785,8 +836,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 {
@@ -831,4 +891,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 d3ed23c70fe3..071d879aa36b 100644
--- a/CRM/Price/BAO/PriceFieldValue.php
+++ b/CRM/Price/BAO/PriceFieldValue.php
@@ -1,9 +1,9 @@
copyValues($params);
@@ -66,16 +64,9 @@ public static function add(&$params, $ids = array()) {
if (!$priceFieldID) {
$priceFieldID = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceFieldValue', $id, 'price_field_id');
}
- if (!empty($params['financial_type_id'])) {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType(
- $params['financial_type_id'],
- $priceFieldID,
- 'PriceField'
- );
- }
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);
}
@@ -95,7 +86,7 @@ public static function add(&$params, $ids = array()) {
*
* @return CRM_Price_DAO_PriceFieldValue
*/
- 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;
@@ -113,8 +104,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 {
@@ -125,6 +115,15 @@ public static function create(&$params, $ids = array()) {
}
}
}
+
+ $financialType = CRM_Utils_Array::value('financial_type_id', $params, NULL);
+ if (!$financialType && $id) {
+ $financialType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'financial_type_id', 'id');
+ }
+ CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
+ if (!empty($financialType) && !array_key_exists($financialType, $financialTypes) && $params['is_active']) {
+ throw new CRM_Core_Exception("Financial Type for Price Field Option is either disabled or does not exist");
+ }
return self::add($params, $ids);
}
@@ -133,10 +132,10 @@ public static function create(&$params, $ids = array()) {
* @return array
*/
public static function getDefaults() {
- return array(
+ return [
'is_active' => 1,
'weight' => 1,
- );
+ ];
}
@@ -157,7 +156,7 @@ public static function retrieve(&$params, &$defaults) {
}
/**
- * Retrive the all values for given field id.
+ * Retrieve all values for given field id.
*
* @param int $fieldId
* Price_field_id.
@@ -166,30 +165,35 @@ public static function retrieve(&$params, &$defaults) {
* @param string $orderBy
* For order by, default weight.
* @param bool|int $isActive is_active, default false
+ * @param bool $admin is this loading it for use on an admin page.
*
* @return array
*
*/
- public static function getValues($fieldId, &$values, $orderBy = 'weight', $isActive = FALSE) {
+ public static function getValues($fieldId, &$values, $orderBy = 'weight', $isActive = FALSE, $admin = FALSE) {
$sql = "SELECT cs.id FROM civicrm_price_set cs INNER JOIN civicrm_price_field cp ON cp.price_set_id = cs.id
WHERE cs.name IN ('default_contribution_amount', 'default_membership_type_amount') AND cp.id = {$fieldId} ";
$setId = CRM_Core_DAO::singleValueQuery($sql);
$fieldValueDAO = new CRM_Price_DAO_PriceFieldValue();
$fieldValueDAO->price_field_id = $fieldId;
+ $addWhere = '';
if (!$setId) {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
- $addWhere = "financial_type_id IN (0)";
- if (!empty($financialTypes)) {
+ if (!$admin) {
+ $addWhere = "financial_type_id IN (0)";
+ }
+ if (!empty($financialTypes) && !$admin) {
$addWhere = "financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
}
- $fieldValueDAO->whereAdd($addWhere);
+ if (!empty($addWhere)) {
+ $fieldValueDAO->whereAdd($addWhere);
+ }
}
$fieldValueDAO->orderBy($orderBy, 'label');
if ($isActive) {
$fieldValueDAO->is_active = 1;
}
$fieldValueDAO->find();
-
while ($fieldValueDAO->fetch()) {
CRM_Core_DAO::storeValues($fieldValueDAO, $values[$fieldValueDAO->id]);
}
@@ -219,9 +223,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);
@@ -280,11 +283,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') {
@@ -327,10 +330,10 @@ public static function updateAmountAndFeeLevel($id, $prevLabel, $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'),
- );
+ $params = [
+ 1 => [CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'],
+ 2 => [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);
diff --git a/CRM/Price/BAO/PriceSet.php b/CRM/Price/BAO/PriceSet.php
index 4b2922c51c83..ff2e0c3b7712 100644
--- a/CRM/Price/BAO/PriceSet.php
+++ b/CRM/Price/BAO/PriceSet.php
@@ -1,9 +1,9 @@
copyValues($params);
if (self::eventPriceSetDomainID()) {
@@ -114,10 +105,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);
@@ -151,9 +140,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,
@@ -162,7 +151,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];
@@ -191,30 +180,24 @@ public static function getTitle($id) {
*
* @return array
*/
- public static function &getUsedBy($id, $simpleReturn = FALSE) {
- $usedBy = $forms = $tables = array();
- $queryString = "
-SELECT entity_table, entity_id
-FROM civicrm_price_set_entity
-WHERE price_set_id = %1";
- $params = array(1 => array($id, 'Integer'));
- $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
-
- while ($crmFormDAO->fetch()) {
- $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
- $tables[] = $crmFormDAO->entity_table;
- }
- // Return only tables
+ public static function getUsedBy($id, $simpleReturn = FALSE) {
+ $usedBy = [];
+ $forms = self::getFormsUsingPriceSet($id);
+ $tables = array_keys($forms);
+ // @todo - this is really clumsy overloading the signature like this. Instead
+ // move towards having a function that does not call reformatUsedByFormsWithEntityData
+ // and call that when that data is not used.
if ($simpleReturn == 'table') {
return $tables;
}
+ // @todo - this is painfully slow in some cases.
if (empty($forms)) {
$queryString = "
SELECT cli.entity_table, cli.entity_id
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;
@@ -224,74 +207,17 @@ public static function &getUsedBy($id, $simpleReturn = FALSE) {
return $usedBy;
}
}
- // Return only entity data
+ // @todo - this is really clumsy overloading the signature like this. See above.
if ($simpleReturn == 'entity') {
return $forms;
}
- foreach ($forms as $table => $entities) {
- switch ($table) {
- case 'civicrm_event':
- $ids = implode(',', $entities);
- $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
-FROM civicrm_event ce
-LEFT JOIN civicrm_option_value ON
- ( ce.event_type_id = civicrm_option_value.value )
-LEFT JOIN civicrm_option_group ON
- ( civicrm_option_group.id = civicrm_option_value.option_group_id )
-WHERE
- civicrm_option_group.name = 'event_type' AND
- ce.id IN ($ids) AND
- ce.is_active = 1;";
- $crmDAO = CRM_Core_DAO::executeQuery($queryString);
- while ($crmDAO->fetch()) {
- if ($crmDAO->isTemplate) {
- $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
- $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
- $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
- }
- else {
- $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
- $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
- $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
- $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
- $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
- }
- }
- break;
-
- case 'civicrm_contribution_page':
- $ids = implode(',', $entities);
- $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
-FROM civicrm_contribution_page cp, civicrm_financial_type ct
-WHERE ct.id = cp.financial_type_id AND
- cp.id IN ($ids) AND
- cp.is_active = 1;";
- $crmDAO = CRM_Core_DAO::executeQuery($queryString);
- while ($crmDAO->fetch()) {
- $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
- $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
- $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
- $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
- }
- break;
-
- case 'civicrm_contribution':
- case 'civicrm_membership':
- case 'civicrm_participant':
- $usedBy[$table] = 1;
- break;
-
- default:
- CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
- break;
- }
- }
+ $usedBy = self::reformatUsedByFormsWithEntityData($forms, $usedBy);
return $usedBy;
}
/**
- * Delete the price set.
+ * Delete the price set, including the fields.
*
* @param int $id
* Price Set id.
@@ -302,19 +228,6 @@ public static function &getUsedBy($id, $simpleReturn = FALSE) {
*
*/
public static function deleteSet($id) {
- // remove from all inactive forms
- $usedBy = self::getUsedBy($id);
- if (isset($usedBy['civicrm_event'])) {
- foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
- $eventDAO = new CRM_Event_DAO_Event();
- $eventDAO->id = $eventId;
- $eventDAO->find();
- while ($eventDAO->fetch()) {
- self::removeFrom('civicrm_event', $eventDAO->id);
- }
- }
- }
-
// delete price fields
$priceField = new CRM_Price_DAO_PriceField();
$priceField->price_set_id = $id;
@@ -374,7 +287,7 @@ public static function removeFrom($entityTable, $entityId) {
}
/**
- * Find a price_set_id associatied with the given table, id and usedFor
+ * Find a price_set_id associated with the given table, id and usedFor
* Used For value for events:1, contribution:2, membership:3
*
* @param string $entityTable
@@ -400,13 +313,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);
@@ -477,7 +390,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);
@@ -521,9 +434,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',
@@ -540,7 +453,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
'javascript',
'visibility_id',
'is_required',
- );
+ ];
if ($required == TRUE) {
$priceFields[] = 'is_required';
}
@@ -549,17 +462,18 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
$select = 'SELECT ' . implode(',', $priceFields);
$from = ' FROM civicrm_price_field';
- $params = array();
- $params[1] = array($setID, 'Integer');
- $where = '
+ $params = [
+ 1 => [$setID, 'Integer'],
+ ];
+ $currentTime = date('YmdHis');
+ $where = "
WHERE price_set_id = %1
AND is_active = 1
-';
+AND ( active_on IS NULL OR active_on <= {$currentTime} )
+";
$dateSelect = '';
if ($validOnly) {
- $currentTime = date('YmdHis');
$dateSelect = "
-AND ( active_on IS NULL OR active_on <= {$currentTime} )
AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
";
}
@@ -570,11 +484,16 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
$dao = CRM_Core_DAO::executeQuery($sql, $params);
+ $isDefaultContributionPriceSet = FALSE;
+ if ('default_contribution_amount' == CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
+ $isDefaultContributionPriceSet = TRUE;
+ }
+
$visibility = CRM_Core_PseudoConstant::visibility('name');
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) {
@@ -587,12 +506,12 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
}
$setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
}
- $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
+ $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
}
// also get the pre and post help from this price set
$sql = "
-SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
+SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
FROM civicrm_price_set
WHERE id = %1";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
@@ -602,6 +521,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
$setTree[$setID]['help_pre'] = $dao->help_pre;
$setTree[$setID]['help_post'] = $dao->help_post;
$setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
+ $setTree[$setID]['min_amount'] = $dao->min_amount;
}
return $setTree;
}
@@ -618,7 +538,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
*/
public static function getOnlyPriceFieldID(array $priceSet) {
if (count($priceSet['fields']) > 1) {
- throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
+ throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
}
return (int) implode('_', array_keys($priceSet['fields']));
}
@@ -634,12 +554,11 @@ public static function getOnlyPriceFieldID(array $priceSet) {
public static function getOnlyPriceFieldValueID(array $priceSet) {
$priceFieldID = self::getOnlyPriceFieldID($priceSet);
if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
- throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
+ throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
}
return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
}
-
/**
* Initiate price set such that various non-BAO things are set on the form.
*
@@ -660,7 +579,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
$priceSetId = self::getFor($entityTable, $id);
}
- //check if priceset is is_config
+ //check if price set is is_config
if (is_numeric($priceSetId)) {
if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
$form->assign('quickConfig', 1);
@@ -708,21 +627,21 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
//get option count info.
$form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
if ($form->_priceSet['optionsCountTotal']) {
- $optionsCountDeails = array();
+ $optionsCountDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
foreach ($field['options'] as $option) {
$count = CRM_Utils_Array::value('count', $option, 0);
- $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
+ $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
}
}
}
- $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
+ $form->_priceSet['optionsCountDetails'] = $optionsCountDetails;
}
//get option max value info.
$optionsMaxValueTotal = 0;
- $optionsMaxValueDetails = array();
+ $optionsMaxValueDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
@@ -763,6 +682,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
* @param string $component
* This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
* (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
+ * @param int $priceSetID
*/
public static function processAmount($fields, &$params, &$lineItem, $component = '', $priceSetID = NULL) {
// using price set
@@ -775,13 +695,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) {
@@ -795,38 +715,36 @@ 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);
- if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
- $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
- $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
- }
- if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
+ $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') {
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
if (array_key_exists($params['financial_type_id'], $taxRates)) {
$field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
- $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
- $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
- $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
- $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
+ $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
+ $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
}
}
+ if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
+ $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
+ }
$totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
break;
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])) {
- $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
- $totalTax += $field['options'][$optionValueId]['tax_amount'];
- if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
+ $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
+ if ($amount_override) {
$lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
}
}
@@ -843,13 +761,12 @@ 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);
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
- $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
- $totalTax += $field['options'][$optionValueId]['tax_amount'];
+ $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
}
$totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
if (
@@ -863,11 +780,10 @@ 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])) {
- $lineItem = self::setLineItem($field, $lineItem, $optionId);
- $totalTax += $field['options'][$optionId]['tax_amount'];
+ $lineItem = self::setLineItem($field, $lineItem, $optionId, $totalTax);
}
$totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
if (
@@ -882,7 +798,7 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
}
}
- $amount_level = array();
+ $amount_level = [];
$totalParticipant = 0;
if (is_array($lineItem)) {
foreach ($lineItem as $values) {
@@ -919,7 +835,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;
}
}
- $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
+
+ $params['amount'] = $totalPrice;
$params['tax_amount'] = $totalTax;
if ($component) {
foreach ($autoRenew as $dontCare => $eachAmount) {
@@ -951,7 +868,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 = '';
@@ -982,7 +899,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']];
@@ -1009,7 +926,7 @@ public static function filterPriceFieldsFromParams($priceSetID, $params) {
public static function getCachedPriceSetDetail($priceSetID) {
$cacheKey = __CLASS__ . __FUNCTION__ . '_' . $priceSetID;
$cache = CRM_Utils_Cache::singleton();
- $values = (array) $cache->get($cacheKey);
+ $values = $cache->get($cacheKey);
if (empty($values)) {
$data = self::getSetDetail($priceSetID);
$values = $data[$priceSetID];
@@ -1033,10 +950,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;
}
@@ -1055,13 +972,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'])) {
@@ -1112,6 +1029,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) ||
@@ -1125,17 +1047,29 @@ 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;
}
- CRM_Price_BAO_PriceField::addQuickFormElement($form,
- 'price_' . $field['id'],
- $field['id'],
- FALSE,
- CRM_Utils_Array::value('is_required', $field, FALSE),
- NULL,
- $options
- );
+ 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'],
+ $field['id'],
+ FALSE,
+ CRM_Utils_Array::value('is_required', $field, FALSE),
+ NULL,
+ $options
+ );
+ }
}
}
}
@@ -1153,7 +1087,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'])) {
@@ -1188,7 +1122,7 @@ public static function setDefaultPriceSet(&$form, &$defaults) {
return $defaults;
}
- foreach ($form->_priceSet['fields'] as $key => $val) {
+ foreach ($form->_priceSet['fields'] as $val) {
foreach ($val['options'] as $keys => $values) {
// build price field index which is passed via URL
// url format will be appended by "&price_5=11"
@@ -1317,25 +1251,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));
@@ -1343,8 +1279,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]
);
}
}
@@ -1394,7 +1330,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
@@ -1404,7 +1340,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;
}
@@ -1418,14 +1354,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;
@@ -1459,7 +1395,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);
@@ -1470,7 +1406,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.
@@ -1513,10 +1449,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];
}
/**
@@ -1534,8 +1470,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);
@@ -1574,15 +1510,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;
@@ -1624,11 +1560,11 @@ public static function copyPriceSet($baoName, $id, $newId) {
}
else {
$copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
- array(
+ [
'entity_id' => $id,
'entity_table' => $baoName,
- ),
- array('entity_id' => $newId)
+ ],
+ ['entity_id' => $newId]
);
}
// copy event discount
@@ -1640,13 +1576,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,
- )
+ ]
);
}
}
@@ -1659,20 +1595,22 @@ public static function copyPriceSet($baoName, $id, $newId) {
* @param array $field
* @param array $lineItem
* @param int $optionValueId
+ * @param float $totalTax
*
* @return array
*/
- public static function setLineItem($field, $lineItem, $optionValueId) {
+ public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
+ // Here we round - i.e. after multiplying by quantity
if ($field['html_type'] == 'Text') {
- $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
+ $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
}
else {
- $taxAmount = $field['options'][$optionValueId]['tax_amount'];
+ $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
}
$taxRate = $field['options'][$optionValueId]['tax_rate'];
$lineItem[$optionValueId]['tax_amount'] = $taxAmount;
$lineItem[$optionValueId]['tax_rate'] = $taxRate;
-
+ $totalTax += $taxAmount;
return $lineItem;
}
@@ -1701,7 +1639,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;
@@ -1719,14 +1657,141 @@ 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])) {
+ if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
$priceSetParams[$field] = $value;
}
}
return $priceSetParams;
}
+ /**
+ * Get non-deductible amount from price options
+ *
+ * @param int $priceSetId
+ * @param array $lineItem
+ *
+ * @return int
+ * calculated non-deductible amount.
+ */
+ public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
+ $nonDeductibleAmount = 0;
+ if (!empty($lineItem[$priceSetId])) {
+ foreach ($lineItem[$priceSetId] as $options) {
+ $nonDeductibleAmount += $options['non_deductible_amount'] * $options['qty'];
+ }
+ }
+
+ return $nonDeductibleAmount;
+ }
+
+ /**
+ * Get an array of all forms using a given price set.
+ *
+ * @param int $id
+ *
+ * @return array
+ * Pages using the price set, keyed by type. e.g
+ * array('
+ * 'civicrm_contribution_page' => array(2,5,6),
+ * 'civicrm_event' => array(5,6),
+ * 'civicrm_event_template' => array(7),
+ * )
+ */
+ public static function getFormsUsingPriceSet($id) {
+ $forms = [];
+ $queryString = "
+SELECT entity_table, entity_id
+FROM civicrm_price_set_entity
+WHERE price_set_id = %1";
+ $params = [1 => [$id, 'Integer']];
+ $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
+
+ while ($crmFormDAO->fetch()) {
+ $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
+ }
+ return $forms;
+ }
+
+ /**
+ * @param array $forms
+ * Array of forms that use a price set keyed by entity. e.g
+ * array('
+ * 'civicrm_contribution_page' => array(2,5,6),
+ * 'civicrm_event' => array(5,6),
+ * 'civicrm_event_template' => array(7),
+ * )
+ *
+ * @return mixed
+ * Array of entities suppliemented with per entity information.
+ * e.g
+ * array('civicrm_event' => array(7 => array('title' => 'x'...))
+ *
+ * @throws \Exception
+ */
+ protected static function reformatUsedByFormsWithEntityData($forms) {
+ $usedBy = [];
+ foreach ($forms as $table => $entities) {
+ switch ($table) {
+ case 'civicrm_event':
+ $ids = implode(',', $entities);
+ $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
+FROM civicrm_event ce
+LEFT JOIN civicrm_option_value ON
+ ( ce.event_type_id = civicrm_option_value.value )
+LEFT JOIN civicrm_option_group ON
+ ( civicrm_option_group.id = civicrm_option_value.option_group_id )
+WHERE
+ civicrm_option_group.name = 'event_type' AND
+ ce.id IN ($ids) AND
+ ce.is_active = 1;";
+ $crmDAO = CRM_Core_DAO::executeQuery($queryString);
+ while ($crmDAO->fetch()) {
+ if ($crmDAO->isTemplate) {
+ $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
+ $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
+ $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
+ }
+ else {
+ $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
+ $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
+ $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
+ $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
+ $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
+ }
+ }
+ break;
+
+ case 'civicrm_contribution_page':
+ $ids = implode(',', $entities);
+ $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
+FROM civicrm_contribution_page cp, civicrm_financial_type ct
+WHERE ct.id = cp.financial_type_id AND
+ cp.id IN ($ids) AND
+ cp.is_active = 1;";
+ $crmDAO = CRM_Core_DAO::executeQuery($queryString);
+ while ($crmDAO->fetch()) {
+ $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
+ $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
+ $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
+ $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
+ }
+ break;
+
+ case 'civicrm_contribution':
+ case 'civicrm_membership':
+ case 'civicrm_participant':
+ $usedBy[$table] = 1;
+ break;
+
+ default:
+ CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
+ break;
+ }
+ }
+ return $usedBy;
+ }
+
}
diff --git a/CRM/Price/DAO/LineItem.php b/CRM/Price/DAO/LineItem.php
index 728fb06068e1..40dbb3f9996c 100644
--- a/CRM/Price/DAO/LineItem.php
+++ b/CRM/Price/DAO/LineItem.php
@@ -1,360 +1,414 @@
__table = 'civicrm_line_item';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Line Item ID'),
+ 'description' => ts('Line Item'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Entity') ,
- 'description' => 'entry in table',
- 'required' => true,
- ) ,
- 'contribution_id' => array(
+ 'title' => ts('Line Item Entity'),
+ 'description' => ts('entry in table'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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'),
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ '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
- ) ,
- 'html' => array(
+ ],
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ '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
- ) ,
- ) ,
- 'participant_count' => array(
+ ],
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ ],
+ '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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ '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'),
'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.'),
'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',
- )
- ) ,
- 'deductible_amount' => array(
- 'name' => 'deductible_amount',
+ ]
+ ],
+ 'non_deductible_amount' => [
+ 'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Deductible Amount') ,
- 'description' => 'Tax-deductible portion of the amount',
- '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
- ) ,
+ ],
'default' => '0.0',
- 'html' => array(
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ 'localizable' => 0,
+ '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,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_line_item.tax_amount',
'headerPattern' => '/tax(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
- 'html' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_line_item',
+ 'entity' => 'LineItem',
+ 'bao' => 'CRM_Price_BAO_LineItem',
+ '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
*
@@ -362,10 +416,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
*
@@ -373,8 +428,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 = [
+ 'index_entity' => [
+ 'name' => 'index_entity',
+ 'field' => [
+ 0 => 'entity_table',
+ 1 => 'entity_id',
+ ],
+ 'localizable' => FALSE,
+ 'sig' => 'civicrm_line_item::0::entity_table::entity_id',
+ ],
+ 'UI_line_item_value' => [
+ 'name' => 'UI_line_item_value',
+ 'field' => [
+ 0 => 'entity_table',
+ 1 => 'entity_id',
+ 2 => 'contribution_id',
+ 3 => 'price_field_value_id',
+ 4 => 'price_field_id',
+ ],
+ '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 f19c899648cb..6211831f0b28 100644
--- a/CRM/Price/DAO/PriceField.php
+++ b/CRM/Price/DAO/PriceField.php
@@ -1,397 +1,468 @@
1)
*
* @var boolean
*/
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
*/
public $visibility_id;
+
/**
- * class constructor
- *
- * @return civicrm_price_field
+ * Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'price_set_id' => array(
+ 'title' => ts('Price Field ID'),
+ 'description' => ts('Price Field'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Price Field Quantity Required?'),
+ 'description' => ts('Enter a quantity for this field?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 1,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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?'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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)'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
- 'type' => 'CheckBox',
- ) ,
- ) ,
- 'expire_on' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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\''),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field',
+ 'entity' => 'PriceField',
+ 'bao' => 'CRM_Price_BAO_PriceField',
+ 'localizable' => 0,
+ '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
*
@@ -399,10 +470,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
*
@@ -410,8 +482,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 = [
+ 'index_name' => [
+ 'name' => 'index_name',
+ 'field' => [
+ 0 => 'name',
+ ],
+ '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 cda882a76f17..c449711499b9 100644
--- a/CRM/Price/DAO/PriceFieldValue.php
+++ b/CRM/Price/DAO/PriceFieldValue.php
@@ -1,404 +1,501 @@
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
*/
public $count;
+
/**
* Max number of participants per field options
*
* @var int unsigned
*/
public $max_value;
+
/**
* Order in which the field options should appear
*
* @var int
*/
public $weight;
+
/**
* FK to Membership Type
*
* @var int unsigned
*/
public $membership_type_id;
+
/**
* Number of terms for this membership
*
* @var int unsigned
*/
public $membership_num_terms;
+
/**
* Is this default price field option
*
* @var boolean
*/
public $is_default;
+
/**
* Is this price field value active
*
* @var boolean
*/
public $is_active;
+
/**
* FK to Financial Type.
*
* @var int unsigned
*/
public $financial_type_id;
+
/**
- * Tax-deductible portion of the amount
+ * Portion of total amount which is NOT tax deductible.
*
* @var float
*/
- public $deductible_amount;
+ public $non_deductible_amount;
+
/**
- * class constructor
+ * Implicit FK to civicrm_option_group with name = 'visibility'
*
- * @return civicrm_price_field_value
+ * @var int unsigned
+ */
+ public $visibility_id;
+
+ /**
+ * Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field_value';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'price_field_id' => array(
+ 'title' => ts('Price Field Value ID'),
+ 'description' => ts('Price Field Value'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 1,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 1,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 1,
+ '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,
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'type' => CRM_Utils_Type::T_MONEY,
+ 'title' => ts('Amount'),
+ 'description' => ts('Price field option amount'),
+ 'required' => TRUE,
+ 'precision' => [
+ 18,
+ 9
+ ],
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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'),
'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'),
'default' => 'NULL',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('Is Default Price Field Option?'),
+ 'description' => ts('Is this default price field option'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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'),
'default' => '1',
- ) ,
- 'financial_type_id' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ ],
+ '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.'),
'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',
- )
- ) ,
- 'deductible_amount' => array(
- 'name' => 'deductible_amount',
+ ]
+ ],
+ 'non_deductible_amount' => [
+ 'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Deductible Amount') ,
- 'description' => 'Tax-deductible portion of the amount',
- '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
- ) ,
+ ],
'default' => '0.0',
- 'html' => array(
+ 'table_name' => 'civicrm_price_field_value',
+ 'entity' => 'PriceFieldValue',
+ 'bao' => 'CRM_Price_BAO_PriceFieldValue',
+ 'localizable' => 0,
+ '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\''),
+ '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
*
@@ -406,10 +503,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
*
@@ -417,8 +515,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 = [];
+ 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 bda7ba9467aa..ed8c4d685b86 100644
--- a/CRM/Price/DAO/PriceSet.php
+++ b/CRM/Price/DAO/PriceSet.php
@@ -1,330 +1,397 @@
__table = 'civicrm_price_set';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Price Set ID'),
+ 'description' => ts('Price Set'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ ],
+ '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'),
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 1,
+ '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'),
'default' => '1',
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 1,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ '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).'),
'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',
- 'html' => array(
+ 'title' => ts('Is Price Set Quick Config?'),
+ 'description' => ts('Is set if edited on Contribution or Event Page rather than through Manage Price Sets'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ '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)?',
- 'html' => array(
+ 'title' => ts('Price Set Is Reserved'),
+ 'description' => ts('Is this a predefined system price set (i.e. it can not be deleted, edited)?'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ 'min_amount' => [
+ 'name' => 'min_amount',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Minimum Amount'),
+ 'description' => ts('Minimum Amount required for this set.'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_price_set',
+ 'entity' => 'PriceSet',
+ 'bao' => 'CRM_Price_BAO_PriceSet',
+ '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 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
*
@@ -332,10 +399,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
*
@@ -343,8 +411,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 = [
+ 'UI_name' => [
+ 'name' => 'UI_name',
+ 'field' => [
+ 0 => 'name',
+ ],
+ '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 663e5511bf40..0bef5929d79b 100644
--- a/CRM/Price/DAO/PriceSetEntity.php
+++ b/CRM/Price/DAO/PriceSetEntity.php
@@ -1,173 +1,177 @@
__table = 'civicrm_price_set_entity';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'entity_table' => array(
+ 'title' => ts('Price Set Entity ID'),
+ 'description' => ts('Price Set Entity'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_price_set_entity',
+ 'entity' => 'PriceSetEntity',
+ 'bao' => 'CRM_Price_DAO_PriceSetEntity',
+ 'localizable' => 0,
+ ],
+ '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,
- ) ,
- 'entity_id' => array(
+ 'table_name' => 'civicrm_price_set_entity',
+ 'entity' => 'PriceSetEntity',
+ 'bao' => 'CRM_Price_DAO_PriceSetEntity',
+ 'localizable' => 0,
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity IF') ,
- 'description' => 'Item in table',
- 'required' => true,
- ) ,
- 'price_set_id' => array(
+ 'title' => ts('Entity IF'),
+ 'description' => ts('Item in table'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_price_set_entity',
+ 'entity' => 'PriceSetEntity',
+ 'bao' => 'CRM_Price_DAO_PriceSetEntity',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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
*
@@ -175,10 +179,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
*
@@ -186,8 +191,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 = [
+ 'UI_entity' => [
+ 'name' => 'UI_entity',
+ 'field' => [
+ 0 => 'entity_table',
+ 1 => 'entity_id',
+ ],
+ '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 176d96e12e30..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 f783c7d3b570..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'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -93,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 2e0fb425a64f..dc237c1fa735 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);
@@ -235,6 +231,10 @@ public function buildQuickForm() {
$this->registerRule('price', 'callback', 'money', 'CRM_Utils_Rule');
$this->addRule('price', ts('must be a monetary value'), 'money');
+ $this->add('text', 'non_deductible_amount', ts('Non-deductible Amount'), NULL);
+ $this->registerRule('non_deductible_amount', 'callback', 'money', 'CRM_Utils_Rule');
+ $this->addRule('non_deductible_amount', ts('Please enter a monetary value for this field.'), 'money');
+
if ($this->_action == CRM_Core_Action::UPDATE) {
$this->freeze('html_type');
}
@@ -268,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
@@ -284,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
@@ -311,29 +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');
- // help post, mask, attributes, javascript ?
- $this->add('textarea', 'help_post', ts('Field Help'),
+ $this->add('textarea', 'help_pre', ts('Pre Field Help'),
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
);
- // active_on
- $date_options = array(
- 'format' => 'dmY His',
- 'minYear' => date('Y') - 1,
- 'maxYear' => date('Y') + 5,
- 'addEmptyOption' => TRUE,
+ // help post, mask, attributes, javascript ?
+ $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?'));
@@ -342,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) {
@@ -371,7 +369,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'")
+ ['onclick' => "location.href='$url'"]
);
}
}
@@ -392,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
@@ -407,15 +405,6 @@ public static function formRule($fields, $files, $form) {
if ($fields['financial_type_id'] == '') {
$errors['financial_type_id'] = ts('Financial Type is a required field');
}
- else {
- // CRM-16189
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($fields['financial_type_id'], $form->_sid);
- }
- catch (CRM_Core_Exception $e) {
- $errors['financial_type_id'] = $e->getMessage();
- }
- }
}
//avoid the same price field label in Within PriceSet
@@ -443,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++) {
@@ -531,21 +521,20 @@ public static function formRule($fields, $files, $form) {
$_showHide->addHide($hideBlock);
}
- $_flagOption = $_emptyRow = 0;
- // CRM-16189
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($fields['option_financial_type_id'][$index], $form->_fid, 'PriceField');
- }
- catch(CRM_Core_Exception $e) {
- $errors["option_financial_type_id[{$index}]"] = $e->getMessage();
+ if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel || !$noAmount)) {
+ if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
+ $publicOptionCount++;
+ }
}
+
+ $_flagOption = $_emptyRow = 0;
}
if (!empty($memTypesIDS)) {
// 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)) {
@@ -585,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']) &&
@@ -599,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'] = [];
}
}
@@ -621,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);
@@ -640,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');
@@ -659,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) {
@@ -677,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 81b994f4ce59..f159c37bdc94 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;
}
@@ -115,22 +124,21 @@ public function setDefaultValues() {
public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::UPDATE) {
$finTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_oid, 'financial_type_id');
- CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::UPDATE);
- if (!array_key_exists($finTypeId, $financialTypes)) {
+ if (!CRM_Financial_BAO_FinancialType::checkPermissionToEditFinancialType($finTypeId)) {
CRM_Core_Error::fatal(ts("You do not have permission to access this page"));
}
}
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 {
@@ -164,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);
@@ -176,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');
}
@@ -194,7 +202,7 @@ public function buildQuickForm() {
'select',
'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType,
+ ['' => ts('- select -')] + $financialType,
TRUE
);
@@ -215,17 +223,24 @@ public function buildQuickForm() {
$this->registerRule('amount', 'callback', 'money', 'CRM_Utils_Rule');
$this->addRule('amount', ts('Please enter a monetary value for this field.'), 'money');
+ $this->add('text', 'non_deductible_amount', ts('Non-deductible Amount'), NULL);
+ $this->registerRule('non_deductible_amount', 'callback', 'money', 'CRM_Utils_Rule');
+ $this->addRule('non_deductible_amount', ts('Please enter a monetary value for this field.'), 'money');
+
$this->add('textarea', 'description', ts('Description'));
$this->add('textarea', 'help_pre', ts('Pre Option Help'));
$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'));
@@ -238,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);
}
/**
@@ -279,19 +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.');
}
- // CRM-16189
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($fields['financial_type_id'], $form->_fid, 'PriceField');
+
+ $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++;
+ }
}
- catch (CRM_Core_Exception $e) {
- $errors['financial_type_id'] = $e->getMessage();
+ if ($visibilityOptions[$priceField->visibility_id] == 'public' && $publicCount == 0) {
+ $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' && $publicCount > 0) {
+ $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;
}
@@ -302,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,
@@ -310,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;
}
$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 71f687eeded8..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'])) {
@@ -132,18 +132,20 @@ public function buildQuickForm() {
foreach ($group['fields'] as $field) {
$fieldId = $field['id'];
$elementName = 'price_' . $fieldId;
- CRM_Price_BAO_PriceField::addQuickFormElement($this, $elementName, $fieldId, FALSE, $field['is_required']);
+ if (!empty($field['options'])) {
+ CRM_Price_BAO_PriceField::addQuickFormElement($this, $elementName, $fieldId, FALSE, $field['is_required']);
+ }
}
}
}
- $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 90d9be60fd3c..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,25 +158,10 @@ 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");
}
- // CRM-16189
- if (!empty($fields['extends'])
- && (array_key_exists(CRM_Core_Component::getComponentID('CiviEvent'), $fields['extends'])
- || array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $fields['extends']))
- ) {
- try {
- CRM_Financial_BAO_FinancialAccount::validateFinancialType($fields['financial_type_id']);
- }
- catch (CRM_Core_Exception $e) {
- $errors['financial_type_id'] = $e->getMessage();
- }
- }
return empty($errors) ? TRUE : $errors;
}
@@ -121,23 +169,18 @@ public static function formRule($fields, $files, $options) {
* Build the form object.
*/
public function buildQuickForm() {
- $this->applyFilter('__ALL__', 'trim');
+ $this->buildQuickEntityForm();
+ $this->assign('sid', $this->getEntityId());
- $this->assign('sid', $this->_sid);
-
- // 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) {
@@ -145,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;
@@ -158,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;
@@ -171,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;
@@ -192,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'"));
}
}
@@ -252,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']);
@@ -276,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) {
@@ -288,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'],
@@ -297,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 9ebf7ebd210b..47e1cb1c93dc 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,27 +133,23 @@ 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);
- $financialTypeId = $optionValues['financial_type_id'];
- if (!array_key_exists($financialTypeId, $financialTypes)) {
- unset($priceField[$priceFieldBAO->id]);
- continue;
- }
$priceField[$priceFieldBAO->id]['price'] = CRM_Utils_Array::value('amount', $optionValues);
+ $financialTypeId = $optionValues['financial_type_id'];
if ($invoicing && isset($taxRate[$financialTypeId])) {
$priceField[$priceFieldBAO->id]['tax_rate'] = $taxRate[$financialTypeId];
$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'];
}
}
@@ -187,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',
@@ -260,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;
@@ -302,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 c67194fa57f9..bdf06ffc3631 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,8 +121,17 @@ public static function &actionLinks() {
* @return void
*/
public function browse() {
- $customOption = array();
- CRM_Price_BAO_PriceFieldValue::getValues($this->_fid, $customOption);
+ $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,
+ 'options' => [
+ 'limit' => 0,
+ 'sort' => ['weight', 'label'],
+ ],
+ ]);
+ $customOption = $priceOptions['values'];
// CRM-15378 - check if these price options are in an Event price set
$isEvent = FALSE;
@@ -134,7 +143,6 @@ public function browse() {
}
$config = CRM_Core_Config::singleton();
- $financialType = CRM_Contribute_PseudoConstant::financialType();
$taxRate = CRM_Core_PseudoConstant::getTaxRates();
// display taxTerm for priceFields
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
@@ -145,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'])) {
- $customOption[$id]['financial_type_id'] = $financialType[$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) {
@@ -175,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',
@@ -215,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);
@@ -242,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;
@@ -280,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 3437be3268c7..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;
}
@@ -143,7 +143,6 @@ public function run() {
$this->preview($sid);
}
elseif ($action & CRM_Core_Action::COPY) {
- $session = CRM_Core_Session::singleton();
CRM_Core_Session::setStatus(ts('A copy of the price set has been created'), ts('Saved'), 'success');
$this->copy();
}
@@ -155,10 +154,8 @@ public function run() {
if (empty($usedBy)) {
// prompt to delete
- $session = CRM_Core_Session::singleton();
- $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/price', 'action=browse'));
+ CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin/price', 'action=browse'));
$controller = new CRM_Core_Controller_Simple('CRM_Price_Form_DeleteSet', 'Delete Price Set', NULL);
- // $id = CRM_Utils_Request::retrieve('sid', 'Positive', $this, false, 0);
$controller->set('sid', $sid);
$controller->setEmbedded(TRUE);
$controller->process();
@@ -171,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;
@@ -227,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}"));
}
@@ -250,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()) {
@@ -264,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)])) {
@@ -297,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 5f8e72b220f2..4c110de5d402 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.
@@ -80,7 +79,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Name of button for saving matching contacts.
- * @var
+ * @var string
*/
protected $_duplicateButtonName;
/**
@@ -114,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;
@@ -122,7 +122,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
protected $_isPermissionedChecksum = FALSE;
/**
- * THe context from which we came from, allows us to go there if redirect not set
+ * THe context from which we came from, allows us to go there if redirect not set.
*
* @var string
*/
@@ -137,9 +137,10 @@ 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
+ * Currently lets implement this functionality only for dialog mode.
+ * @var array
*/
- protected $_profileIds = array();
+ protected $_profileIds = [];
/**
* Contact profile having activity fields?
@@ -161,7 +162,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
protected $_recordId = NULL;
/**
- * Action for multi record profile (create/edit/delete)
+ * Action for multi record profile (create/edit/delete).
*
* @var string
*/
@@ -180,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 = [$form->_session->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.
*/
@@ -191,16 +290,12 @@ public function getDefaultEntity() {
* Pre processing work done here.
*
* gets session variables for table name, id of entity in table, type of entity and stores them.
- *
- * @param
- *
- * @return void
*/
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
@@ -225,7 +320,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'));
}
@@ -268,7 +363,7 @@ public function preProcess() {
}
$this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
- //get values for ufGroupName, captch and dupe update.
+ //get values for ufGroupName, captcha and dupe update.
if ($this->_gid) {
$dao = new CRM_Core_DAO_UFGroup();
$dao->id = $this->_gid;
@@ -280,16 +375,16 @@ public function preProcess() {
$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']);
$gids = empty($this->_profileIds) ? $this->_gid : $this->_profileIds;
- // if we dont have a gid use the default, else just use that specific gid
+ // if we don't have a gid use the default, else just use that specific gid
if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
$this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
$this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
@@ -313,7 +408,7 @@ public function preProcess() {
($this->_action == CRM_Core_Action::ADD) ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT
);
$multiRecordFieldListing = FALSE;
- //using selector for listing of multirecord fields
+ //using selector for listing of multi-record fields
if ($this->_mode == self::MODE_EDIT && $this->_gid) {
CRM_Core_BAO_UFGroup::shiftMultiRecordFields($this->_fields, $this->_multiRecordFields);
@@ -330,17 +425,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'];
@@ -357,7 +452,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');
}
}
}
@@ -370,13 +465,13 @@ 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');
- //multirecord listing page
+ //multi-record listing page
$multiRecordFieldListing = TRUE;
$page = new CRM_Profile_Page_MultipleRecordFieldsListing();
$cs = $this->get('cs');
@@ -428,11 +523,9 @@ public function preProcess() {
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
*/
public function setDefaultsValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
return;
}
@@ -444,7 +537,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;
@@ -470,7 +563,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) {
@@ -507,15 +600,20 @@ public function setDefaultsValues() {
) {
$entityId = $this->_activityId;
}
- $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key);
+
+ $url = '';
+ if (isset($value)) {
+ $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key, $value);
+ }
if ($url) {
$customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
$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";
@@ -554,8 +652,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";
@@ -577,31 +676,16 @@ public function setDefaultsValues() {
}
if (!empty($this->_defaults['image_URL'])) {
- list($imageWidth, $imageHeight) = getimagesize(CRM_Utils_String::unstupifyUrl($this->_defaults['image_URL']));
- list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
- $this->assign("imageWidth", $imageWidth);
- $this->assign("imageHeight", $imageHeight);
- $this->assign("imageThumbWidth", $imageThumbWidth);
- $this->assign("imageThumbHeight", $imageThumbHeight);
- $this->assign("imageURL", $this->_defaults['image_URL']);
+ $this->assign("imageURL", CRM_Utils_File::getImageURL($this->_defaults['image_URL']));
$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);
}
/**
* Build the form object.
*
- * @return void
*/
public function buildQuickForm() {
$this->add('hidden', 'gid', $this->_gid);
@@ -629,7 +713,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);
@@ -679,7 +763,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]);
}
}
}
@@ -687,7 +771,7 @@ public function buildQuickForm() {
if (
in_array(
$profileType,
- array("Membership", "Participant", "Contribution")
+ ["Membership", "Participant", "Contribution"]
)
) {
$return = TRUE;
@@ -713,7 +797,7 @@ public function buildQuickForm() {
$admin = TRUE;
if ($this->_mode == self::MODE_EDIT) {
$admin = FALSE;
- // show all fields that are visibile:
+ // show all fields that are visible:
// if we are a admin OR the same user OR acl-user with access to the profile
// or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
if (
@@ -743,7 +827,7 @@ public function buildQuickForm() {
}
$this->assign('anonUser', $anonUser);
- $addCaptcha = array();
+ $addCaptcha = [];
$emailPresent = FALSE;
// add the form elements
@@ -857,18 +941,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;
}
@@ -881,7 +965,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;
@@ -903,16 +987,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;
}
@@ -920,7 +1009,7 @@ public static function formRule($fields, $files, $form) {
$register = TRUE;
}
- // dont check for duplicates during registration validation: CRM-375
+ // don't check for duplicates during registration validation: CRM-375
if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
// fix for CRM-3240
if (!empty($fields['email-Primary'])) {
@@ -932,96 +1021,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';
- }
- $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $ctype);
- 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'));
- }
-
- // for dialog mode we should always use fuzzy rule.
- $ruleType = 'Unsupervised';
- if ($form->_context == 'dialog') {
- $ruleType = 'Supervised';
- }
-
- $dedupeParams['check_permission'] = FALSE;
- $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams,
- $ctype,
- $ruleType,
- $exceptions,
- $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);
}
}
@@ -1067,10 +1068,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))]
);
}
}
@@ -1082,8 +1083,6 @@ public static function formRule($fields, $files, $form) {
/**
* Process the user submitted custom data values.
*
- *
- * @return void
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
@@ -1092,15 +1091,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');
}
@@ -1113,13 +1112,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
@@ -1156,7 +1155,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) {
@@ -1166,18 +1165,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;
@@ -1222,13 +1221,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;
@@ -1261,7 +1260,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])) {
@@ -1308,7 +1307,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;
}
@@ -1371,9 +1370,6 @@ public function checkTemplateFileExists($suffix = NULL) {
*
* @return string
*/
- /**
- * @return string
- */
public function getTemplateFileName() {
$fileName = $this->checkTemplateFileExists();
return $fileName ? $fileName : parent::getTemplateFileName();
@@ -1385,9 +1381,6 @@ public function getTemplateFileName() {
*
* @return string
*/
- /**
- * @return string
- */
public function overrideExtraTemplateFileName() {
$fileName = $this->checkTemplateFileExists('extra.');
return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
diff --git a/CRM/Profile/Form/Dynamic.php b/CRM/Profile/Form/Dynamic.php
index 9c3f20019d94..c1e6c50ac595 100644
--- a/CRM/Profile/Form/Dynamic.php
+++ b/CRM/Profile/Form/Dynamic.php
@@ -1,9 +1,9 @@
get('register')) {
@@ -71,22 +69,21 @@ public function preProcess() {
/**
* Build the form object.
*
- * @return void
*/
public function buildQuickForm() {
- $this->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);
}
/**
@@ -103,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'])) {
@@ -115,9 +112,6 @@ public static function formRule($fields, $files, $form) {
/**
* Process the user submitted custom data values.
- *
- *
- * @return void
*/
public function postProcess() {
parent::postProcess();
diff --git a/CRM/Profile/Form/Edit.php b/CRM/Profile/Form/Edit.php
index dd9e1c5f5328..c5d493bacf88 100644
--- a/CRM/Profile/Form/Edit.php
+++ b/CRM/Profile/Form/Edit.php
@@ -1,9 +1,9 @@
_mode = CRM_Profile_Form::MODE_CREATE;
@@ -63,7 +62,7 @@ public function preProcess() {
$this->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);
@@ -71,6 +70,9 @@ public function preProcess() {
//set the prefix
$this->_prefix = CRM_Utils_Request::retrieve('prefix', 'String', $this);
+ // Fields for the EntityRef widget
+ $this->returnExtra = CRM_Utils_Request::retrieve('returnExtra', 'String', $this);
+
$this->assign('context', $this->_context);
if ($this->_blockNo) {
@@ -86,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);
@@ -98,8 +99,9 @@ public function preProcess() {
if ($id != $userID) {
// do not allow edit for anon users in joomla frontend, CRM-4668, unless u have checksum CRM-5228
+ // see also CRM-19079 for modifications to the condition
$config = CRM_Core_Config::singleton();
- if ($config->userFrameworkFrontend) {
+ if ($config->userFrameworkFrontend && $config->userSystem->is_joomla) {
CRM_Contact_BAO_Contact_Permission::validateOnlyChecksum($id, $this);
}
else {
@@ -126,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;
@@ -140,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]
));
}
}
@@ -148,7 +150,6 @@ public function preProcess() {
/**
* Build the form object.
*
- * @return void
*/
public function buildQuickForm() {
if (empty($this->_ufGroup['id'])) {
@@ -219,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;
@@ -238,29 +242,35 @@ 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);
}
/**
* Process the user submitted custom data values.
*
- *
- * @return void
*/
public function postProcess() {
parent::postProcess();
- $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name');
- $sortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'sort_name');
- $this->ajaxResponse['label'] = $sortName;
+ // Send back data for the EntityRef widget
+ if ($this->returnExtra) {
+ $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);
+ }
+ }
// When saving (not deleting) and not in an ajax popup
if (empty($_POST[$this->_deleteButtonName]) && $this->_context != 'dialog') {
@@ -291,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 b14e2f159a1e..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 9b0dfd1b9ac8..8f9d42e64cfb 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');
@@ -177,7 +178,6 @@ public function &actionLinks() {
* This method is called after the page is created. It checks for the
* type of action and executes that action.
*
- * @return void
*/
public function run() {
$template = CRM_Core_Smarty::singleton();
@@ -239,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,
@@ -271,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') {
@@ -289,7 +289,7 @@ public function run() {
$activityFields,
$values,
TRUE,
- array(array('activity_id', '=', $this->_activityId, 0, 0))
+ [['activity_id', '=', $this->_activityId, 0, 0]]
);
}
}
@@ -314,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
@@ -332,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);
@@ -353,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 {
@@ -377,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
@@ -416,9 +416,6 @@ public function checkTemplateFileExists($suffix = '') {
*
* @return string
*/
- /**
- * @return string
- */
public function getTemplateFileName() {
$fileName = $this->checkTemplateFileExists();
return $fileName ? $fileName : parent::getTemplateFileName();
@@ -430,9 +427,6 @@ public function getTemplateFileName() {
*
* @return string
*/
- /**
- * @return string
- */
public function overrideExtraTemplateFileName() {
$fileName = $this->checkTemplateFileExists('extra.');
return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
diff --git a/CRM/Profile/Page/Listings.php b/CRM/Profile/Page/Listings.php
index 3bc3e8d9b048..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',
@@ -155,22 +154,22 @@ 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['from'] = $from;
- $value['to'] = $to;
+ $value[$name . '_from'] = $from;
+ $value[$name . '_to'] = $to;
}
elseif ($from) {
- $value['from'] = $from;
+ $value[$name . '_from'] = $from;
}
elseif ($to) {
- $value['to'] = $to;
+ $value[$name . '_to'] = $to;
}
}
elseif ((substr($name, 0, 7) == 'custom_') &&
@@ -216,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;
}
@@ -228,9 +227,9 @@ 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 dont see any value
+ // only reset on a POST submission if we don't see any value
$value = NULL;
$this->set($name, $value);
}
@@ -249,13 +248,18 @@ public function preProcess() {
if ($operator) {
$this->_params[$name . '_operator'] = $operator;
}
- $this->_params[$name] = $this->_fields[$name]['value'] = $value;
+ if ((substr($name, 0, 6) == 'custom') && !empty($field['is_search_range'])) {
+ $this->_params += $value;
+ }
+ else {
+ $this->_params[$name] = $this->_fields[$name]['value'] = $value;
+ }
}
}
// set the prox params
// need to ensure proximity searching is enabled
- $proximityVars = array(
+ $proximityVars = [
'street_address',
'city',
'postal_code',
@@ -263,7 +267,7 @@ public function preProcess() {
'country_id',
'distance',
'distance_unit',
- );
+ ];
foreach ($proximityVars as $var) {
$value = CRM_Utils_Request::retrieve("prox_{$var}",
'String',
@@ -282,7 +286,6 @@ public function preProcess() {
/**
* Run this page (figure out the action needed and perform it).
*
- * @return void
*/
public function run() {
$this->preProcess();
@@ -396,7 +399,7 @@ public function run() {
$controller->run();
}
- //CRM-6862 -run form cotroller after
+ //CRM-6862 -run form controller after
//selector, since it erase $_POST
$formController->run();
@@ -414,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
@@ -431,7 +434,7 @@ public static function getProfileContact($gid) {
$params['group'][$groupId] = 1;
}
else {
- $params['group'] = array($groupId => 1);
+ $params['group'] = [$groupId => 1];
}
}
@@ -492,9 +495,6 @@ public function checkTemplateFileExists($suffix = '') {
*
* @return string
*/
- /**
- * @return string
- */
public function getTemplateFileName() {
$fileName = $this->checkTemplateFileExists();
return $fileName ? $fileName : parent::getTemplateFileName();
@@ -506,9 +506,6 @@ public function getTemplateFileName() {
*
* @return string
*/
- /**
- * @return string
- */
public function overrideExtraTemplateFileName() {
$fileName = $this->checkTemplateFileExists('extra.');
return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
diff --git a/CRM/Profile/Page/MultipleRecordFieldsListing.php b/CRM/Profile/Page/MultipleRecordFieldsListing.php
index d973c27f5f3e..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') {
@@ -109,7 +108,7 @@ public function &links() {
elseif ($this->_pageViewType == 'customDataView') {
// custom data specific view links
$links[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/view/cd';
- $links[CRM_Core_Action::VIEW]['qs'] = 'reset=1&gid=%%gid%%&cid=%%cid%%&recId=%%recId%%&multiRecordDisplay=single&mode=view';
+ $links[CRM_Core_Action::VIEW]['qs'] = 'reset=1&gid=%%gid%%&cid=%%cid%%&recId=%%recId%%&cgcount=%%cgcount%%&multiRecordDisplay=single&mode=view';
// custom data specific update links
$links[CRM_Core_Action::UPDATE]['url'] = 'civicrm/contact/view/cd/edit';
@@ -117,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;
@@ -137,7 +136,6 @@ public function &links() {
* of action and executes that action. Finally it calls the parent's run
* method.
*
- * @return void
*/
public function run() {
// get the requested action, default to 'browse'
@@ -166,12 +164,11 @@ public function run() {
/**
* Browse the listing.
*
- * @return void
*/
public function browse() {
$dateFields = NULL;
- $cgcount = 0;
- $attributes = $headerAttr = array();
+ $newCgCount = $cgcount = 0;
+ $attributes = $result = $headerAttr = [];
$dateFieldsVals = NULL;
if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
$fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL,
@@ -181,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);
@@ -202,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);
@@ -219,9 +216,9 @@ public function browse() {
// from the above customGroupInfo we can get $this->_customGroupTitle
$this->_customGroupTitle = $groupDetail[$customGroupId]['title'];
}
- if ($fieldIDs && !empty($fieldIDs) && $this->_contactId) {
- $options = array();
- $returnProperities = array(
+ if (!empty($fieldIDs) && $this->_contactId) {
+ $options = [];
+ $returnProperities = [
'html_type',
'data_type',
'date_format',
@@ -229,15 +226,15 @@ 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;
- $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
+ $actualPHPFormats = CRM_Utils_Date::datePluginToPHPFormats();
$dateFormat = (array) CRM_Utils_Array::value($returnValues['date_format'], $actualPHPFormats);
$timeFormat = CRM_Utils_Array::value('time_format', $returnValues);
}
@@ -259,12 +256,15 @@ public function browse() {
= $options[$fieldIDs[$key]]['attributes']['date_format'] = CRM_Utils_Array::value('date_format', $returnValues);
$options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
}
+ $linkAction = array_sum(array_keys($this->links()));
+ }
+ if (!empty($fieldIDs) && $this->_contactId) {
$DTparams = !empty($this->_DTparams) ? $this->_DTparams : NULL;
// 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,16 +279,17 @@ 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);
$this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
}
- // $cgcount is defined before 'if' condition as enitiy may have no record
+ // $cgcount is defined before 'if' condition as entity may have no record
// and $cgcount is used to build new record url
$cgcount = 1;
- if ($result && !empty($result)) {
+ $newCgCount = (!$reached) ? $resultCount + 1 : NULL;
+ if (!empty($result) && empty($this->_headersOnly)) {
$links = self::links();
if ($this->_pageViewType == 'profileDataView') {
$pageCheckSum = $this->get('pageCheckSum');
@@ -298,12 +299,10 @@ public function browse() {
}
}
}
- $linkAction = array_sum(array_keys($this->links()));
if ($reached) {
unset($links[CRM_Core_Action::COPY]);
}
- $newCgCount = (!$reached) ? $resultCount + 1 : NULL;
if (!empty($DTparams)) {
$this->_total = $resultCount;
$cgcount = $DTparams['offset'] + 1;
@@ -340,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;
@@ -376,16 +375,14 @@ 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 {
- $headerAttr[$fieldId]['dataType'] = CRM_Utils_Array::value('data-type', $fieldAttributes);
- $headerAttr[$fieldId]['dataEmptyOption'] = CRM_Utils_Array::value('data-empty-option', $fieldAttributes);
// different set of url params
$actionParams['gid'] = $actionParams['groupID'] = $this->_customGroupId;
$actionParams['cid'] = $actionParams['entityID'] = $this->_contactId;
@@ -395,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';
@@ -426,16 +423,36 @@ public function browse() {
}
}
- $headers = array();
+ $headers = [];
if (!empty($fieldIDs)) {
+ $fields = ['Radio', 'Select', 'Select Country', 'Select State/Province'];
foreach ($fieldIDs as $fieldID) {
- $headers[$fieldID] = ($this->_pageViewType == 'profileDataView') ? $customGroupInfo[$fieldID]['fieldLabel'] : $fieldLabels[$fieldID]['label'];
- $headerAttr[$fieldID]['columnName'] = $fieldLabels[$fieldID]['column_name'];
+ if ($this->_pageViewType == 'profileDataView') {
+ $headers[$fieldID] = $customGroupInfo[$fieldID]['fieldLabel'];
+ }
+ elseif (!empty($this->_headersOnly)) {
+ if (!$options[$fieldID]['attributes']['is_view'] && $linkAction & CRM_Core_Action::UPDATE) {
+ $spec = $options[$fieldID]['attributes'];
+
+ if (in_array($spec['html_type'], $fields)) {
+ $headerAttr[$fieldID]['dataType'] = $spec['data_type'] == 'Boolean' ? 'boolean' : 'select';
+ if (!$spec['is_required']) {
+ $headerAttr[$fieldID]['dataEmptyOption'] = ts('- none -');
+ }
+ }
+ elseif ($spec['html_type'] == 'TextArea') {
+ $headerAttr[$fieldID]['dataType'] = 'textarea';
+ }
+ }
+ $headers[$fieldID] = $fieldLabels[$fieldID]['label'];
+ $headerAttr[$fieldID]['columnName'] = $fieldLabels[$fieldID]['column_name'];
+ }
}
}
$this->assign('dateFields', $dateFields);
$this->assign('dateFieldsVals', $dateFieldsVals);
$this->assign('cgcount', $cgcount);
+ $this->assign('newCgCount', $newCgCount);
$this->assign('contactId', $this->_contactId);
$this->assign('contactType', $this->_contactType);
$this->assign('customGroupTitle', $this->_customGroupTitle);
@@ -444,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 18198983d012..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 89d8f798faad..593d656d4110 100644
--- a/CRM/Profile/Page/View.php
+++ b/CRM/Profile/Page/View.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive',
@@ -74,7 +72,7 @@ public function preProcess() {
$gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0, 'GET'));
- $profileIds = array();
+ $profileIds = [];
if (count($gids) > 1) {
if (!empty($gids)) {
foreach ($gids as $pfId) {
@@ -97,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'])) {
@@ -132,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'])) {
@@ -163,9 +161,8 @@ public function preProcess() {
}
/**
- * Build the outcome basing on the CRM_Profile_Page_Dynamic's HTML
+ * Build the outcome basing on the CRM_Profile_Page_Dynamic's HTML.
*
- * @return void
*/
public function run() {
$this->preProcess();
@@ -202,9 +199,6 @@ public function checkTemplateFileExists($suffix = '') {
*
* @return string
*/
- /**
- * @return string
- */
public function getTemplateFileName() {
$fileName = $this->checkTemplateFileExists();
return $fileName ? $fileName : parent::getTemplateFileName();
@@ -216,9 +210,6 @@ public function getTemplateFileName() {
*
* @return string
*/
- /**
- * @return string
- */
public function overrideExtraTemplateFileName() {
$fileName = $this->checkTemplateFileExists('extra.');
return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
diff --git a/CRM/Profile/Selector/Listings.php b/CRM/Profile/Selector/Listings.php
index 9c3611b658ca..ac36108f2a2b 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;
}
@@ -174,7 +173,7 @@ public function __construct(
$this->_params['group'][$groupId] = 1;
}
else {
- $this->_params['group'] = array($groupId => 1);
+ $this->_params['group'] = [$groupId => 1];
}
}
@@ -213,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) {
@@ -228,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;
@@ -295,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');
@@ -336,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`";
}
@@ -357,25 +356,25 @@ 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;
}
}
- // if we dont have any valid columns, dont add the implicit ones
+ // 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;
@@ -445,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']);
@@ -496,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) {
@@ -504,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;
}
}
@@ -516,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
@@ -549,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}";
}
@@ -578,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";
@@ -595,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,
@@ -636,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];
@@ -661,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)) {
@@ -688,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) {
@@ -792,7 +791,7 @@ public function setMultiRecordTableName($fields) {
}
//if the field is in selector and not a searchable field
- //get the proper customvalue table name
+ //get the proper custom value table name
if ($selectorSet) {
$this->_multiRecordTableName
= $multiRecordTableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
diff --git a/CRM/Queue/BAO/QueueItem.php b/CRM/Queue/BAO/QueueItem.php
index 25c0e664199c..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,
- ) ,
- 'queue_name' => array(
+ 'title' => ts('Queue ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_queue_item',
+ 'entity' => 'QueueItem',
+ 'bao' => 'CRM_Queue_BAO_QueueItem',
+ 'localizable' => 0,
+ ],
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_queue_item',
+ 'entity' => 'QueueItem',
+ 'bao' => 'CRM_Queue_BAO_QueueItem',
+ 'localizable' => 0,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'required' => true,
- 'html' => array(
+ 'title' => ts('Order'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_queue_item',
+ 'entity' => 'QueueItem',
+ 'bao' => 'CRM_Queue_BAO_QueueItem',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'title' => ts('Submit Time'),
+ 'description' => ts('date on which this item was submitted to the queue'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_queue_item',
+ 'entity' => 'QueueItem',
+ 'bao' => 'CRM_Queue_BAO_QueueItem',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('Release Time'),
+ 'description' => ts('date on which this job becomes available; null if ASAP'),
+ 'table_name' => 'civicrm_queue_item',
+ 'entity' => 'QueueItem',
+ 'bao' => 'CRM_Queue_BAO_QueueItem',
+ 'localizable' => 0,
+ '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'),
+ '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
*
@@ -191,10 +203,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
*
@@ -202,8 +215,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 = [
+ 'index_queueids' => [
+ 'name' => 'index_queueids',
+ 'field' => [
+ 0 => 'queue_name',
+ 1 => 'weight',
+ 2 => 'id',
+ ],
+ '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 0fbea745cef3..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 7ae1605849a5..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 75f8ef3c68cf..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 709638303b62..6be0e23aa275 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'],
+ ]);
}
/**
@@ -133,9 +133,9 @@ public function claimItem($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 (is_a($dao, 'DB_Error')) {
// FIXME - Adding code to allow tests to pass
@@ -145,10 +145,10 @@ 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'),
- ));
+ 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'],
+ ]);
// 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);
@@ -156,14 +156,6 @@ public function claimItem($lease_time = 3600) {
$dao->data = unserialize($dao->data);
return $dao;
}
- else {
- CRM_Core_Error::debug_var('not ready for release', $dao);
- return FALSE;
- }
- }
- else {
- CRM_Core_Error::debug_var('no items found');
- return FALSE;
}
}
@@ -184,23 +176,19 @@ 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;
}
- else {
- CRM_Core_Error::debug_var('no items found');
- return FALSE;
- }
}
/**
@@ -222,9 +210,9 @@ 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 8d0c3fc208c8..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 84501b8c398b..abb0738f850f 100644
--- a/CRM/Queue/Service.php
+++ b/CRM/Queue/Service.php
@@ -1,9 +1,9 @@
queues = array();
+ $this->queues = [];
}
/**
diff --git a/CRM/Queue/Task.php b/CRM/Queue/Task.php
index 666dfd14b8bf..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 0bcfbe1ad5bb..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;
}
@@ -364,32 +363,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 1cd6fec1104f..bd2d42c3ef4d 100644
--- a/CRM/Report/DAO/ReportInstance.php
+++ b/CRM/Report/DAO/ReportInstance.php
@@ -1,461 +1,551 @@
__table = 'civicrm_report_instance';
parent::__construct();
}
+
/**
- * Returns foreign keys and entity references
+ * 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,
- ) ,
- 'domain_id' => array(
+ 'title' => ts('Report Instance ID'),
+ 'description' => ts('Report Instance ID'),
+ 'required' => TRUE,
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ ],
+ '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,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ '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,
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- ) ,
- 'is_active' => array(
+ 'export' => TRUE,
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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?',
- 'html' => array(
+ 'title' => ts('Report Instance is Active'),
+ 'description' => ts('Is this entry active?'),
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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.'),
+ '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.'),
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('Email Report Instance To'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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',
- 'html' => array(
+ 'title' => ts('cc Email Report Instance To'),
+ 'description' => ts('comma-separated list of email addresses to send the report to'),
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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,
- 'html' => array(
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ 'localizable' => 0,
+ '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') ,
- 'html' => array(
+ 'title' => ts('Instance is Reserved'),
+ 'default' => '0',
+ 'table_name' => 'civicrm_report_instance',
+ 'entity' => 'ReportInstance',
+ 'bao' => 'CRM_Report_BAO_ReportInstance',
+ '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 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
*
@@ -463,10 +553,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
*
@@ -474,8 +565,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 = [];
+ 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 043092cd46b4..a136d9ef6c8b 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_OptionGroup::getValue('activity_type', 'Inbound SMS', 'name'); - + 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 897cac2662b5..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 new file mode 100644 index 000000000000..14b4adb6e124 --- /dev/null +++ b/CRM/Tag/Form/Edit.php @@ -0,0 +1,242 @@ +set('BAOName', 'CRM_Core_BAO_Tag'); + parent::preProcess(); + } + + /** + * Build the form object. + */ + public function buildQuickForm() { + $bounceUrl = CRM_Utils_System::url('civicrm/tag'); + if ($this->_action == CRM_Core_Action::DELETE) { + 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."), $bounceUrl); + } + foreach ($this->_id as $id) { + if (!CRM_Utils_Rule::positiveInteger($id)) { + 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.", [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."), $bounceUrl); + } + } + if (count($this->_id) > 1) { + $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 && + CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $this->_id, 'is_tagset') + ) { + $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'); + } + else { + $parentId = CRM_Utils_Request::retrieve('parent_id', 'Integer', $this); + } + $isTagSetChild = $parentId ? CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $parentId, 'is_tagset') : FALSE; + + 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, ['placeholder' => ts('- select -')]); + } + + // Tagsets are not selectable by definition so only include the selectable field if NOT a tagset. + $selectable = $this->add('checkbox', 'is_selectable', ts('Selectable?')); + // Selectable should be checked by default when creating a new tag + if ($this->_action == CRM_Core_Action::ADD) { + $selectable->setValue(1); + } + + $this->add('color', 'color', ts('Color')); + } + + $this->assign('isTagSet', $this->_isTagSet); + + $this->applyFilter('__ALL__', 'trim'); + + $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', [ + 'CRM_Core_DAO_Tag', + $this->_id, + ]); + + $this->add('text', 'description', ts('Description'), + CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'description') + ); + + $isReserved = $this->add('checkbox', 'is_reserved', ts('Reserved?')); + + if (!$isTagSetChild) { + $this->addSelect('used_for', ['multiple' => TRUE, 'option_url' => NULL]); + } + + $this->assign('adminTagset', $adminTagset); + + if (!$adminReservedTags) { + $isReserved->freeze(); + } + $this->assign('adminReservedTags', $adminReservedTags); + } + $this->setPageTitle($this->_isTagSet ? ts('Tag Set') : ts('Tag')); + parent::buildQuickForm(); + } + + /** + * Set default values for the form. + * + * @return array + */ + public function setDefaultValues() { + $defaults = parent::setDefaultValues(); + $cloneFrom = CRM_Utils_Request::retrieve('clone_from', 'Integer'); + if (empty($this->_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'])) { + $defaults['color'] = '#ffffff'; + } + if (empty($this->_id) && empty($defaults['used_for'])) { + $defaults['used_for'] = 'civicrm_contact'; + } + return $defaults; + } + + /** + * Process the form submission. + */ + public function postProcess() { + if ($this->_action == CRM_Core_Action::DELETE) { + $deleted = 0; + $tag = civicrm_api3('tag', 'getsingle', ['id' => $this->_id[0]]); + foreach ($this->_id as $id) { + if (CRM_Core_BAO_Tag::del($id)) { + $deleted++; + } + } + if (count($this->_id) == 1 && $deleted == 1) { + if ($tag['is_tagset']) { + 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.", [1 => $tag['name']]), ts('Deleted'), 'success'); + } + } + else { + CRM_Core_Session::setStatus(ts("Deleted %1 tags.", [1 => $deleted]), ts('Deleted'), 'success'); + } + } + else { + $params = $this->exportValues(); + if ($this->_id) { + $params['id'] = $this->_id; + } + + if (isset($params['used_for']) && ($this->_action == CRM_Core_Action::ADD || $this->_action == CRM_Core_Action::UPDATE)) { + $params['used_for'] = implode(",", $params['used_for']); + } + + $params['is_tagset'] = 0; + if ($this->_isTagSet) { + $params['is_tagset'] = 1; + } + + if (!isset($params['is_reserved'])) { + $params['is_reserved'] = 0; + } + + if (!isset($params['parent_id']) && $this->get('parent_id')) { + $params['parent_id'] = $this->get('parent_id'); + } + if (empty($params['parent_id'])) { + $params['parent_id'] = ''; + } + + if (!isset($params['is_selectable'])) { + $params['is_selectable'] = 0; + } + $tag = CRM_Core_BAO_Tag::add($params); + 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 new file mode 100644 index 000000000000..67ef526fb430 --- /dev/null +++ b/CRM/Tag/Form/Merge.php @@ -0,0 +1,125 @@ +_id = CRM_Utils_Request::retrieve('id', 'String', $this, FALSE); + $this->_id = explode(',', $this->_id); + $url = CRM_Utils_System::url('civicrm/tag'); + if (count($this->_id) < 2) { + CRM_Core_Error::statusBounce(ts("You must select at least 2 tags for merging."), $url); + } + $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); + } + if (!CRM_Core_Permission::check('administer reserved tags')) { + foreach ($tags['values'] as $tag) { + if (!empty($tag['is_reserved'])) { + CRM_Core_Error::statusBounce(ts("You do not have permission to administer reserved tags."), $url); + } + } + } + } + + /** + * Build the form object. + */ + 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([ + [ + 'type' => 'next', + 'name' => ts('Merge'), + 'spacing' => ' ', + 'isDefault' => TRUE, + ], + [ + 'type' => 'cancel', + 'name' => ts('Cancel'), + ], + ]); + } + + /** + * Set default values for the form. + * + * @return array + */ + public function setDefaultValues() { + $primary = CRM_Utils_Array::first($this->_tags); + return [ + 'name' => $primary['name'], + ]; + } + + /** + * Process the form submission. + */ + public function postProcess() { + $params = $this->exportValues(); + $deleted = CRM_Utils_Array::collect('name', $this->_tags); + $primary = array_shift($this->_tags); + + foreach ($this->_tags as $tag) { + CRM_Core_BAO_EntityTag::mergeTags($primary['id'], $tag['id']); + } + + if ($params['name'] != $primary['name']) { + civicrm_api3('Tag', 'create', ['id' => $primary['id'], 'name' => $params['name']]); + } + + $key = array_search($params['name'], $deleted); + if ($key !== FALSE) { + unset($deleted[$key]); + } + + CRM_Core_Session::setStatus( + 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' + ); + + CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/tag')); + } + +} diff --git a/CRM/Tag/Form/Tag.php b/CRM/Tag/Form/Tag.php index a786ebe19ff9..27e5048e21b4 100644 --- a/CRM/Tag/Form/Tag.php +++ b/CRM/Tag/Form/Tag.php @@ -1,9 +1,9 @@ assign('tagged', $entityTag); // get the list of all the categories - $allTag = CRM_Core_BAO_Tag::getTagsUsedFor($this->_entityTable); + $allTags = CRM_Core_BAO_Tag::getTagsUsedFor($this->_entityTable, FALSE); // need to append the array with the " checked " if contact is tagged with the tag - foreach ($allTag as $tagID => $varValue) { + foreach ($allTags as $tagID => $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); @@ -99,20 +99,9 @@ public function buildQuickForm() { $tags = new CRM_Core_BAO_Tag(); $tree = $tags->getTree($this->_entityTable, TRUE); - - // let's not load jstree if there are not children. This also fixes blank - // display at the beginning of checkboxes - $loadJsTree = CRM_Utils_Array::retrieveValueRecursive($tree, 'children'); - $this->assign('loadjsTree', FALSE); - if (!empty($loadJsTree)) { - CRM_Core_Resources::singleton() - ->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE) - ->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header'); - $this->assign('loadjsTree', TRUE); - } $this->assign('tree', $tree); - $this->assign('tag', $allTag); + $this->assign('allTags', $allTags); //build tag widget $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_contact'); @@ -124,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 new file mode 100644 index 000000000000..11d899a511f9 --- /dev/null +++ b/CRM/Tag/Page/Tag.php @@ -0,0 +1,79 @@ +addScriptFile('civicrm', 'bower_components/jstree/dist/jstree.min.js', 0, 'html-header') + ->addStyleFile('civicrm', 'bower_components/jstree/dist/themes/default/style.min.css') + ->addPermissions(['administer reserved tags', 'administer Tagsets']); + + $usedFor = $tagsets = []; + + $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', [ + 'return' => ["name", "used_for", "description", "created_id.display_name", "created_date", "is_reserved"], + 'is_tagset' => 1, + '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))); + if (isset($tagset['created_id.display_name'])) { + $tagset['display_name'] = $tagset['created_id.display_name']; + } + unset($tagset['created_id.display_name']); + $tagsets[$id] = $tagset; + } + + $this->assign('usedFor', $usedFor); + $this->assign('tagsets', $tagsets); + + return parent::run(); + } + +} diff --git a/CRM/UF/Form/AbstractPreview.php b/CRM/UF/Form/AbstractPreview.php index 4d3d182f350f..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 0239efe4b64e..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); @@ -55,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 @@ -75,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(); @@ -84,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 4e2a27168ef5..9086dfc0b17f 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', @@ -108,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, @@ -122,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); } } @@ -147,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(); @@ -184,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 6b3b2e068daf..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 b0269cec2a73..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 5681fc884c48..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 = []; + foreach ($columns as $fieldName) { + $prefixedFieldNames[] = "$tableAlias.$fieldName"; + } + + $clauses[] = sprintf("MATCH (%s) AGAINST ('%s' IN BOOLEAN MODE)", + implode(',', $prefixedFieldNames), + $strtolower(CRM_Core_DAO::escapeString($formattedQuery)) + ); + } + else { + //CRM_Core_Session::setStatus(ts('Cannot use FTS for %1 (%2)', array( + // 1 => $table, + // 2 => implode(', ', $fullTextFields), + //))); + + $formattedQuery = $this->format($queryText, CRM_Utils_QueryFormatter::LANG_SQL_LIKE); + $escapedText = $strtolower(CRM_Core_DAO::escapeString($formattedQuery)); + foreach ($columns as $fieldName) { + $clauses[] = "$tableAlias.$fieldName LIKE '{$escapedText}'"; + } + } + return implode(' OR ', $clauses); + } + /** * Format Fts. * @@ -211,6 +290,20 @@ protected function _formatFts($text, $mode) { */ protected function _formatFtsBool($text, $mode) { $result = NULL; + $operators = ['+', '-', '~', '(', ')']; + $wildCards = ['@', '%', '*']; + $expression = preg_quote(implode('', array_merge($operators, $wildCards)), '/'); + + //Return if searched string ends with an unsupported operator. + //Or if the string contains an invalid joint occurrence of operators. + foreach ($operators as $val) { + if ($text == '@' || CRM_Utils_String::endsWith($text, $val) || preg_match("/[{$expression}]{2,}/", $text)) { + $csid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'CRM_Contact_Form_Search_Custom_FullText', 'value', 'name'); + $url = CRM_Utils_System::url("civicrm/contact/search/custom", "csid={$csid}&reset=1"); + $operators = implode("', '", $operators); + CRM_Core_Error::statusBounce("Full-Text Search does not support the use of a search with two attached operators or string ending with any of these operators ('{$operators}' or a single '@'). Please adjust your search term and try again.", $url, 'Invalid Search String'); + } + } // normalize user-inputted wildcards $text = str_replace('%', '*', $text); @@ -233,7 +326,7 @@ protected function _formatFtsBool($text, $mode) { else { switch ($mode) { case self::MODE_NONE: - $result = $this->mapWords($text, '+word'); + $result = $this->mapWords($text, '+word', TRUE); break; case self::MODE_PHRASE: @@ -304,22 +397,45 @@ protected function _formatLike($text, $mode) { * User-supplied query string. * @param string $template * A prototypical description of each word, eg "word%" or "word*" or "*word*". + * @param bool $quotes + * True if each searched keyword need to be surrounded with quotes. * @return string */ - protected function mapWords($text, $template) { - $result = array(); - foreach ($this->parseWords($text) as $word) { + protected function mapWords($text, $template, $quotes = FALSE) { + $result = []; + foreach ($this->parseWords($text, $quotes) as $word) { $result[] = str_replace('word', $word, $template); } return implode(' ', $result); } /** - * @param $text + * @param string $text + * @param bool $quotes * @return array */ - protected function parseWords($text) { - return explode(' ', preg_replace('/[ \r\n\t]+/', ' ', trim($text))); + protected function parseWords($text, $quotes) { + //NYSS 9692 special handling for emails + if (preg_match('/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/', $text)) { + $parts = explode('@', $text); + $parts[1] = stristr($parts[1], '.', TRUE); + $text = implode(' ', $parts); + } + + //NYSS also replace other occurrences of @ + $replacedText = preg_replace('/[ \r\n\t\@]+/', ' ', trim($text)); + //filter empty values if any + $keywords = array_filter(explode(' ', $replacedText)); + + //Ensure each searched keywords are wrapped in double quotes. + if ($quotes) { + foreach ($keywords as &$val) { + if (!is_numeric($val)) { + $val = "\"{$val}\""; + } + } + } + return $keywords; } /** @@ -345,13 +461,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, - ); + ]; } /** @@ -360,12 +476,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 c6c05788cde3..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 41e5d8f68bea..31980430149b 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); diff --git a/CRM/Utils/Recent.php b/CRM/Utils/Recent.php index c596c7b8cb41..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 f5fd4b14b721..2f55cea32c37 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,63 @@ 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 + */ + 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 0ea7c32e3cc3..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); @@ -554,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; } /** @@ -694,7 +774,7 @@ public static function htmlFile($elementValue) { * @param string $value * The value of the field we are checking. * @param array $options - * The daoName and fieldName (optional ). + * The daoName, fieldName (optional) and DomainID (optional). * * @return bool * true if object exists @@ -705,7 +785,7 @@ public static function objectExists($value, $options) { $name = $options[2]; } - return CRM_Core_DAO::objectExists($value, CRM_Utils_Array::value(0, $options), CRM_Utils_Array::value(1, $options), CRM_Utils_Array::value(2, $options, $name)); + return CRM_Core_DAO::objectExists($value, CRM_Utils_Array::value(0, $options), CRM_Utils_Array::value(1, $options), CRM_Utils_Array::value(2, $options, $name), CRM_Utils_Array::value(3, $options)); } /** @@ -715,7 +795,7 @@ public static function objectExists($value, $options) { * @return bool */ public static function optionExists($value, $options) { - return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name')); + return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'), CRM_Utils_Array::value(4, $options, FALSE)); } /** @@ -725,7 +805,6 @@ public static function optionExists($value, $options) { * @return bool */ public static function creditCardNumber($value, $type) { - require_once 'Validate/Finance/CreditCard.php'; return Validate_Finance_CreditCard::number($value, $type); } @@ -736,8 +815,6 @@ public static function creditCardNumber($value, $type) { * @return bool */ public static function cvv($value, $type) { - require_once 'Validate/Finance/CreditCard.php'; - return Validate_Finance_CreditCard::cvv($value, $type); } @@ -773,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 * @@ -887,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 994c698bad75..8c7f4c693854 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,117 @@ 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; + } + + /** + * Is the Database set up to handle acceents. + * @warning This function was introduced in attempt to determine the reason why the test getInternationalStrings was failing on ubu1604 but passing on ubu1204-5 + * This function should not be used as the basis of further work as the reasoning is not perfact and is giving false failures. + * @return bool + */ + public static function supportStorageOfAccents() { + $charSetDB = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE 'character_set_database'")->fetchAll(); + $charSet = $charSetDB[0]['Value']; + if ($charSet == 'utf8') { + return TRUE; + } + return FALSE; + } + + /** + * 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..f48d05556c6d --- /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 (isset($args[$m[2]])) { + $values = $args[$m[2]]; + } + elseif (isset($args[$m[1] . $m[2]])) { + // 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, @@ -200,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); } @@ -274,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/README.md b/README.md new file mode 100644 index 000000000000..69835a0b75c5 --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +![](i/logo_lg.png) Welcome to CiviCRM +===================================== + +About +----- + +CiviCRM is a constituent relationship management system designed to +meet the needs of advocacy, non-profit and non-governmental groups. +It is an open source project, licensed under GNU AGPL 3, and +coordinated by CiviCRM LLC. The project website is https://civicrm.org/ + +CiviCRM is released as a module that runs within the Drupal, Joomla, +and WordPress content management systems. + + +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). + + +Documentation +------------- + +Documentation can be found at https://civicrm.org/documentation + + +Support +------- + +Answers for users, administrators & integrators: +http://civicrm.stackexchange.com + +Paid support available from +https://civicrm.org/providers + + +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). + +Report all issues to CiviCRM via GitLab: +https://lab.civicrm.org diff --git a/README.txt b/README.txt deleted file mode 100644 index 147b0df3ae82..000000000000 --- a/README.txt +++ /dev/null @@ -1,67 +0,0 @@ -************************* -README file for CiviCRM -************************* -1. About -2. Installation -3. Documentation -4. Support -5. Development - - - -************************* -1. About -************************* -CiviCRM is a constituent relationship management system designed to -meet the needs of advocacy, non-profit and non-governmental groups. -It is an open source project, licensed under GNU AGPL 3, and -coordinated by CiviCRM LLC. The project website is https://civicrm.org/ - -CiviCRM is released as a module that runs within the Drupal, Joomla, -and WordPress content management systems. - - -************************* -2. Installation -************************* -The download URLs and installation instructions are available on our -website: -https://civicrm.org/download - -Installation instruction can be found on the wiki: -http://wiki.civicrm.org/ - - -************************* -3. Documentation -************************* -Documentation, as well as the project bug tracker and mailing lists, -can be found at https://civicrm.org/ Just click on the appropriate link. - -Our main documentation site is the CiviCRM wiki: -http://wiki.civicrm.org/ - - -************************* -4. Support -************************* -Answers for users, administrators & integrators: -http://civicrm.stackexchange.com - -Paid support available from -https://civicrm.org/providers - - -************************* -5. Development -************************* -Developers are highly encouraged to join the CiviCRM forums and post -questions and ideas on the Developer Discussion board: -http://forum.civicrm.org/index.php/board,20.0.html - -Installing the latest developmental code requires some special steps. Full -instructions are on the wiki: -http://wiki.civicrm.org/confluence/display/CRMDOC/Contributing+to+CiviCRM+using+GitHub - -Report all issues to CiviCRM via JIRA: -https://issues.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/crmApp.ang.php b/ang/crmApp.ang.php new file mode 100644 index 000000000000..d4179315bd05 --- /dev/null +++ b/ang/crmApp.ang.php @@ -0,0 +1,9 @@ + 'civicrm', + 'js' => ['ang/crmApp.js'], +]; diff --git a/ang/crmApp.js b/ang/crmApp.js index 0726a045040c..c7bb81e29bc9 100644 --- a/ang/crmApp.js +++ b/ang/crmApp.js @@ -5,6 +5,16 @@ var crmApp = angular.module('crmApp', CRM.angular.modules); crmApp.config(['$routeProvider', function($routeProvider) { + + if (CRM.crmApp.defaultRoute) { + $routeProvider.when('/', { + template: '
', + controller: function($location) { + $location.path(CRM.crmApp.defaultRoute); + } + }); + } + $routeProvider.otherwise({ template: ts('Unknown path') }); diff --git a/ang/crmAttachment.ang.php b/ang/crmAttachment.ang.php new file mode 100644 index 000000000000..e278f75e32c7 --- /dev/null +++ b/ang/crmAttachment.ang.php @@ -0,0 +1,15 @@ + 'civicrm', + 'js' => ['ang/crmAttachment.js'], + 'css' => ['ang/crmAttachment.css'], + 'partials' => ['ang/crmAttachment'], + 'settings' => [ + 'token' => \CRM_Core_Page_AJAX_Attachment::createToken(), + ], + 'requires' => ['angularFileUpload', 'crmResource'], +]; diff --git a/ang/crmAttachment.js b/ang/crmAttachment.js index 35dd1c582fe2..b89fe4ca22ef 100644 --- a/ang/crmAttachment.js +++ b/ang/crmAttachment.js @@ -1,7 +1,7 @@ /// crmFile: Manage file attachments (function (angular, $, _) { - angular.module('crmAttachment', ['angularFileUpload']); + angular.module('crmAttachment', CRM.angRequires('crmAttachment')); // crmAttachment manages the list of files which are attached to a given entity angular.module('crmAttachment').factory('CrmAttachments', function (crmApi, crmStatus, FileUploader, $q) { diff --git a/ang/crmAutosave.ang.php b/ang/crmAutosave.ang.php new file mode 100644 index 000000000000..6f998782c709 --- /dev/null +++ b/ang/crmAutosave.ang.php @@ -0,0 +1,10 @@ + 'civicrm', + 'js' => ['ang/crmAutosave.js'], + 'requires' => ['crmUtil'], +]; diff --git a/ang/crmAutosave.js b/ang/crmAutosave.js index a697880b8f11..359ccfebac89 100644 --- a/ang/crmAutosave.js +++ b/ang/crmAutosave.js @@ -1,7 +1,7 @@ /// crmAutosave (function(angular, $, _) { - angular.module('crmAutosave', ['crmUtil']); + angular.module('crmAutosave', CRM.angRequires('crmAutosave')); // usage: // var autosave = new CrmAutosaveCtrl({ diff --git a/ang/crmCaseType.ang.php b/ang/crmCaseType.ang.php new file mode 100644 index 000000000000..21596810d419 --- /dev/null +++ b/ang/crmCaseType.ang.php @@ -0,0 +1,20 @@ +addSetting([ + 'crmCaseType' => [ + 'REL_TYPE_CNAME' => CRM_Case_XMLProcessor::REL_TYPE_CNAME, + ], +]); + +return [ + 'ext' => 'civicrm', + 'js' => ['ang/crmCaseType.js'], + 'css' => ['ang/crmCaseType.css'], + 'partials' => ['ang/crmCaseType'], + 'requires' => ['ngRoute', 'ui.utils', 'crmUi', 'unsavedChanges', 'crmUtil', 'crmResource'], +]; diff --git a/ang/crmCaseType.css b/ang/crmCaseType.css index fa8edc12723b..6352b3d24dc8 100644 --- a/ang/crmCaseType.css +++ b/ang/crmCaseType.css @@ -2,8 +2,14 @@ vertical-align: middle; cursor: move; } -.crmCaseType .crm-i { - margin: 0.4em 0.2em 0 0; + +.crmCaseType .fa-pencil { + margin: 0.2em 0.2em 0 0; + cursor: pointer; +} + +.crmCaseType .fa-trash { + margin: 0.56em 0.2em 0 0; cursor: pointer; } diff --git a/ang/crmCaseType.js b/ang/crmCaseType.js index e5aae2a3516a..ee2344ece81a 100644 --- a/ang/crmCaseType.js +++ b/ang/crmCaseType.js @@ -1,6 +1,6 @@ (function(angular, $, _) { - var crmCaseType = angular.module('crmCaseType', ['ngRoute', 'ui.utils', 'crmUi', 'unsavedChanges', 'crmUtil']); + var crmCaseType = angular.module('crmCaseType', CRM.angRequires('crmCaseType')); // Note: This template will be passed to cloneDeep(), so don't put any funny stuff in here! var newCaseTypeTemplate = { @@ -50,16 +50,33 @@ apiCalls: function($route, crmApi) { var reqs = {}; reqs.actStatuses = ['OptionValue', 'get', { - option_group_id: 'activity_status' + option_group_id: 'activity_status', + sequential: 1, + options: {limit: 0} + }]; + reqs.caseStatuses = ['OptionValue', 'get', { + option_group_id: 'case_status', + sequential: 1, + options: {limit: 0} }]; reqs.actTypes = ['OptionValue', 'get', { option_group_id: 'activity_type', + sequential: 1, options: { sort: 'name', limit: 0 } }]; + reqs.defaultAssigneeTypes = ['OptionValue', 'get', { + option_group_id: 'activity_default_assignee', + sequential: 1, + options: { + limit: 0 + } + }]; reqs.relTypes = ['RelationshipType', 'get', { + sequential: 1, + is_active: 1, options: { sort: CRM.crmCaseType.REL_TYPE_CNAME, limit: 0 @@ -84,14 +101,6 @@ restrict: 'AE', template: '', link: function(scope, element, attrs) { - /// Format list of options for select2's "data" - var getFormattedOptions = function() { - return { - results: _.map(scope[attrs.crmOptions], function(option){ - return {id: option, text: option}; - }) - }; - }; var input = $('input', element); @@ -101,11 +110,14 @@ scope[attrs.crmVar] = ''; }; - $(input).select2({ - data: getFormattedOptions, + $(input).crmSelect2({ + data: function () { + return { results: scope[attrs.crmOptions] }; + }, createSearchChoice: function(term) { - return {id: term, text: term}; + return {id: term, text: term + ' (' + ts('new') + ')'}; }, + createSearchChoicePosition: 'bottom', placeholder: attrs.placeholder }); $(input).on('select2-selecting', function(e) { @@ -114,36 +126,217 @@ scope.$evalAsync('_resetSelection()'); e.preventDefault(); }); - - scope.$watch(attrs.crmOptions, function(value) { - $(input).select2('data', getFormattedOptions); - $(input).select2('val', ''); - }); } }; }); - crmCaseType.controller('CaseTypeCtrl', function($scope, crmApi, apiCalls) { - var ts = $scope.ts = CRM.ts(null); + crmCaseType.directive('crmEditableTabTitle', function($timeout) { + return { + restrict: 'AE', + link: function(scope, element, attrs) { + element.addClass('crm-editable crm-editable-enabled'); + var titleLabel = $(element).find('span'); + var penIcon = $('').prependTo(element); + var saveButton = $('').appendTo(element); + var cancelButton = $('').appendTo(element); + $('button', element).wrapAll(''); + var buttons = $('.crm-editable-form', element); + titleLabel.on('click', startEditMode); + penIcon.on('click', startEditMode); + + function detectEscapeKeyPress (event) { + var isEscape = false; + + if ("key" in event) { + isEscape = (event.key == "Escape" || event.key == "Esc"); + } else { + isEscape = (event.keyCode == 27); + } + + return isEscape; + } - $scope.activityStatuses = _.values(apiCalls.actStatuses.values); - $scope.activityTypes = apiCalls.actTypes.values; - $scope.activityTypeNames = _.pluck(apiCalls.actTypes.values, 'name'); - $scope.activityTypes = apiCalls.actTypes.values; - $scope.relationshipTypeNames = _.pluck(apiCalls.relTypes.values, CRM.crmCaseType.REL_TYPE_CNAME); // CRM_Case_XMLProcessor::REL_TYPE_CNAME - $scope.locks = {caseTypeName: true, activitySetName: true}; + function detectEnterKeyPress (event) { + var isEnter = false; + + if ("key" in event) { + isEnter = (event.key == "Enter"); + } else { + isEnter = (event.keyCode == 13); + } + + return isEnter; + } + + function startEditMode () { + if (titleLabel.is(":focus")) { + return; + } - $scope.workflows = { - 'timeline': 'Timeline', - 'sequence': 'Sequence' + penIcon.hide(); + buttons.show(); + + saveButton.click(function () { + updateTextValue(); + stopEditMode(); + }); + + cancelButton.click(function () { + revertTextValue(); + stopEditMode(); + }); + + $(element).addClass('crm-editable-editing'); + + titleLabel + .attr("contenteditable", "true") + .focus() + .focusout(function (event) { + $timeout(function () { + revertTextValue(); + stopEditMode(); + }, 500); + }) + .keydown(function(event) { + event.stopImmediatePropagation(); + + if(detectEscapeKeyPress(event)) { + revertTextValue(); + stopEditMode(); + } else if(detectEnterKeyPress(event)) { + event.preventDefault(); + updateTextValue(); + stopEditMode(); + } + }); + } + + function stopEditMode () { + titleLabel.removeAttr("contenteditable").off("focusout"); + titleLabel.off("keydown"); + saveButton.off("click"); + cancelButton.off("click"); + $(element).removeClass('crm-editable-editing'); + + penIcon.show(); + buttons.hide(); + } + + function revertTextValue () { + titleLabel.text(scope.activitySet.label); + } + + function updateTextValue () { + var updatedTitle = titleLabel.text(); + + scope.$evalAsync(function () { + scope.activitySet.label = updatedTitle; + }); + } + } }; + }); + + crmCaseType.controller('CaseTypeCtrl', function($scope, crmApi, apiCalls, crmUiHelp) { + var REL_TYPE_CNAME, defaultAssigneeDefaultValue, ts; + + (function init () { + // CRM_Case_XMLProcessor::REL_TYPE_CNAME + REL_TYPE_CNAME = CRM.crmCaseType.REL_TYPE_CNAME; + + ts = $scope.ts = CRM.ts(null); + $scope.hs = crmUiHelp({file: 'CRM/Case/CaseType'}); + $scope.locks = { caseTypeName: true, activitySetName: true }; + $scope.workflows = { timeline: 'Timeline', sequence: 'Sequence' }; + defaultAssigneeDefaultValue = _.find(apiCalls.defaultAssigneeTypes.values, { is_default: '1' }) || {}; + + storeApiCallsResults(); + initCaseType(); + initCaseTypeDefinition(); + initSelectedStatuses(); + })(); + + /// Stores the api calls results in the $scope object + function storeApiCallsResults() { + $scope.activityStatuses = apiCalls.actStatuses.values; + $scope.caseStatuses = _.indexBy(apiCalls.caseStatuses.values, 'name'); + $scope.activityTypes = _.indexBy(apiCalls.actTypes.values, 'name'); + $scope.activityTypeOptions = _.map(apiCalls.actTypes.values, formatActivityTypeOption); + $scope.defaultAssigneeTypes = apiCalls.defaultAssigneeTypes.values; + $scope.relationshipTypeOptions = _.map(apiCalls.relTypes.values, function(type) { + return {id: type[REL_TYPE_CNAME], text: type.label_b_a}; + }); + $scope.defaultRelationshipTypeOptions = getDefaultRelationshipTypeOptions(); + // stores the default assignee values indexed by their option name: + $scope.defaultAssigneeTypeValues = _.chain($scope.defaultAssigneeTypes) + .indexBy('name').mapValues('value').value(); + } + + /// Returns the default relationship type options. If the relationship is + /// bidirectional (Ex: Spouse of) it adds a single option otherwise it adds + /// two options representing the relationship type directions + /// (Ex: Employee of, Employer is) + function getDefaultRelationshipTypeOptions() { + return _.transform(apiCalls.relTypes.values, function(result, relType) { + var isBidirectionalRelationship = relType.label_a_b === relType.label_b_a; + + result.push({ + label: relType.label_b_a, + value: relType.id + '_b_a' + }); + + if (!isBidirectionalRelationship) { + result.push({ + label: relType.label_a_b, + value: relType.id + '_a_b' + }); + } + }, []); + } + + /// initializes the case type object + function initCaseType() { + var isNewCaseType = !apiCalls.caseType; + + if (isNewCaseType) { + $scope.caseType = _.cloneDeep(newCaseTypeTemplate); + } else { + $scope.caseType = apiCalls.caseType; + } + } + + /// initializes the case type definition object + function initCaseTypeDefinition() { + $scope.caseType.definition = $scope.caseType.definition || []; + $scope.caseType.definition.activityTypes = $scope.caseType.definition.activityTypes || []; + $scope.caseType.definition.activitySets = $scope.caseType.definition.activitySets || []; + $scope.caseType.definition.caseRoles = $scope.caseType.definition.caseRoles || []; + $scope.caseType.definition.statuses = $scope.caseType.definition.statuses || []; + $scope.caseType.definition.timelineActivityTypes = $scope.caseType.definition.timelineActivityTypes || []; + $scope.caseType.definition.restrictActivityAsgmtToCmsUser = $scope.caseType.definition.restrictActivityAsgmtToCmsUser || 0; + $scope.caseType.definition.activityAsgmtGrps = $scope.caseType.definition.activityAsgmtGrps || []; + + _.each($scope.caseType.definition.activitySets, function (set) { + _.each(set.activityTypes, function (type, name) { + var isDefaultAssigneeTypeUndefined = _.isUndefined(type.default_assignee_type); + var typeDefinition = $scope.activityTypes[type.name]; + type.label = (typeDefinition && typeDefinition.label) || type.name; + + if (isDefaultAssigneeTypeUndefined) { + type.default_assignee_type = defaultAssigneeDefaultValue.value; + } + }); + }); + } + + /// initializes the selected statuses + function initSelectedStatuses() { + $scope.selectedStatuses = {}; - $scope.caseType = apiCalls.caseType ? apiCalls.caseType : _.cloneDeep(newCaseTypeTemplate); - $scope.caseType.definition = $scope.caseType.definition || []; - $scope.caseType.definition.activityTypes = $scope.caseType.definition.activityTypes || []; - $scope.caseType.definition.activitySets = $scope.caseType.definition.activitySets || []; - $scope.caseType.definition.caseRoles = $scope.caseType.definition.caseRoles || []; - window.ct = $scope.caseType; + _.each(apiCalls.caseStatuses.values, function (status) { + $scope.selectedStatuses[status.name] = !$scope.caseType.definition.statuses.length || $scope.caseType.definition.statuses.indexOf(status.name) > -1; + }); + } $scope.addActivitySet = function(workflow) { var activitySet = {}; @@ -162,17 +355,54 @@ }); }; - /// Add a new activity entry to an activity-set + function formatActivityTypeOption(type) { + return {id: type.name, text: type.label, icon: type.icon}; + } + + function addActivityToSet(activitySet, activityTypeName) { + activitySet.activityTypes = activitySet.activityTypes || []; + var activity = { + name: activityTypeName, + label: $scope.activityTypes[activityTypeName].label, + status: 'Scheduled', + reference_activity: 'Open Case', + reference_offset: '1', + reference_select: 'newest', + default_assignee_type: $scope.defaultAssigneeTypeValues.NONE + }; + activitySet.activityTypes.push(activity); + if(typeof activitySet.timeline !== "undefined" && activitySet.timeline == "1") { + $scope.caseType.definition.timelineActivityTypes.push(activity); + } + } + + function resetTimelineActivityTypes() { + $scope.caseType.definition.timelineActivityTypes = []; + angular.forEach($scope.caseType.definition.activitySets, function(activitySet) { + angular.forEach(activitySet.activityTypes, function(activityType) { + $scope.caseType.definition.timelineActivityTypes.push(activityType); + }); + }); + } + + function createActivity(name, callback) { + CRM.loadForm(CRM.url('civicrm/admin/options/activity_type', {action: 'add', reset: 1, label: name, component_id: 7})) + .on('crmFormSuccess', function(e, data) { + $scope.activityTypes[data.optionValue.name] = data.optionValue; + $scope.activityTypeOptions.push(formatActivityTypeOption(data.optionValue)); + callback(data.optionValue); + $scope.$digest(); + }); + } + + // Add a new activity entry to an activity-set $scope.addActivity = function(activitySet, activityType) { - activitySet.activityTypes.push({ - name: activityType, - status: 'Scheduled', - reference_activity: 'Open Case', - reference_offset: '1', - reference_select: 'newest' - }); - if (!_.contains($scope.activityTypeNames, activityType)) { - $scope.activityTypeNames.push(activityType); + if ($scope.activityTypes[activityType]) { + addActivityToSet(activitySet, activityType); + } else { + createActivity(activityType, function(newActivity) { + addActivityToSet(activitySet, newActivity.name); + }); } }; @@ -180,26 +410,38 @@ $scope.addActivityType = function(activityType) { var names = _.pluck($scope.caseType.definition.activityTypes, 'name'); if (!_.contains(names, activityType)) { - $scope.caseType.definition.activityTypes.push({ - name: activityType - }); - - } - if (!_.contains($scope.activityTypeNames, activityType)) { - $scope.activityTypeNames.push(activityType); + // Add an activity type that exists + if ($scope.activityTypes[activityType]) { + $scope.caseType.definition.activityTypes.push({name: activityType}); + } else { + createActivity(activityType, function(newActivity) { + $scope.caseType.definition.activityTypes.push({name: newActivity.name}); + }); + } } }; + /// Clears the activity's default assignee values for relationship and contact + $scope.clearActivityDefaultAssigneeValues = function(activity) { + activity.default_assignee_relationship = null; + activity.default_assignee_contact = null; + }; + /// Add a new role $scope.addRole = function(roles, roleName) { var names = _.pluck($scope.caseType.definition.caseRoles, 'name'); if (!_.contains(names, roleName)) { - roles.push({ - name: roleName - }); - } - if (!_.contains($scope.relationshipTypeNames, roleName)) { - $scope.relationshipTypeNames.push(roleName); + if (_.where($scope.relationshipTypeOptions, {id: roleName}).length) { + roles.push({name: roleName}); + } else { + CRM.loadForm(CRM.url('civicrm/admin/reltype', {action: 'add', reset: 1, label_a_b: roleName, label_b_a: roleName})) + .on('crmFormSuccess', function(e, data) { + var newType = _.values(data.relationshipType)[0]; + roles.push({name: newType[REL_TYPE_CNAME]}); + $scope.relationshipTypeOptions.push({id: newType[REL_TYPE_CNAME], text: newType.label_b_a}); + $scope.$digest(); + }); + } } }; @@ -215,6 +457,7 @@ var idx = _.indexOf(array, item); if (idx != -1) { array.splice(idx, 1); + resetTimelineActivityTypes(); } }; @@ -222,6 +465,15 @@ return !$scope.caseType.id || $scope.caseType.is_forkable; }; + $scope.newStatus = function() { + CRM.loadForm(CRM.url('civicrm/admin/options/case_status', {action: 'add', reset: 1})) + .on('crmFormSuccess', function(e, data) { + $scope.caseStatuses[data.optionValue.name] = data.optionValue; + $scope.selectedStatuses[data.optionValue.name] = true; + $scope.$digest(); + }); + }; + $scope.isNewActivitySetAllowed = function(workflow) { switch (workflow) { case 'timeline': @@ -235,11 +487,7 @@ }; $scope.isActivityRemovable = function(activitySet, activity) { - if (activitySet.name == 'standard_timeline' && activity.name == 'Open Case') { - return false; - } else { - return true; - } + return true; }; $scope.isValidName = function(name) { @@ -274,6 +522,18 @@ }; $scope.save = function() { + // Add selected statuses + var selectedStatuses = []; + _.each($scope.selectedStatuses, function(v, k) { + if (v) selectedStatuses.push(k); + }); + // Ignore if ALL or NONE selected + $scope.caseType.definition.statuses = selectedStatuses.length == _.size($scope.selectedStatuses) ? [] : selectedStatuses; + + if ($scope.caseType.definition.activityAsgmtGrps) { + $scope.caseType.definition.activityAsgmtGrps = $scope.caseType.definition.activityAsgmtGrps.toString().split(","); + } + var result = crmApi('CaseType', 'create', $scope.caseType, true); result.then(function(data) { if (data.is_error === 0 || data.is_error == '0') { @@ -302,6 +562,7 @@ if (!$scope.isForkable()) { CRM.alert(ts('The CiviCase XML file for this case-type prohibits editing the definition.')); } + }); crmCaseType.controller('CaseTypeListCtrl', function($scope, crmApi, caseTypes) { @@ -324,7 +585,6 @@ }) .then(function (data) { delete caseTypes.values[caseType.id]; - $scope.$digest(); }); }; $scope.revertCaseType = function (caseType) { diff --git a/ang/crmCaseType/activitySetDetails.html b/ang/crmCaseType/activitySetDetails.html deleted file mode 100644 index 58701a19a3e7..000000000000 --- a/ang/crmCaseType/activitySetDetails.html +++ /dev/null @@ -1,28 +0,0 @@ - -{{ts('Label')}} | -- - | -
{{ts('Name')}} | -- - - - | -
{{ts('Workflow')}} | -- {{ getWorkflowName(activitySet) }} - | -
{{ts('Activity Type')}} | {{ts('Max Instances')}} | @@ -15,10 +16,13 @@ | |
---|---|---|---|
+ | ++ {{ activityType.name }} | - + | @@ -28,13 +32,14 @@ |
+ > |
{{ts('Activity')}} | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+ | ++ {{ activity.name }} | @@ -26,11 +30,11 @@ | ||||||||||||
+ > |
+ | {{ts('Name')}} | +{{ts('Class')}} | +
---|---|---|
+ + | ++ {{ caseStatuses[status].label }} + | ++ {{ caseStatuses[status].grouping }} + | +
+ | {{ ts('New Status') }} | ++ |
{{ts('Activity')}} | {{ts('Status')}} | {{ts('Reference')}} | {{ts('Offset')}} | {{ts('Select')}} | +{{ts('Default assignee')}} | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
- {{ activity.name }} + | ++ + {{activity.label}} | @@ -33,35 +38,59 @@ | + > | + |
+
+
+ + + + ++ + + |
-
+
+ >
|
{{ts('Existing Connections')}}
+
diff --git a/ang/crmD3.ang.php b/ang/crmD3.ang.php
new file mode 100644
index 000000000000..0a737341ae81
--- /dev/null
+++ b/ang/crmD3.ang.php
@@ -0,0 +1,16 @@
+ 'civicrm',
+ 'js' => [
+ 'ang/crmD3.js',
+ 'bower_components/d3/d3.min.js',
+ ],
+ 'requires' => [],
+];
diff --git a/ang/crmD3.js b/ang/crmD3.js
index eca29a3cfb4b..d06eeac9b40b 100644
--- a/ang/crmD3.js
+++ b/ang/crmD3.js
@@ -1,4 +1,3 @@
(function (angular, $, _) {
- // thin stub for declaring dependencies
- angular.module('crmD3', []);
+ angular.module('crmD3', CRM.angRequires('crmD3'));
})(angular, CRM.$, CRM._);
diff --git a/ang/crmExample.ang.php b/ang/crmExample.ang.php
new file mode 100644
index 000000000000..763f1eaca2ab
--- /dev/null
+++ b/ang/crmExample.ang.php
@@ -0,0 +1,11 @@
+ 'civicrm',
+ 'js' => ['ang/crmExample.js'],
+ 'partials' => ['ang/crmExample'],
+ 'requires' => ['crmUtil', 'ngRoute', 'ui.utils', 'crmUi', 'crmResource'],
+];
diff --git a/ang/crmExample.js b/ang/crmExample.js
index d32d81d29a62..138ce8f12a5b 100644
--- a/ang/crmExample.js
+++ b/ang/crmExample.js
@@ -1,8 +1,6 @@
(function(angular, $, _) {
- angular.module('crmExample', [
- 'crmUtil', 'ngRoute', 'ui.utils', 'crmUi'
- ]);
+ angular.module('crmExample', CRM.angRequires('crmExample'));
angular.module('crmExample').config([
'$routeProvider',
diff --git a/ang/crmExample/example.html b/ang/crmExample/example.html
index c9b6abd03f7d..5393e7c1a521 100644
--- a/ang/crmExample/example.html
+++ b/ang/crmExample/example.html
@@ -20,17 +20,16 @@
{{ts('New Connections')}}{{api.actions}}
-
+
{{action}} ,
-
+
-
+
-
+
|
{{exampleForm[exName]|json}}diff --git a/ang/crmMailing.ang.php b/ang/crmMailing.ang.php new file mode 100644 index 000000000000..a3e140c6058a --- /dev/null +++ b/ang/crmMailing.ang.php @@ -0,0 +1,18 @@ + 'civicrm', + 'js' => [ + 'ang/crmMailing.js', + 'ang/crmMailing/*.js', + ], + 'css' => ['ang/crmMailing.css'], + 'partials' => ['ang/crmMailing'], + 'requires' => ['crmUtil', 'crmAttachment', 'crmAutosave', 'ngRoute', 'ui.utils', 'crmUi', 'dialogService', 'crmResource'], +]; diff --git a/ang/crmMailing.js b/ang/crmMailing.js index 7254b8a06ed9..95148bf27b3f 100644 --- a/ang/crmMailing.js +++ b/ang/crmMailing.js @@ -1,8 +1,6 @@ (function (angular, $, _) { - angular.module('crmMailing', [ - 'crmUtil', 'crmAttachment', 'crmAutosave', 'ngRoute', 'ui.utils', 'crmUi', 'dialogService' - ]); + angular.module('crmMailing', CRM.angRequires('crmMailing')); angular.module('crmMailing').config([ '$routeProvider', @@ -12,41 +10,50 @@ controller: 'ListMailingsCtrl' }); - var editorPaths = { - '': '~/crmMailing/EditMailingCtrl/2step.html', - '/unified': '~/crmMailing/EditMailingCtrl/unified.html', - '/unified2': '~/crmMailing/EditMailingCtrl/unified2.html', - '/wizard': '~/crmMailing/EditMailingCtrl/wizard.html' - }; - angular.forEach(editorPaths, function(editTemplate, pathSuffix) { - if (CRM && CRM.crmMailing && CRM.crmMailing.workflowEnabled) { - editTemplate = '~/crmMailing/EditMailingCtrl/workflow.html'; // override + if (!CRM || !CRM.crmMailing) { + return; + } + + $routeProvider.when('/mailing/new', { + template: ' ' + ts('Initializing...') + ' ', + controller: 'CreateMailingCtrl', + resolve: { + selectedMail: function(crmMailingMgr) { + var m = crmMailingMgr.create({ + template_type: CRM.crmMailing.templateTypes[0].name + }); + return crmMailingMgr.save(m); + } } - $routeProvider.when('/mailing/new' + pathSuffix, { - template: '' + ts('Initializing...') + ' ', - controller: 'CreateMailingCtrl', - resolve: { - selectedMail: function(crmMailingMgr) { - var m = crmMailingMgr.create(); - return crmMailingMgr.save(m); - } + }); + + $routeProvider.when('/mailing/new/:templateType', { + template: '' + ts('Initializing...') + ' ', + controller: 'CreateMailingCtrl', + resolve: { + selectedMail: function($route, crmMailingMgr) { + var m = crmMailingMgr.create({ + template_type: $route.current.params.templateType + }); + return crmMailingMgr.save(m); } - }); - $routeProvider.when('/mailing/:id' + pathSuffix, { - templateUrl: editTemplate, - controller: 'EditMailingCtrl', - resolve: { - selectedMail: function($route, crmMailingMgr) { - return crmMailingMgr.get($route.current.params.id); - }, - attachments: function($route, CrmAttachments) { - var attachments = new CrmAttachments(function () { - return {entity_table: 'civicrm_mailing', entity_id: $route.current.params.id}; - }); - return attachments.load(); - } + } + }); + + $routeProvider.when('/mailing/:id', { + templateUrl: '~/crmMailing/EditMailingCtrl/base.html', + controller: 'EditMailingCtrl', + resolve: { + selectedMail: function($route, crmMailingMgr) { + return crmMailingMgr.get($route.current.params.id); + }, + attachments: function($route, CrmAttachments) { + var attachments = new CrmAttachments(function () { + return {entity_table: 'civicrm_mailing', entity_id: $route.current.params.id}; + }); + return attachments.load(); } - }); + } }); } ]); diff --git a/ang/crmMailing/BlockMailing.html b/ang/crmMailing/BlockMailing.html index 432387719041..8e09974322ce 100644 --- a/ang/crmMailing/BlockMailing.html +++ b/ang/crmMailing/BlockMailing.html @@ -7,20 +7,7 @@
diff --git a/ang/crmMailing/BlockPreview.html b/ang/crmMailing/BlockPreview.html
index a9e69eff9f8e..6315466e83cf 100644
--- a/ang/crmMailing/BlockPreview.html
+++ b/ang/crmMailing/BlockPreview.html
@@ -22,7 +22,7 @@
-->
-
+
-
diff --git a/ang/crmMailing/BlockPreview.js b/ang/crmMailing/BlockPreview.js
index 561ddf09501c..5e582dc0566a 100644
--- a/ang/crmMailing/BlockPreview.js
+++ b/ang/crmMailing/BlockPreview.js
@@ -21,6 +21,7 @@
});
};
scope.doSend = function doSend(recipient) {
+ recipient = JSON.parse(JSON.stringify(recipient).replace(/\,\s/g, ','));
scope.$eval(attr.onSend, {
preview: {recipient: recipient}
});
@@ -29,16 +30,15 @@
scope.previewTestGroup = function(e) {
var $dialog = $(this);
$dialog.html('').parent().find('button[data-op=yes]').prop('disabled', true);
- $dialog.dialog('option', 'title', ts('Send to %1', {1: _.pluck(_.where(scope.crmMailingConst.groupNames, {id: scope.testGroup.gid}), 'title')[0]}));
- CRM.api3('contact', 'get', {
- group: scope.testGroup.gid,
- options: {limit: 0},
- return: 'display_name,email'
+ CRM.api3({
+ contact: ['contact', 'get', {group: scope.testGroup.gid, options: {limit: 0}, return: 'display_name,email'}],
+ group: ['group', 'getsingle', {id: scope.testGroup.gid, return: 'title'}]
}).done(function(data) {
+ $dialog.dialog('option', 'title', ts('Send to %1', {1: data.group.title}));
var count = 0,
// Fixme: should this be in a template?
- markup = '
' + ts('A test message will be sent to %1 people:', {1: count}) + '' + markup; if (!count) { markup = ' '; } $dialog diff --git a/ang/crmMailing/BlockRecipients.html b/ang/crmMailing/BlockRecipients.html index 5852a8e97c7b..cedfa6dc2441 100644 --- a/ang/crmMailing/BlockRecipients.html +++ b/ang/crmMailing/BlockRecipients.html @@ -1,19 +1,15 @@ - diff --git a/ang/crmMailing/BlockReview.html b/ang/crmMailing/BlockReview.html index 49b9232a6442..5a0021e40ab6 100644 --- a/ang/crmMailing/BlockReview.html +++ b/ang/crmMailing/BlockReview.html @@ -11,7 +11,7 @@
-
+
({{ts('Include:')}} {{getIncludesAsString(mailing)}})
@@ -34,6 +34,9 @@
{{ts('None')}}
+ {{crmMailingConst.enabledLanguages[mailing.language]}}
+
diff --git a/ang/crmMailing/BlockTemplates.html b/ang/crmMailing/BlockTemplates.html
new file mode 100644
index 000000000000..38a37a91fd77
--- /dev/null
+++ b/ang/crmMailing/BlockTemplates.html
@@ -0,0 +1,9 @@
+
\ No newline at end of file
diff --git a/ang/crmMailing/BlockTemplates.js b/ang/crmMailing/BlockTemplates.js
new file mode 100644
index 000000000000..9ee2efbfeea8
--- /dev/null
+++ b/ang/crmMailing/BlockTemplates.js
@@ -0,0 +1,5 @@
+(function(angular, $, _) {
+ angular.module('crmMailing').directive('crmMailingBlockTemplates', function(crmMailingSimpleDirective) {
+ return crmMailingSimpleDirective('crmMailingBlockTemplates', '~/crmMailing/BlockTemplates.html');
+ });
+})(angular, CRM.$, CRM._);
\ No newline at end of file
diff --git a/ang/crmMailing/BodyHtml.html b/ang/crmMailing/BodyHtml.html
index 730beecdd866..b38c28c76bfa 100644
--- a/ang/crmMailing/BodyHtml.html
+++ b/ang/crmMailing/BodyHtml.html
@@ -4,17 +4,18 @@
-
+
diff --git a/ang/crmMailing/CreateMailingCtrl.js b/ang/crmMailing/CreateMailingCtrl.js
index 9baecadbf2f7..08a6171311dc 100644
--- a/ang/crmMailing/CreateMailingCtrl.js
+++ b/ang/crmMailing/CreateMailingCtrl.js
@@ -1,10 +1,7 @@
(function(angular, $, _) {
angular.module('crmMailing').controller('CreateMailingCtrl', function EditMailingCtrl($scope, selectedMail, $location) {
- // Transition URL "/mailing/new/foo" => "/mailing/123/foo"
- var parts = $location.path().split('/'); // e.g. "/mailing/new" or "/mailing/123/wizard"
- parts[2] = selectedMail.id;
- $location.path(parts.join('/'));
+ $location.path("/mailing/" + selectedMail.id);
$location.replace();
});
diff --git a/ang/crmMailing/EditMailingCtrl.js b/ang/crmMailing/EditMailingCtrl.js
index 262049755088..91f6db3f3aa7 100644
--- a/ang/crmMailing/EditMailingCtrl.js
+++ b/ang/crmMailing/EditMailingCtrl.js
@@ -13,6 +13,10 @@
var block = $scope.block = crmBlocker();
var myAutosave = null;
+ var templateTypes = _.where(CRM.crmMailing.templateTypes, {name: selectedMail.template_type});
+ if (!templateTypes[0]) throw 'Unrecognized template type: ' + selectedMail.template_type;
+ $scope.mailingEditorUrl = templateTypes[0].editorUrl;
+
$scope.isSubmitted = function isSubmitted() {
return _.size($scope.mailing.jobs) > 0;
};
@@ -43,7 +47,7 @@
// @return Promise
$scope.submit = function submit(options) {
options = options || {};
- if (block.check() || $scope.crmMailing.$invalid) {
+ if (block.check()) {
return;
}
diff --git a/ang/crmMailing/EditMailingCtrl/2step.html b/ang/crmMailing/EditMailingCtrl/2step.html
index da35ce2bfe78..cabd6f307c69 100644
--- a/ang/crmMailing/EditMailingCtrl/2step.html
+++ b/ang/crmMailing/EditMailingCtrl/2step.html
@@ -1,55 +1,48 @@
-
-
-
- {{ts('This mailing has been submitted.')}}
-
-
- |