PageRenderTime 22ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/civicrm/custom/php/CRM/Core/BAO/Block.php

https://github.com/nysenate/Bluebird-CRM
PHP | 450 lines | 249 code | 35 blank | 166 comment | 73 complexity | 7d98f7eff2fef3eca330c57dd22ef8f4 MD5 | raw file
Possible License(s): JSON, BSD-3-Clause, MPL-2.0-no-copyleft-exception, AGPL-1.0, GPL-2.0, AGPL-3.0, Apache-2.0, MIT, GPL-3.0, CC-BY-4.0, LGPL-2.1, BSD-2-Clause, LGPL-3.0
  1. <?php
  2. /*
  3. +--------------------------------------------------------------------+
  4. | Copyright CiviCRM LLC. All rights reserved. |
  5. | |
  6. | This work is published under the GNU AGPLv3 license with some |
  7. | permitted exceptions and without any warranty. For full license |
  8. | and copyright information, see https://civicrm.org/licensing |
  9. +--------------------------------------------------------------------+
  10. */
  11. /**
  12. * Add static functions to include some common functionality used across location sub object BAO classes.
  13. *
  14. * @package CRM
  15. * @copyright CiviCRM LLC https://civicrm.org/licensing
  16. */
  17. class CRM_Core_BAO_Block {
  18. /**
  19. * Fields that are required for a valid block.
  20. * @var array
  21. */
  22. public static $requiredBlockFields = [
  23. 'email' => ['email'],
  24. 'phone' => ['phone', 'phone_ext'],//NYSS 4775
  25. 'im' => ['name'],
  26. 'openid' => ['openid'],
  27. ];
  28. /**
  29. * Given the list of params in the params array, fetch the object
  30. * and store the values in the values array
  31. *
  32. * @param string $blockName
  33. * Name of the above object.
  34. * @param array $params
  35. * Input parameters to find object.
  36. *
  37. * @return array
  38. * Array of $block objects.
  39. * @throws CRM_Core_Exception
  40. */
  41. public static function &getValues($blockName, $params) {
  42. if (empty($params)) {
  43. return NULL;
  44. }
  45. $BAOString = 'CRM_Core_BAO_' . $blockName;
  46. $block = new $BAOString();
  47. $blocks = [];
  48. if (!isset($params['entity_table'])) {
  49. $block->contact_id = $params['contact_id'];
  50. if (!$block->contact_id) {
  51. throw new CRM_Core_Exception('Invalid Contact ID parameter passed');
  52. }
  53. $blocks = self::retrieveBlock($block, $blockName);
  54. }
  55. else {
  56. $blockIds = self::getBlockIds($blockName, NULL, $params);
  57. if (empty($blockIds)) {
  58. return $blocks;
  59. }
  60. $count = 1;
  61. foreach ($blockIds as $blockId) {
  62. $block = new $BAOString();
  63. $block->id = $blockId['id'];
  64. $getBlocks = self::retrieveBlock($block, $blockName);
  65. $blocks[$count++] = array_pop($getBlocks);
  66. }
  67. }
  68. return $blocks;
  69. }
  70. /**
  71. * Given the list of params in the params array, fetch the object
  72. * and store the values in the values array
  73. *
  74. * @param Object $block
  75. * Typically a Phone|Email|IM|OpenID object.
  76. * @param string $blockName
  77. * Name of the above object.
  78. *
  79. * @return array
  80. * Array of $block objects.
  81. */
  82. public static function retrieveBlock(&$block, $blockName) {
  83. // we first get the primary location due to the order by clause
  84. $block->orderBy('is_primary desc, id');
  85. $block->find();
  86. $count = 1;
  87. $blocks = [];
  88. while ($block->fetch()) {
  89. CRM_Core_DAO::storeValues($block, $blocks[$count]);
  90. //unset is_primary after first block. Due to some bug in earlier version
  91. //there might be more than one primary blocks, hence unset is_primary other than first
  92. if ($count > 1) {
  93. unset($blocks[$count]['is_primary']);
  94. }
  95. $count++;
  96. }
  97. return $blocks;
  98. }
  99. /**
  100. * Check if the current block object has any valid data.
  101. *
  102. * @param array $blockFields
  103. * Array of fields that are of interest for this object.
  104. * @param array $params
  105. * Associated array of submitted fields.
  106. *
  107. * @return bool
  108. * true if the block has data, otherwise false
  109. */
  110. public static function dataExists($blockFields, &$params) {
  111. //NYSS 4775
  112. $isEmpty = TRUE;
  113. foreach ($blockFields as $field) {
  114. if (!CRM_Utils_System::isNull(CRM_Utils_Array::value($field, $params))) {
  115. $isEmpty = FALSE;
  116. }
  117. }
  118. if ($isEmpty) {
  119. return FALSE;
  120. }
  121. else {
  122. return TRUE;
  123. }
  124. }
  125. /**
  126. * Check if the current block exits.
  127. *
  128. * @param string $blockName
  129. * Block name.
  130. * @param array $params
  131. * Array of submitted fields.
  132. *
  133. * @return bool
  134. * true if the block is in the params and is an array
  135. */
  136. public static function blockExists($blockName, $params) {
  137. //NYSS 4775 allow saving just phone ext
  138. if ( $blockName == 'phone' ) {
  139. if ( ( !CRM_Utils_Array::value( $blockName, $params ) &&
  140. !CRM_Utils_Array::value( 'phone_ext', $params ) ) ||
  141. !is_array( $params[$blockName] ) ) {
  142. return false;
  143. }
  144. }
  145. elseif (empty($params[$blockName]) || !is_array($params[$blockName])) {
  146. return FALSE;
  147. }
  148. return TRUE;
  149. }
  150. /**
  151. * Get all block ids for a contact.
  152. *
  153. * @param string $blockName
  154. * Block name.
  155. * @param int $contactId
  156. * Contact id.
  157. *
  158. * @param null $entityElements
  159. * @param bool $updateBlankLocInfo
  160. *
  161. * @return array
  162. * formatted array of block ids
  163. *
  164. */
  165. public static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
  166. $allBlocks = [];
  167. $name = ucfirst($blockName);
  168. if ($blockName == 'im') {
  169. $name = 'IM';
  170. }
  171. elseif ($blockName == 'openid') {
  172. $name = 'OpenID';
  173. }
  174. $baoString = 'CRM_Core_BAO_' . $name;
  175. if ($contactId) {
  176. //@todo a cleverer way to do this would be to use the same fn name on each
  177. // BAO rather than constructing the fn
  178. // it would also be easier to grep for
  179. // e.g $bao = new $baoString;
  180. // $bao->getAllBlocks()
  181. $baoFunction = 'all' . $name . 's';
  182. $allBlocks = $baoString::$baoFunction($contactId, $updateBlankLocInfo);
  183. }
  184. elseif (!empty($entityElements) && $blockName != 'openid') {
  185. $baoFunction = 'allEntity' . $name . 's';
  186. $allBlocks = $baoString::$baoFunction($entityElements);
  187. }
  188. return $allBlocks;
  189. }
  190. /**
  191. * Takes an associative array and creates a block.
  192. *
  193. * @param string $blockName
  194. * Block name.
  195. * @param array $params
  196. * Array of name/value pairs.
  197. *
  198. * @return array|null
  199. * Array of created location entities or NULL if none to create.
  200. */
  201. public static function create($blockName, $params) {
  202. if (!self::blockExists($blockName, $params)) {
  203. return NULL;
  204. }
  205. $name = ucfirst($blockName);
  206. $isPrimary = $isBilling = TRUE;
  207. $entityElements = $blocks = [];
  208. $resetPrimaryId = NULL;
  209. $primaryId = FALSE;
  210. $contactId = $params['contact_id'];
  211. $updateBlankLocInfo = CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE);
  212. $isIdSet = CRM_Utils_Array::value('isIdSet', $params[$blockName], FALSE);
  213. //get existing block ids.
  214. $blockIds = self::getBlockIds($blockName, $contactId, $entityElements);
  215. foreach ($params[$blockName] as $count => $value) {
  216. $blockId = $value['id'] ?? NULL;
  217. if ($blockId) {
  218. if (is_array($blockIds) && array_key_exists($blockId, $blockIds)) {
  219. unset($blockIds[$blockId]);
  220. }
  221. else {
  222. unset($value['id']);
  223. }
  224. }
  225. }
  226. $baoString = 'CRM_Core_BAO_' . $name;
  227. foreach ($params[$blockName] as $count => $value) {
  228. if (!is_array($value)) {
  229. continue;
  230. }
  231. // if in some cases (eg. email used in Online Conribution Page, Profiles, etc.) id is not set
  232. // lets try to add using the previous method to avoid any false creation of existing data.
  233. foreach ($blockIds as $blockId => $blockValue) {
  234. if (empty($value['id']) && $blockValue['locationTypeId'] == CRM_Utils_Array::value('location_type_id', $value) && !$isIdSet) {
  235. $valueId = FALSE;
  236. if ($blockName == 'phone') {
  237. $phoneTypeBlockValue = $blockValue['phoneTypeId'] ?? NULL;
  238. if ($phoneTypeBlockValue == CRM_Utils_Array::value('phone_type_id', $value)) {
  239. $valueId = TRUE;
  240. }
  241. }
  242. elseif ($blockName == 'im') {
  243. $providerBlockValue = $blockValue['providerId'] ?? NULL;
  244. if (!empty($value['provider_id']) && $providerBlockValue == $value['provider_id']) {
  245. $valueId = TRUE;
  246. }
  247. }
  248. else {
  249. $valueId = TRUE;
  250. }
  251. if ($valueId) {
  252. $value['id'] = $blockValue['id'];
  253. if (!$primaryId && !empty($blockValue['is_primary'])) {
  254. $value['is_primary'] = $blockValue['is_primary'];
  255. }
  256. break;
  257. }
  258. }
  259. }
  260. $dataExists = self::dataExists(self::$requiredBlockFields[$blockName], $value);
  261. // Note there could be cases when block info already exist ($value[id] is set) for a contact/entity
  262. // BUT info is not present at this time, and therefore we should be really careful when deleting the block.
  263. // $updateBlankLocInfo will help take appropriate decision. CRM-5969
  264. if (!empty($value['id']) && !$dataExists && $updateBlankLocInfo) {
  265. //delete the existing record
  266. $baoString::del($value['id']);
  267. continue;
  268. }
  269. elseif (!$dataExists) {
  270. continue;
  271. }
  272. $contactFields = [
  273. 'contact_id' => $contactId,
  274. 'location_type_id' => $value['location_type_id'] ?? NULL,
  275. ];
  276. $contactFields['is_billing'] = 0;
  277. if ($isBilling && !empty($value['is_billing'])) {
  278. $contactFields['is_billing'] = $value['is_billing'];
  279. $isBilling = FALSE;
  280. }
  281. $blockFields = array_merge($value, $contactFields);
  282. $blocks[] = $baoString::create($blockFields);
  283. }
  284. return $blocks;
  285. }
  286. /**
  287. * Delete block.
  288. * @deprecated - just call the BAO / api directly.
  289. *
  290. * @param string $blockName
  291. * Block name.
  292. * @param int $params
  293. * Associates array.
  294. */
  295. public static function blockDelete($blockName, $params) {
  296. $name = ucfirst($blockName);
  297. if ($blockName == 'im') {
  298. $name = 'IM';
  299. }
  300. elseif ($blockName == 'openid') {
  301. $name = 'OpenID';
  302. }
  303. $baoString = 'CRM_Core_BAO_' . $name;
  304. $baoString::del($params['id']);
  305. }
  306. /**
  307. * Handling for is_primary.
  308. * $params is_primary could be
  309. * # 1 - find other entries with is_primary = 1 & reset them to 0
  310. * # 0 - make sure at least one entry is set to 1
  311. * - if no other entry is 1 change to 1
  312. * - if one other entry exists change that to 1
  313. * - if more than one other entry exists change first one to 1
  314. * @fixme - perhaps should choose by location_type
  315. * # empty - same as 0 as once we have checked first step
  316. * we know if it should be 1 or 0
  317. *
  318. * if $params['id'] is set $params['contact_id'] may need to be retrieved
  319. *
  320. * @param array $params
  321. * @param $class
  322. *
  323. * @throws API_Exception
  324. */
  325. public static function handlePrimary(&$params, $class) {
  326. if (isset($params['id']) && CRM_Utils_System::isNull($params['is_primary'] ?? NULL)) {
  327. // if id is set & is_primary isn't we can assume no change)
  328. return;
  329. }
  330. $table = CRM_Core_DAO_AllCoreTables::getTableForClass($class);
  331. if (!$table) {
  332. throw new API_Exception("Failed to locate table for class [$class]");
  333. }
  334. // contact_id in params might be empty or the string 'null' so cast to integer
  335. $contactId = (int) ($params['contact_id'] ?? 0);
  336. // If id is set & we haven't been passed a contact_id, retrieve it
  337. if (!empty($params['id']) && !isset($params['contact_id'])) {
  338. $entity = new $class();
  339. $entity->id = $params['id'];
  340. $entity->find(TRUE);
  341. $contactId = $params['contact_id'] = $entity->contact_id;
  342. }
  343. // If entity is not associated with contact, concept of is_primary not relevant
  344. if (!$contactId) {
  345. return;
  346. }
  347. // if params is_primary then set all others to not be primary & exit out
  348. // if is_primary = 1
  349. if (!empty($params['is_primary'])) {
  350. $sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
  351. $sqlParams = [1 => [$contactId, 'Integer']];
  352. // we don't want to create unnecessary entries in the log_ tables so exclude the one we are working on
  353. if (!empty($params['id'])) {
  354. $sql .= " AND id <> %2";
  355. $sqlParams[2] = [$params['id'], 'Integer'];
  356. }
  357. CRM_Core_DAO::executeQuery($sql, $sqlParams);
  358. return;
  359. }
  360. //Check what other emails exist for the contact
  361. $existingEntities = new $class();
  362. $existingEntities->contact_id = $contactId;
  363. $existingEntities->orderBy('is_primary DESC');
  364. if (!$existingEntities->find(TRUE) || (!empty($params['id']) && $existingEntities->id == $params['id'])) {
  365. // ie. if no others is set to be primary then this has to be primary set to 1 so change
  366. $params['is_primary'] = 1;
  367. return;
  368. }
  369. else {
  370. /*
  371. * If the only existing email is the one we are editing then we must set
  372. * is_primary to 1
  373. * @see https://issues.civicrm.org/jira/browse/CRM-10451
  374. */
  375. if ($existingEntities->N == 1 && $existingEntities->id == CRM_Utils_Array::value('id', $params)) {
  376. $params['is_primary'] = 1;
  377. return;
  378. }
  379. if ($existingEntities->is_primary == 1) {
  380. return;
  381. }
  382. // so at this point we are only dealing with ones explicity setting is_primary to 0
  383. // since we have reverse sorted by email we can either set the first one to
  384. // primary or return if is already is
  385. $existingEntities->is_primary = 1;
  386. $existingEntities->save();
  387. if ($class === 'CRM_Core_BAO_Email') {
  388. CRM_Core_BAO_Email::updateContactName($contactId, $existingEntities->email);
  389. }
  390. }
  391. }
  392. /**
  393. * Sort location array so primary element is first.
  394. *
  395. * @param array $locations
  396. */
  397. public static function sortPrimaryFirst(&$locations) {
  398. uasort($locations, 'self::primaryComparison');
  399. }
  400. /**
  401. * compare 2 locations to see which should go first based on is_primary
  402. * (sort function for sortPrimaryFirst)
  403. * @param array $location1
  404. * @param array $location2
  405. * @return int
  406. */
  407. public static function primaryComparison($location1, $location2) {
  408. $l1 = $location1['is_primary'] ?? NULL;
  409. $l2 = $location2['is_primary'] ?? NULL;
  410. if ($l1 == $l2) {
  411. return 0;
  412. }
  413. return ($l1 < $l2) ? -1 : 1;
  414. }
  415. }