| @@ -456,7 +456,7 @@ | ||
| 456 | 456 | * @param EEM_Base $model | 
| 457 | 457 | * @param EE_Model_Relation_Base $relation | 
| 458 | 458 | * @param WP_REST_Request $request | 
| 459 | -     * @return array { | |
| 459 | +     * @return EE_Base_Class[] { | |
| 460 | 460 | * @type EE_Base_Class $model_obj | 
| 461 | 461 | * @type EE_Base_Class|null $other_model_obj | 
| 462 | 462 | * } | 
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | use EventEspresso\core\services\loaders\LoaderFactory; | 
| 12 | 12 | use Exception; | 
| 13 | 13 | use InvalidArgumentException; | 
| 14 | -use ReflectionException; | |
| 15 | 14 | use \WP_REST_Request; | 
| 16 | 15 | use \WP_REST_Response; | 
| 17 | 16 | use EventEspresso\core\libraries\rest_api\Capabilities; | 
| @@ -134,9 +134,9 @@ discard block | ||
| 134 | 134 |      { | 
| 135 | 135 | Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create'); | 
| 136 | 136 | $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | 
| 137 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 137 | +        if ( ! current_user_can($default_cap_to_check_for)) { | |
| 138 | 138 | throw new RestException( | 
| 139 | - 'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 139 | + 'rest_cannot_create_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 140 | 140 | sprintf( | 
| 141 | 141 | esc_html__( | 
| 142 | 142 | // @codingStandardsIgnoreStart | 
| @@ -164,7 +164,7 @@ discard block | ||
| 164 | 164 | ); | 
| 165 | 165 | $model_obj->save(); | 
| 166 | 166 | $new_id = $model_obj->ID(); | 
| 167 | -        if (! $new_id) { | |
| 167 | +        if ( ! $new_id) { | |
| 168 | 168 | throw new RestException( | 
| 169 | 169 | 'rest_insertion_failed', | 
| 170 | 170 |                  sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name()) | 
| @@ -186,9 +186,9 @@ discard block | ||
| 186 | 186 |      { | 
| 187 | 187 | Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | 
| 188 | 188 | $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | 
| 189 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 189 | +        if ( ! current_user_can($default_cap_to_check_for)) { | |
| 190 | 190 | throw new RestException( | 
| 191 | - 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 191 | + 'rest_cannot_edit_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 192 | 192 | sprintf( | 
| 193 | 193 | esc_html__( | 
| 194 | 194 | // @codingStandardsIgnoreStart | 
| @@ -202,7 +202,7 @@ discard block | ||
| 202 | 202 | ); | 
| 203 | 203 | } | 
| 204 | 204 |          $obj_id = $request->get_param('id'); | 
| 205 | -        if (! $obj_id) { | |
| 205 | +        if ( ! $obj_id) { | |
| 206 | 206 | throw new RestException( | 
| 207 | 207 | 'rest_edit_failed', | 
| 208 | 208 |                  sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name()) | 
| @@ -215,7 +215,7 @@ discard block | ||
| 215 | 215 | true | 
| 216 | 216 | ); | 
| 217 | 217 | $model_obj = $model->get_one_by_ID($obj_id); | 
| 218 | -        if (! $model_obj instanceof EE_Base_Class) { | |
| 218 | +        if ( ! $model_obj instanceof EE_Base_Class) { | |
| 219 | 219 | $lowercase_model_name = strtolower($model->get_this_model_name()); | 
| 220 | 220 | throw new RestException( | 
| 221 | 221 |                  sprintf('rest_%s_invalid_id', $lowercase_model_name), | 
| @@ -240,9 +240,9 @@ discard block | ||
| 240 | 240 |      { | 
| 241 | 241 | Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete'); | 
| 242 | 242 | $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | 
| 243 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 243 | +        if ( ! current_user_can($default_cap_to_check_for)) { | |
| 244 | 244 | throw new RestException( | 
| 245 | - 'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 245 | + 'rest_cannot_delete_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 246 | 246 | sprintf( | 
| 247 | 247 | esc_html__( | 
| 248 | 248 | // @codingStandardsIgnoreStart | 
| @@ -258,7 +258,7 @@ discard block | ||
| 258 | 258 |          $obj_id = $request->get_param('id'); | 
| 259 | 259 | // this is where we would apply more fine-grained caps | 
| 260 | 260 | $model_obj = $model->get_one_by_ID($obj_id); | 
| 261 | -        if (! $model_obj instanceof EE_Base_Class) { | |
| 261 | +        if ( ! $model_obj instanceof EE_Base_Class) { | |
| 262 | 262 | $lowercase_model_name = strtolower($model->get_this_model_name()); | 
| 263 | 263 | throw new RestException( | 
| 264 | 264 |                  sprintf('rest_%s_invalid_id', $lowercase_model_name), | 
| @@ -316,7 +316,7 @@ discard block | ||
| 316 | 316 |              } else { | 
| 317 | 317 | $raw_value = $model_obj->get_raw($field_name); | 
| 318 | 318 | } | 
| 319 | - $simulated_db_row[ $field_obj->get_qualified_column() ] = $field_obj->prepare_for_use_in_db($raw_value); | |
| 319 | + $simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value); | |
| 320 | 320 | } | 
| 321 | 321 |          $read_controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | 
| 322 | 322 | $read_controller->setRequestedVersion($this->getRequestedVersion()); | 
| @@ -434,7 +434,7 @@ discard block | ||
| 434 | 434 | ) | 
| 435 | 435 | ) | 
| 436 | 436 | ); | 
| 437 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 437 | + $response['join'][strtolower($relation->get_join_model()->get_this_model_name())] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 438 | 438 | } | 
| 439 | 439 | return $response; | 
| 440 | 440 | } | 
| @@ -482,7 +482,7 @@ discard block | ||
| 482 | 482 |      { | 
| 483 | 483 | // This endpoint doesn't accept body parameters (it's understandable to think it might, so let developers know | 
| 484 | 484 | // up-front that it doesn't.) | 
| 485 | -        if (!empty($request->get_body_params())) { | |
| 485 | +        if ( ! empty($request->get_body_params())) { | |
| 486 | 486 | $body_params = $request->get_body_params(); | 
| 487 | 487 | throw new RestException( | 
| 488 | 488 | 'invalid_field', | 
| @@ -524,9 +524,9 @@ discard block | ||
| 524 | 524 | ) | 
| 525 | 525 | ); | 
| 526 | 526 |              if ($join_model_obj instanceof EE_Base_Class) { | 
| 527 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 527 | + $response['join'][strtolower($relation->get_join_model()->get_this_model_name())] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 528 | 528 |              } else { | 
| 529 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = null; | |
| 529 | + $response['join'][strtolower($relation->get_join_model()->get_this_model_name())] = null; | |
| 530 | 530 | } | 
| 531 | 531 | } | 
| 532 | 532 | return $response; | 
| @@ -551,9 +551,9 @@ discard block | ||
| 551 | 551 | // Check generic caps. For now, we're only allowing access to this endpoint to full admins. | 
| 552 | 552 | Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | 
| 553 | 553 | $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | 
| 554 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 554 | +        if ( ! current_user_can($default_cap_to_check_for)) { | |
| 555 | 555 | throw new RestException( | 
| 556 | - 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 556 | + 'rest_cannot_edit_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 557 | 557 | sprintf( | 
| 558 | 558 | esc_html__( | 
| 559 | 559 | // @codingStandardsIgnoreStart | 
| @@ -570,7 +570,7 @@ discard block | ||
| 570 | 570 |          $model_obj = $this->getOneOrThrowException($model, $request->get_param('id')); | 
| 571 | 571 | // For now, we require the other model object to exist too. This might be relaxed later. | 
| 572 | 572 |          $other_obj = $this->getOneOrThrowException($relation->get_other_model(), $request->get_param('related_id')); | 
| 573 | - return array($model_obj,$other_obj); | |
| 573 | + return array($model_obj, $other_obj); | |
| 574 | 574 | } | 
| 575 | 575 | |
| 576 | 576 | /** | 
| @@ -39,573 +39,573 @@ | ||
| 39 | 39 |  { | 
| 40 | 40 | |
| 41 | 41 | |
| 42 | - public function __construct() | |
| 43 | -    { | |
| 44 | - parent::__construct(); | |
| 45 | -        EE_Registry::instance()->load_helper('Inflector'); | |
| 46 | - } | |
| 42 | + public function __construct() | |
| 43 | +	{ | |
| 44 | + parent::__construct(); | |
| 45 | +		EE_Registry::instance()->load_helper('Inflector'); | |
| 46 | + } | |
| 47 | 47 | |
| 48 | 48 | |
| 49 | - /** | |
| 50 | - * Handles requests to get all (or a filtered subset) of entities for a particular model | |
| 51 | - * | |
| 52 | - * @param WP_REST_Request $request | |
| 53 | - * @param string $version | |
| 54 | - * @param string $model_name | |
| 55 | - * @return WP_REST_Response|\WP_Error | |
| 56 | - */ | |
| 57 | - public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name) | |
| 58 | -    { | |
| 59 | - $controller = new Write(); | |
| 60 | -        try { | |
| 61 | - $controller->setRequestedVersion($version); | |
| 62 | - return $controller->sendResponse( | |
| 63 | - $controller->insert( | |
| 64 | - $controller->getModelVersionInfo()->loadModel($model_name), | |
| 65 | - $request | |
| 66 | - ) | |
| 67 | - ); | |
| 68 | -        } catch (Exception $e) { | |
| 69 | - return $controller->sendResponse($e); | |
| 70 | - } | |
| 71 | - } | |
| 49 | + /** | |
| 50 | + * Handles requests to get all (or a filtered subset) of entities for a particular model | |
| 51 | + * | |
| 52 | + * @param WP_REST_Request $request | |
| 53 | + * @param string $version | |
| 54 | + * @param string $model_name | |
| 55 | + * @return WP_REST_Response|\WP_Error | |
| 56 | + */ | |
| 57 | + public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name) | |
| 58 | +	{ | |
| 59 | + $controller = new Write(); | |
| 60 | +		try { | |
| 61 | + $controller->setRequestedVersion($version); | |
| 62 | + return $controller->sendResponse( | |
| 63 | + $controller->insert( | |
| 64 | + $controller->getModelVersionInfo()->loadModel($model_name), | |
| 65 | + $request | |
| 66 | + ) | |
| 67 | + ); | |
| 68 | +		} catch (Exception $e) { | |
| 69 | + return $controller->sendResponse($e); | |
| 70 | + } | |
| 71 | + } | |
| 72 | 72 | |
| 73 | 73 | |
| 74 | - /** | |
| 75 | - * Handles a request from \WP_REST_Server to update an EE model | |
| 76 | - * | |
| 77 | - * @param WP_REST_Request $request | |
| 78 | - * @param string $version | |
| 79 | - * @param string $model_name | |
| 80 | - * @return WP_REST_Response|\WP_Error | |
| 81 | - */ | |
| 82 | - public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name) | |
| 83 | -    { | |
| 84 | - $controller = new Write(); | |
| 85 | -        try { | |
| 86 | - $controller->setRequestedVersion($version); | |
| 87 | - return $controller->sendResponse( | |
| 88 | - $controller->update( | |
| 89 | - $controller->getModelVersionInfo()->loadModel($model_name), | |
| 90 | - $request | |
| 91 | - ) | |
| 92 | - ); | |
| 93 | -        } catch (Exception $e) { | |
| 94 | - return $controller->sendResponse($e); | |
| 95 | - } | |
| 96 | - } | |
| 74 | + /** | |
| 75 | + * Handles a request from \WP_REST_Server to update an EE model | |
| 76 | + * | |
| 77 | + * @param WP_REST_Request $request | |
| 78 | + * @param string $version | |
| 79 | + * @param string $model_name | |
| 80 | + * @return WP_REST_Response|\WP_Error | |
| 81 | + */ | |
| 82 | + public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name) | |
| 83 | +	{ | |
| 84 | + $controller = new Write(); | |
| 85 | +		try { | |
| 86 | + $controller->setRequestedVersion($version); | |
| 87 | + return $controller->sendResponse( | |
| 88 | + $controller->update( | |
| 89 | + $controller->getModelVersionInfo()->loadModel($model_name), | |
| 90 | + $request | |
| 91 | + ) | |
| 92 | + ); | |
| 93 | +		} catch (Exception $e) { | |
| 94 | + return $controller->sendResponse($e); | |
| 95 | + } | |
| 96 | + } | |
| 97 | 97 | |
| 98 | 98 | |
| 99 | - /** | |
| 100 | - * Deletes a single model object and returns it. Unless | |
| 101 | - * | |
| 102 | - * @param WP_REST_Request $request | |
| 103 | - * @param string $version | |
| 104 | - * @param string $model_name | |
| 105 | - * @return WP_REST_Response|\WP_Error | |
| 106 | - */ | |
| 107 | - public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name) | |
| 108 | -    { | |
| 109 | - $controller = new Write(); | |
| 110 | -        try { | |
| 111 | - $controller->setRequestedVersion($version); | |
| 112 | - return $controller->sendResponse( | |
| 113 | - $controller->delete( | |
| 114 | - $controller->getModelVersionInfo()->loadModel($model_name), | |
| 115 | - $request | |
| 116 | - ) | |
| 117 | - ); | |
| 118 | -        } catch (Exception $e) { | |
| 119 | - return $controller->sendResponse($e); | |
| 120 | - } | |
| 121 | - } | |
| 99 | + /** | |
| 100 | + * Deletes a single model object and returns it. Unless | |
| 101 | + * | |
| 102 | + * @param WP_REST_Request $request | |
| 103 | + * @param string $version | |
| 104 | + * @param string $model_name | |
| 105 | + * @return WP_REST_Response|\WP_Error | |
| 106 | + */ | |
| 107 | + public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name) | |
| 108 | +	{ | |
| 109 | + $controller = new Write(); | |
| 110 | +		try { | |
| 111 | + $controller->setRequestedVersion($version); | |
| 112 | + return $controller->sendResponse( | |
| 113 | + $controller->delete( | |
| 114 | + $controller->getModelVersionInfo()->loadModel($model_name), | |
| 115 | + $request | |
| 116 | + ) | |
| 117 | + ); | |
| 118 | +		} catch (Exception $e) { | |
| 119 | + return $controller->sendResponse($e); | |
| 120 | + } | |
| 121 | + } | |
| 122 | 122 | |
| 123 | 123 | |
| 124 | - /** | |
| 125 | - * Inserts a new model object according to the $request | |
| 126 | - * | |
| 127 | - * @param EEM_Base $model | |
| 128 | - * @param WP_REST_Request $request | |
| 129 | - * @return array | |
| 130 | - * @throws EE_Error | |
| 131 | - * @throws RestException | |
| 132 | - */ | |
| 133 | - public function insert(EEM_Base $model, WP_REST_Request $request) | |
| 134 | -    { | |
| 135 | - Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create'); | |
| 136 | - $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 137 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 138 | - throw new RestException( | |
| 139 | - 'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 140 | - sprintf( | |
| 141 | - esc_html__( | |
| 142 | - // @codingStandardsIgnoreStart | |
| 143 | - 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.', | |
| 144 | - // @codingStandardsIgnoreEnd | |
| 145 | - 'event_espresso' | |
| 146 | - ), | |
| 147 | - $default_cap_to_check_for | |
| 148 | - ), | |
| 149 | -                array('status' => 403) | |
| 150 | - ); | |
| 151 | - } | |
| 152 | - $submitted_json_data = array_merge((array) $request->get_body_params(), (array) $request->get_json_params()); | |
| 153 | - $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 154 | - $submitted_json_data, | |
| 155 | - $model, | |
| 156 | - $this->getModelVersionInfo()->requestedVersion(), | |
| 157 | - true | |
| 158 | - ); | |
| 159 | - $model_obj = EE_Registry::instance()->load_class( | |
| 160 | - $model->get_this_model_name(), | |
| 161 | - array($model_data, $model->get_timezone()), | |
| 162 | - false, | |
| 163 | - false | |
| 164 | - ); | |
| 165 | - $model_obj->save(); | |
| 166 | - $new_id = $model_obj->ID(); | |
| 167 | -        if (! $new_id) { | |
| 168 | - throw new RestException( | |
| 169 | - 'rest_insertion_failed', | |
| 170 | -                sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name()) | |
| 171 | - ); | |
| 172 | - } | |
| 173 | - return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 174 | - } | |
| 124 | + /** | |
| 125 | + * Inserts a new model object according to the $request | |
| 126 | + * | |
| 127 | + * @param EEM_Base $model | |
| 128 | + * @param WP_REST_Request $request | |
| 129 | + * @return array | |
| 130 | + * @throws EE_Error | |
| 131 | + * @throws RestException | |
| 132 | + */ | |
| 133 | + public function insert(EEM_Base $model, WP_REST_Request $request) | |
| 134 | +	{ | |
| 135 | + Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create'); | |
| 136 | + $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 137 | +		if (! current_user_can($default_cap_to_check_for)) { | |
| 138 | + throw new RestException( | |
| 139 | + 'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 140 | + sprintf( | |
| 141 | + esc_html__( | |
| 142 | + // @codingStandardsIgnoreStart | |
| 143 | + 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.', | |
| 144 | + // @codingStandardsIgnoreEnd | |
| 145 | + 'event_espresso' | |
| 146 | + ), | |
| 147 | + $default_cap_to_check_for | |
| 148 | + ), | |
| 149 | +				array('status' => 403) | |
| 150 | + ); | |
| 151 | + } | |
| 152 | + $submitted_json_data = array_merge((array) $request->get_body_params(), (array) $request->get_json_params()); | |
| 153 | + $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 154 | + $submitted_json_data, | |
| 155 | + $model, | |
| 156 | + $this->getModelVersionInfo()->requestedVersion(), | |
| 157 | + true | |
| 158 | + ); | |
| 159 | + $model_obj = EE_Registry::instance()->load_class( | |
| 160 | + $model->get_this_model_name(), | |
| 161 | + array($model_data, $model->get_timezone()), | |
| 162 | + false, | |
| 163 | + false | |
| 164 | + ); | |
| 165 | + $model_obj->save(); | |
| 166 | + $new_id = $model_obj->ID(); | |
| 167 | +		if (! $new_id) { | |
| 168 | + throw new RestException( | |
| 169 | + 'rest_insertion_failed', | |
| 170 | +				sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name()) | |
| 171 | + ); | |
| 172 | + } | |
| 173 | + return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 174 | + } | |
| 175 | 175 | |
| 176 | 176 | |
| 177 | - /** | |
| 178 | - * Updates an existing model object according to the $request | |
| 179 | - * | |
| 180 | - * @param EEM_Base $model | |
| 181 | - * @param WP_REST_Request $request | |
| 182 | - * @return array | |
| 183 | - * @throws EE_Error | |
| 184 | - */ | |
| 185 | - public function update(EEM_Base $model, WP_REST_Request $request) | |
| 186 | -    { | |
| 187 | - Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | |
| 188 | - $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 189 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 190 | - throw new RestException( | |
| 191 | - 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 192 | - sprintf( | |
| 193 | - esc_html__( | |
| 194 | - // @codingStandardsIgnoreStart | |
| 195 | - 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.', | |
| 196 | - // @codingStandardsIgnoreEnd | |
| 197 | - 'event_espresso' | |
| 198 | - ), | |
| 199 | - $default_cap_to_check_for | |
| 200 | - ), | |
| 201 | -                array('status' => 403) | |
| 202 | - ); | |
| 203 | - } | |
| 204 | -        $obj_id = $request->get_param('id'); | |
| 205 | -        if (! $obj_id) { | |
| 206 | - throw new RestException( | |
| 207 | - 'rest_edit_failed', | |
| 208 | -                sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name()) | |
| 209 | - ); | |
| 210 | - } | |
| 211 | - $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 212 | - $this->getBodyParams($request), | |
| 213 | - $model, | |
| 214 | - $this->getModelVersionInfo()->requestedVersion(), | |
| 215 | - true | |
| 216 | - ); | |
| 217 | - $model_obj = $model->get_one_by_ID($obj_id); | |
| 218 | -        if (! $model_obj instanceof EE_Base_Class) { | |
| 219 | - $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 220 | - throw new RestException( | |
| 221 | -                sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 222 | -                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 223 | -                array('status' => 404) | |
| 224 | - ); | |
| 225 | - } | |
| 226 | - $model_obj->save($model_data); | |
| 227 | - return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 228 | - } | |
| 177 | + /** | |
| 178 | + * Updates an existing model object according to the $request | |
| 179 | + * | |
| 180 | + * @param EEM_Base $model | |
| 181 | + * @param WP_REST_Request $request | |
| 182 | + * @return array | |
| 183 | + * @throws EE_Error | |
| 184 | + */ | |
| 185 | + public function update(EEM_Base $model, WP_REST_Request $request) | |
| 186 | +	{ | |
| 187 | + Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | |
| 188 | + $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 189 | +		if (! current_user_can($default_cap_to_check_for)) { | |
| 190 | + throw new RestException( | |
| 191 | + 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 192 | + sprintf( | |
| 193 | + esc_html__( | |
| 194 | + // @codingStandardsIgnoreStart | |
| 195 | + 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.', | |
| 196 | + // @codingStandardsIgnoreEnd | |
| 197 | + 'event_espresso' | |
| 198 | + ), | |
| 199 | + $default_cap_to_check_for | |
| 200 | + ), | |
| 201 | +				array('status' => 403) | |
| 202 | + ); | |
| 203 | + } | |
| 204 | +		$obj_id = $request->get_param('id'); | |
| 205 | +		if (! $obj_id) { | |
| 206 | + throw new RestException( | |
| 207 | + 'rest_edit_failed', | |
| 208 | +				sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name()) | |
| 209 | + ); | |
| 210 | + } | |
| 211 | + $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 212 | + $this->getBodyParams($request), | |
| 213 | + $model, | |
| 214 | + $this->getModelVersionInfo()->requestedVersion(), | |
| 215 | + true | |
| 216 | + ); | |
| 217 | + $model_obj = $model->get_one_by_ID($obj_id); | |
| 218 | +		if (! $model_obj instanceof EE_Base_Class) { | |
| 219 | + $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 220 | + throw new RestException( | |
| 221 | +				sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 222 | +				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 223 | +				array('status' => 404) | |
| 224 | + ); | |
| 225 | + } | |
| 226 | + $model_obj->save($model_data); | |
| 227 | + return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 228 | + } | |
| 229 | 229 | |
| 230 | 230 | |
| 231 | - /** | |
| 232 | - * Updates an existing model object according to the $request | |
| 233 | - * | |
| 234 | - * @param EEM_Base $model | |
| 235 | - * @param WP_REST_Request $request | |
| 236 | - * @return array of either the soft-deleted item, or | |
| 237 | - * @throws EE_Error | |
| 238 | - */ | |
| 239 | - public function delete(EEM_Base $model, WP_REST_Request $request) | |
| 240 | -    { | |
| 241 | - Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete'); | |
| 242 | - $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 243 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 244 | - throw new RestException( | |
| 245 | - 'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 246 | - sprintf( | |
| 247 | - esc_html__( | |
| 248 | - // @codingStandardsIgnoreStart | |
| 249 | - 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.', | |
| 250 | - // @codingStandardsIgnoreEnd | |
| 251 | - 'event_espresso' | |
| 252 | - ), | |
| 253 | - $default_cap_to_check_for | |
| 254 | - ), | |
| 255 | -                array('status' => 403) | |
| 256 | - ); | |
| 257 | - } | |
| 258 | -        $obj_id = $request->get_param('id'); | |
| 259 | - // this is where we would apply more fine-grained caps | |
| 260 | - $model_obj = $model->get_one_by_ID($obj_id); | |
| 261 | -        if (! $model_obj instanceof EE_Base_Class) { | |
| 262 | - $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 263 | - throw new RestException( | |
| 264 | -                sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 265 | -                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 266 | -                array('status' => 404) | |
| 267 | - ); | |
| 268 | - } | |
| 269 | -        $requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN); | |
| 270 | -        $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN); | |
| 271 | -        if ($requested_permanent_delete) { | |
| 272 | - $previous = $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 273 | - $deleted = (bool) $model->delete_permanently_by_ID($obj_id, $requested_allow_blocking); | |
| 274 | - return array( | |
| 275 | - 'deleted' => $deleted, | |
| 276 | - 'previous' => $previous, | |
| 277 | - ); | |
| 278 | -        } else { | |
| 279 | -            if ($model instanceof EEM_Soft_Delete_Base) { | |
| 280 | - $model->delete_by_ID($obj_id, $requested_allow_blocking); | |
| 281 | - return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 282 | -            } else { | |
| 283 | - throw new RestException( | |
| 284 | - 'rest_trash_not_supported', | |
| 285 | - 501, | |
| 286 | - sprintf( | |
| 287 | -                        esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'), | |
| 288 | - EEH_Inflector::pluralize($model->get_this_model_name()) | |
| 289 | - ) | |
| 290 | - ); | |
| 291 | - } | |
| 292 | - } | |
| 293 | - } | |
| 231 | + /** | |
| 232 | + * Updates an existing model object according to the $request | |
| 233 | + * | |
| 234 | + * @param EEM_Base $model | |
| 235 | + * @param WP_REST_Request $request | |
| 236 | + * @return array of either the soft-deleted item, or | |
| 237 | + * @throws EE_Error | |
| 238 | + */ | |
| 239 | + public function delete(EEM_Base $model, WP_REST_Request $request) | |
| 240 | +	{ | |
| 241 | + Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete'); | |
| 242 | + $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 243 | +		if (! current_user_can($default_cap_to_check_for)) { | |
| 244 | + throw new RestException( | |
| 245 | + 'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 246 | + sprintf( | |
| 247 | + esc_html__( | |
| 248 | + // @codingStandardsIgnoreStart | |
| 249 | + 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.', | |
| 250 | + // @codingStandardsIgnoreEnd | |
| 251 | + 'event_espresso' | |
| 252 | + ), | |
| 253 | + $default_cap_to_check_for | |
| 254 | + ), | |
| 255 | +				array('status' => 403) | |
| 256 | + ); | |
| 257 | + } | |
| 258 | +		$obj_id = $request->get_param('id'); | |
| 259 | + // this is where we would apply more fine-grained caps | |
| 260 | + $model_obj = $model->get_one_by_ID($obj_id); | |
| 261 | +		if (! $model_obj instanceof EE_Base_Class) { | |
| 262 | + $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 263 | + throw new RestException( | |
| 264 | +				sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 265 | +				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 266 | +				array('status' => 404) | |
| 267 | + ); | |
| 268 | + } | |
| 269 | +		$requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN); | |
| 270 | +		$requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN); | |
| 271 | +		if ($requested_permanent_delete) { | |
| 272 | + $previous = $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 273 | + $deleted = (bool) $model->delete_permanently_by_ID($obj_id, $requested_allow_blocking); | |
| 274 | + return array( | |
| 275 | + 'deleted' => $deleted, | |
| 276 | + 'previous' => $previous, | |
| 277 | + ); | |
| 278 | +		} else { | |
| 279 | +			if ($model instanceof EEM_Soft_Delete_Base) { | |
| 280 | + $model->delete_by_ID($obj_id, $requested_allow_blocking); | |
| 281 | + return $this->returnModelObjAsJsonResponse($model_obj, $request); | |
| 282 | +			} else { | |
| 283 | + throw new RestException( | |
| 284 | + 'rest_trash_not_supported', | |
| 285 | + 501, | |
| 286 | + sprintf( | |
| 287 | +						esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'), | |
| 288 | + EEH_Inflector::pluralize($model->get_this_model_name()) | |
| 289 | + ) | |
| 290 | + ); | |
| 291 | + } | |
| 292 | + } | |
| 293 | + } | |
| 294 | 294 | |
| 295 | 295 | |
| 296 | - /** | |
| 297 | - * Returns an array ready to be converted into a JSON response, based solely on the model object | |
| 298 | - * | |
| 299 | - * @param EE_Base_Class $model_obj | |
| 300 | - * @param WP_REST_Request $request | |
| 301 | - * @return array ready for a response | |
| 302 | - */ | |
| 303 | - protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request) | |
| 304 | -    { | |
| 305 | - $model = $model_obj->get_model(); | |
| 306 | - // create an array exactly like the wpdb results row, | |
| 307 | - // so we can pass it to controllers/model/Read::create_entity_from_wpdb_result() | |
| 308 | - $simulated_db_row = array(); | |
| 309 | -        foreach ($model->field_settings(true) as $field_name => $field_obj) { | |
| 310 | - // we need to reconstruct the normal wpdb results, including the db-only fields | |
| 311 | - // like a secondary table's primary key. The models expect those (but don't care what value they have) | |
| 312 | -            if ($field_obj instanceof EE_DB_Only_Field_Base) { | |
| 313 | - $raw_value = true; | |
| 314 | -            } elseif ($field_obj instanceof EE_Datetime_Field) { | |
| 315 | - $raw_value = $model_obj->get_DateTime_object($field_name); | |
| 316 | -            } else { | |
| 317 | - $raw_value = $model_obj->get_raw($field_name); | |
| 318 | - } | |
| 319 | - $simulated_db_row[ $field_obj->get_qualified_column() ] = $field_obj->prepare_for_use_in_db($raw_value); | |
| 320 | - } | |
| 321 | -        $read_controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 322 | - $read_controller->setRequestedVersion($this->getRequestedVersion()); | |
| 323 | - // the simulates request really doesn't need any info downstream | |
| 324 | -        $simulated_request = new WP_REST_Request('GET'); | |
| 325 | - // set the caps context on the simulated according to the original request. | |
| 326 | -        switch ($request->get_method()) { | |
| 327 | - case 'POST': | |
| 328 | - case 'PUT': | |
| 329 | - $caps_context = EEM_Base::caps_edit; | |
| 330 | - break; | |
| 331 | - case 'DELETE': | |
| 332 | - $caps_context = EEM_Base::caps_delete; | |
| 333 | - break; | |
| 334 | - default: | |
| 335 | - $caps_context = EEM_Base::caps_read_admin; | |
| 336 | - } | |
| 337 | -        $simulated_request->set_param('caps', $caps_context); | |
| 338 | - return $read_controller->createEntityFromWpdbResult( | |
| 339 | - $model_obj->get_model(), | |
| 340 | - $simulated_db_row, | |
| 341 | - $simulated_request | |
| 342 | - ); | |
| 343 | - } | |
| 296 | + /** | |
| 297 | + * Returns an array ready to be converted into a JSON response, based solely on the model object | |
| 298 | + * | |
| 299 | + * @param EE_Base_Class $model_obj | |
| 300 | + * @param WP_REST_Request $request | |
| 301 | + * @return array ready for a response | |
| 302 | + */ | |
| 303 | + protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request) | |
| 304 | +	{ | |
| 305 | + $model = $model_obj->get_model(); | |
| 306 | + // create an array exactly like the wpdb results row, | |
| 307 | + // so we can pass it to controllers/model/Read::create_entity_from_wpdb_result() | |
| 308 | + $simulated_db_row = array(); | |
| 309 | +		foreach ($model->field_settings(true) as $field_name => $field_obj) { | |
| 310 | + // we need to reconstruct the normal wpdb results, including the db-only fields | |
| 311 | + // like a secondary table's primary key. The models expect those (but don't care what value they have) | |
| 312 | +			if ($field_obj instanceof EE_DB_Only_Field_Base) { | |
| 313 | + $raw_value = true; | |
| 314 | +			} elseif ($field_obj instanceof EE_Datetime_Field) { | |
| 315 | + $raw_value = $model_obj->get_DateTime_object($field_name); | |
| 316 | +			} else { | |
| 317 | + $raw_value = $model_obj->get_raw($field_name); | |
| 318 | + } | |
| 319 | + $simulated_db_row[ $field_obj->get_qualified_column() ] = $field_obj->prepare_for_use_in_db($raw_value); | |
| 320 | + } | |
| 321 | +		$read_controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 322 | + $read_controller->setRequestedVersion($this->getRequestedVersion()); | |
| 323 | + // the simulates request really doesn't need any info downstream | |
| 324 | +		$simulated_request = new WP_REST_Request('GET'); | |
| 325 | + // set the caps context on the simulated according to the original request. | |
| 326 | +		switch ($request->get_method()) { | |
| 327 | + case 'POST': | |
| 328 | + case 'PUT': | |
| 329 | + $caps_context = EEM_Base::caps_edit; | |
| 330 | + break; | |
| 331 | + case 'DELETE': | |
| 332 | + $caps_context = EEM_Base::caps_delete; | |
| 333 | + break; | |
| 334 | + default: | |
| 335 | + $caps_context = EEM_Base::caps_read_admin; | |
| 336 | + } | |
| 337 | +		$simulated_request->set_param('caps', $caps_context); | |
| 338 | + return $read_controller->createEntityFromWpdbResult( | |
| 339 | + $model_obj->get_model(), | |
| 340 | + $simulated_db_row, | |
| 341 | + $simulated_request | |
| 342 | + ); | |
| 343 | + } | |
| 344 | 344 | |
| 345 | 345 | |
| 346 | - /** | |
| 347 | - * Gets the item affected by this request | |
| 348 | - * | |
| 349 | - * @param EEM_Base $model | |
| 350 | - * @param WP_REST_Request $request | |
| 351 | - * @param int|string $obj_id | |
| 352 | - * @return \WP_Error|array | |
| 353 | - */ | |
| 354 | - protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id) | |
| 355 | -    { | |
| 356 | - $requested_version = $this->getRequestedVersion($request->get_route()); | |
| 357 | - $get_request = new WP_REST_Request( | |
| 358 | - 'GET', | |
| 359 | - EED_Core_Rest_Api::ee_api_namespace | |
| 360 | - . $requested_version | |
| 361 | - . '/' | |
| 362 | - . EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 363 | - . '/' | |
| 364 | - . $obj_id | |
| 365 | - ); | |
| 366 | - $get_request->set_url_params( | |
| 367 | - array( | |
| 368 | - 'id' => $obj_id, | |
| 369 | -                'include' => $request->get_param('include'), | |
| 370 | - ) | |
| 371 | - ); | |
| 372 | - $read_controller = new Read(); | |
| 373 | - $read_controller->setRequestedVersion($this->getRequestedVersion()); | |
| 374 | - return $read_controller->getEntityFromModel($model, $get_request); | |
| 375 | - } | |
| 346 | + /** | |
| 347 | + * Gets the item affected by this request | |
| 348 | + * | |
| 349 | + * @param EEM_Base $model | |
| 350 | + * @param WP_REST_Request $request | |
| 351 | + * @param int|string $obj_id | |
| 352 | + * @return \WP_Error|array | |
| 353 | + */ | |
| 354 | + protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id) | |
| 355 | +	{ | |
| 356 | + $requested_version = $this->getRequestedVersion($request->get_route()); | |
| 357 | + $get_request = new WP_REST_Request( | |
| 358 | + 'GET', | |
| 359 | + EED_Core_Rest_Api::ee_api_namespace | |
| 360 | + . $requested_version | |
| 361 | + . '/' | |
| 362 | + . EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 363 | + . '/' | |
| 364 | + . $obj_id | |
| 365 | + ); | |
| 366 | + $get_request->set_url_params( | |
| 367 | + array( | |
| 368 | + 'id' => $obj_id, | |
| 369 | +				'include' => $request->get_param('include'), | |
| 370 | + ) | |
| 371 | + ); | |
| 372 | + $read_controller = new Read(); | |
| 373 | + $read_controller->setRequestedVersion($this->getRequestedVersion()); | |
| 374 | + return $read_controller->getEntityFromModel($model, $get_request); | |
| 375 | + } | |
| 376 | 376 | |
| 377 | - /** | |
| 378 | - * Adds a relation between the specified models (if it doesn't already exist.) | |
| 379 | - * @since $VID:$ | |
| 380 | - * @param WP_REST_Request $request | |
| 381 | - * @return WP_REST_Response | |
| 382 | - */ | |
| 383 | - public static function handleRequestAddRelation(WP_REST_Request $request, $version, $model_name, $related_model_name) | |
| 384 | -    { | |
| 385 | - $controller = new Write(); | |
| 386 | -        try { | |
| 387 | - $controller->setRequestedVersion($version); | |
| 388 | - $main_model = $controller->validateModel($model_name); | |
| 389 | - $controller->validateModel($related_model_name); | |
| 390 | - return $controller->sendResponse( | |
| 391 | - $controller->addRelation( | |
| 392 | - $main_model, | |
| 393 | - $main_model->related_settings_for($related_model_name), | |
| 394 | - $request | |
| 395 | - ) | |
| 396 | - ); | |
| 397 | -        } catch (Exception $e) { | |
| 398 | - return $controller->sendResponse($e); | |
| 399 | - } | |
| 400 | - } | |
| 377 | + /** | |
| 378 | + * Adds a relation between the specified models (if it doesn't already exist.) | |
| 379 | + * @since $VID:$ | |
| 380 | + * @param WP_REST_Request $request | |
| 381 | + * @return WP_REST_Response | |
| 382 | + */ | |
| 383 | + public static function handleRequestAddRelation(WP_REST_Request $request, $version, $model_name, $related_model_name) | |
| 384 | +	{ | |
| 385 | + $controller = new Write(); | |
| 386 | +		try { | |
| 387 | + $controller->setRequestedVersion($version); | |
| 388 | + $main_model = $controller->validateModel($model_name); | |
| 389 | + $controller->validateModel($related_model_name); | |
| 390 | + return $controller->sendResponse( | |
| 391 | + $controller->addRelation( | |
| 392 | + $main_model, | |
| 393 | + $main_model->related_settings_for($related_model_name), | |
| 394 | + $request | |
| 395 | + ) | |
| 396 | + ); | |
| 397 | +		} catch (Exception $e) { | |
| 398 | + return $controller->sendResponse($e); | |
| 399 | + } | |
| 400 | + } | |
| 401 | 401 | |
| 402 | - /** | |
| 403 | - * Adds a relation between the two model specified model objects. | |
| 404 | - * @since $VID:$ | |
| 405 | - * @param EEM_Base $model | |
| 406 | - * @param EE_Model_Relation_Base $relation | |
| 407 | - * @param WP_REST_Request $request | |
| 408 | - * @return array | |
| 409 | - * @throws EE_Error | |
| 410 | - * @throws InvalidArgumentException | |
| 411 | - * @throws InvalidDataTypeException | |
| 412 | - * @throws InvalidInterfaceException | |
| 413 | - * @throws RestException | |
| 414 | - * @throws DomainException | |
| 415 | - */ | |
| 416 | - public function addRelation(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 417 | -    { | |
| 418 | - list($model_obj, $other_obj) = $this->getBothModelObjects($model, $relation, $request); | |
| 419 | - $extra_params = array(); | |
| 420 | -        if ($relation instanceof EE_HABTM_Relation) { | |
| 421 | - $extra_params = array_intersect_key( | |
| 422 | - ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 423 | - $request->get_body_params(), | |
| 424 | - $relation->get_join_model(), | |
| 425 | - $this->getModelVersionInfo()->requestedVersion(), | |
| 426 | - true | |
| 427 | - ), | |
| 428 | - $relation->getNonKeyFields() | |
| 429 | - ); | |
| 430 | - } | |
| 431 | - // Add a relation. | |
| 432 | - $related_obj = $model_obj->_add_relation_to( | |
| 433 | - $other_obj, | |
| 434 | - $relation->get_other_model()->get_this_model_name(), | |
| 435 | - $extra_params | |
| 436 | - ); | |
| 437 | - $response = array( | |
| 438 | - strtolower($model->get_this_model_name()) => $this->returnModelObjAsJsonResponse($model_obj, $request), | |
| 439 | - strtolower($relation->get_other_model()->get_this_model_name()) => $this->returnModelObjAsJsonResponse($related_obj, $request), | |
| 440 | - ); | |
| 441 | -        if ($relation instanceof EE_HABTM_Relation) { | |
| 442 | - $join_model_obj = $relation->get_join_model()->get_one( | |
| 443 | - array( | |
| 444 | - array( | |
| 445 | - $model->primary_key_name() => $model_obj->ID(), | |
| 446 | - $relation->get_other_model()->primary_key_name() => $related_obj->ID() | |
| 447 | - ) | |
| 448 | - ) | |
| 449 | - ); | |
| 450 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 451 | - } | |
| 452 | - return $response; | |
| 453 | - } | |
| 402 | + /** | |
| 403 | + * Adds a relation between the two model specified model objects. | |
| 404 | + * @since $VID:$ | |
| 405 | + * @param EEM_Base $model | |
| 406 | + * @param EE_Model_Relation_Base $relation | |
| 407 | + * @param WP_REST_Request $request | |
| 408 | + * @return array | |
| 409 | + * @throws EE_Error | |
| 410 | + * @throws InvalidArgumentException | |
| 411 | + * @throws InvalidDataTypeException | |
| 412 | + * @throws InvalidInterfaceException | |
| 413 | + * @throws RestException | |
| 414 | + * @throws DomainException | |
| 415 | + */ | |
| 416 | + public function addRelation(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 417 | +	{ | |
| 418 | + list($model_obj, $other_obj) = $this->getBothModelObjects($model, $relation, $request); | |
| 419 | + $extra_params = array(); | |
| 420 | +		if ($relation instanceof EE_HABTM_Relation) { | |
| 421 | + $extra_params = array_intersect_key( | |
| 422 | + ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 423 | + $request->get_body_params(), | |
| 424 | + $relation->get_join_model(), | |
| 425 | + $this->getModelVersionInfo()->requestedVersion(), | |
| 426 | + true | |
| 427 | + ), | |
| 428 | + $relation->getNonKeyFields() | |
| 429 | + ); | |
| 430 | + } | |
| 431 | + // Add a relation. | |
| 432 | + $related_obj = $model_obj->_add_relation_to( | |
| 433 | + $other_obj, | |
| 434 | + $relation->get_other_model()->get_this_model_name(), | |
| 435 | + $extra_params | |
| 436 | + ); | |
| 437 | + $response = array( | |
| 438 | + strtolower($model->get_this_model_name()) => $this->returnModelObjAsJsonResponse($model_obj, $request), | |
| 439 | + strtolower($relation->get_other_model()->get_this_model_name()) => $this->returnModelObjAsJsonResponse($related_obj, $request), | |
| 440 | + ); | |
| 441 | +		if ($relation instanceof EE_HABTM_Relation) { | |
| 442 | + $join_model_obj = $relation->get_join_model()->get_one( | |
| 443 | + array( | |
| 444 | + array( | |
| 445 | + $model->primary_key_name() => $model_obj->ID(), | |
| 446 | + $relation->get_other_model()->primary_key_name() => $related_obj->ID() | |
| 447 | + ) | |
| 448 | + ) | |
| 449 | + ); | |
| 450 | + $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 451 | + } | |
| 452 | + return $response; | |
| 453 | + } | |
| 454 | 454 | |
| 455 | 455 | |
| 456 | - /** | |
| 457 | - * Removes the relation between the specified models (if it exists). | |
| 458 | - * @since $VID:$ | |
| 459 | - * @param WP_REST_Request $request | |
| 460 | - * @return WP_REST_Response | |
| 461 | - */ | |
| 462 | - public static function handleRequestRemoveRelation(WP_REST_Request $request, $version, $model_name, $related_model_name) | |
| 463 | -    { | |
| 464 | - $controller = new Write(); | |
| 465 | -        try { | |
| 466 | - $controller->setRequestedVersion($version); | |
| 467 | - $main_model = $controller->getModelVersionInfo()->loadModel($model_name); | |
| 468 | - return $controller->sendResponse( | |
| 469 | - $controller->removeRelation( | |
| 470 | - $main_model, | |
| 471 | - $main_model->related_settings_for($related_model_name), | |
| 472 | - $request | |
| 473 | - ) | |
| 474 | - ); | |
| 475 | -        } catch (Exception $e) { | |
| 476 | - return $controller->sendResponse($e); | |
| 477 | - } | |
| 478 | - } | |
| 456 | + /** | |
| 457 | + * Removes the relation between the specified models (if it exists). | |
| 458 | + * @since $VID:$ | |
| 459 | + * @param WP_REST_Request $request | |
| 460 | + * @return WP_REST_Response | |
| 461 | + */ | |
| 462 | + public static function handleRequestRemoveRelation(WP_REST_Request $request, $version, $model_name, $related_model_name) | |
| 463 | +	{ | |
| 464 | + $controller = new Write(); | |
| 465 | +		try { | |
| 466 | + $controller->setRequestedVersion($version); | |
| 467 | + $main_model = $controller->getModelVersionInfo()->loadModel($model_name); | |
| 468 | + return $controller->sendResponse( | |
| 469 | + $controller->removeRelation( | |
| 470 | + $main_model, | |
| 471 | + $main_model->related_settings_for($related_model_name), | |
| 472 | + $request | |
| 473 | + ) | |
| 474 | + ); | |
| 475 | +		} catch (Exception $e) { | |
| 476 | + return $controller->sendResponse($e); | |
| 477 | + } | |
| 478 | + } | |
| 479 | 479 | |
| 480 | - /** | |
| 481 | - * Adds a relation between the two model specified model objects. | |
| 482 | - * @since $VID:$ | |
| 483 | - * @param EEM_Base $model | |
| 484 | - * @param EE_Model_Relation_Base $relation | |
| 485 | - * @param WP_REST_Request $request | |
| 486 | - * @return array | |
| 487 | - * @throws DomainException | |
| 488 | - * @throws EE_Error | |
| 489 | - * @throws InvalidArgumentException | |
| 490 | - * @throws InvalidDataTypeException | |
| 491 | - * @throws InvalidInterfaceException | |
| 492 | - * @throws RestException | |
| 493 | - */ | |
| 494 | - public function removeRelation(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 495 | -    { | |
| 496 | - // This endpoint doesn't accept body parameters (it's understandable to think it might, so let developers know | |
| 497 | - // up-front that it doesn't.) | |
| 498 | -        if (!empty($request->get_body_params())) { | |
| 499 | - $body_params = $request->get_body_params(); | |
| 500 | - throw new RestException( | |
| 501 | - 'invalid_field', | |
| 502 | - sprintf( | |
| 503 | -                    esc_html__('This endpoint doesn\'t accept post body arguments, you sent in %1$s', 'event_espresso'), | |
| 504 | - implode(array_keys($body_params)) | |
| 505 | - ) | |
| 506 | - ); | |
| 507 | - } | |
| 508 | - list($model_obj, $other_obj) = $this->getBothModelObjects($model, $relation, $request); | |
| 509 | - // Remember the old relation, if it used a join entry. | |
| 510 | - $join_model_obj = null; | |
| 511 | -        if ($relation instanceof EE_HABTM_Relation) { | |
| 512 | - $join_model_obj = $relation->get_join_model()->get_one( | |
| 513 | - array( | |
| 514 | - array( | |
| 515 | - $model->primary_key_name() => $model_obj->ID(), | |
| 516 | - $relation->get_other_model()->primary_key_name() => $other_obj->ID() | |
| 517 | - ) | |
| 518 | - ) | |
| 519 | - ); | |
| 520 | - } | |
| 521 | - // Remove the relation. | |
| 522 | - $related_obj = $model_obj->_remove_relation_to( | |
| 523 | - $other_obj, | |
| 524 | - $relation->get_other_model()->get_this_model_name() | |
| 525 | - ); | |
| 526 | - $response = array( | |
| 527 | - strtolower($model->get_this_model_name()) => $this->returnModelObjAsJsonResponse($model_obj, $request), | |
| 528 | - strtolower($relation->get_other_model()->get_this_model_name()) => $this->returnModelObjAsJsonResponse($related_obj, $request), | |
| 529 | - ); | |
| 530 | -        if ($relation instanceof EE_HABTM_Relation) { | |
| 531 | - $join_model_obj_after_removal = $relation->get_join_model()->get_one( | |
| 532 | - array( | |
| 533 | - array( | |
| 534 | - $model->primary_key_name() => $model_obj->ID(), | |
| 535 | - $relation->get_other_model()->primary_key_name() => $other_obj->ID() | |
| 536 | - ) | |
| 537 | - ) | |
| 538 | - ); | |
| 539 | -            if ($join_model_obj instanceof EE_Base_Class) { | |
| 540 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 541 | -            } else { | |
| 542 | - $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = null; | |
| 543 | - } | |
| 544 | - } | |
| 545 | - return $response; | |
| 546 | - } | |
| 480 | + /** | |
| 481 | + * Adds a relation between the two model specified model objects. | |
| 482 | + * @since $VID:$ | |
| 483 | + * @param EEM_Base $model | |
| 484 | + * @param EE_Model_Relation_Base $relation | |
| 485 | + * @param WP_REST_Request $request | |
| 486 | + * @return array | |
| 487 | + * @throws DomainException | |
| 488 | + * @throws EE_Error | |
| 489 | + * @throws InvalidArgumentException | |
| 490 | + * @throws InvalidDataTypeException | |
| 491 | + * @throws InvalidInterfaceException | |
| 492 | + * @throws RestException | |
| 493 | + */ | |
| 494 | + public function removeRelation(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 495 | +	{ | |
| 496 | + // This endpoint doesn't accept body parameters (it's understandable to think it might, so let developers know | |
| 497 | + // up-front that it doesn't.) | |
| 498 | +		if (!empty($request->get_body_params())) { | |
| 499 | + $body_params = $request->get_body_params(); | |
| 500 | + throw new RestException( | |
| 501 | + 'invalid_field', | |
| 502 | + sprintf( | |
| 503 | +					esc_html__('This endpoint doesn\'t accept post body arguments, you sent in %1$s', 'event_espresso'), | |
| 504 | + implode(array_keys($body_params)) | |
| 505 | + ) | |
| 506 | + ); | |
| 507 | + } | |
| 508 | + list($model_obj, $other_obj) = $this->getBothModelObjects($model, $relation, $request); | |
| 509 | + // Remember the old relation, if it used a join entry. | |
| 510 | + $join_model_obj = null; | |
| 511 | +		if ($relation instanceof EE_HABTM_Relation) { | |
| 512 | + $join_model_obj = $relation->get_join_model()->get_one( | |
| 513 | + array( | |
| 514 | + array( | |
| 515 | + $model->primary_key_name() => $model_obj->ID(), | |
| 516 | + $relation->get_other_model()->primary_key_name() => $other_obj->ID() | |
| 517 | + ) | |
| 518 | + ) | |
| 519 | + ); | |
| 520 | + } | |
| 521 | + // Remove the relation. | |
| 522 | + $related_obj = $model_obj->_remove_relation_to( | |
| 523 | + $other_obj, | |
| 524 | + $relation->get_other_model()->get_this_model_name() | |
| 525 | + ); | |
| 526 | + $response = array( | |
| 527 | + strtolower($model->get_this_model_name()) => $this->returnModelObjAsJsonResponse($model_obj, $request), | |
| 528 | + strtolower($relation->get_other_model()->get_this_model_name()) => $this->returnModelObjAsJsonResponse($related_obj, $request), | |
| 529 | + ); | |
| 530 | +		if ($relation instanceof EE_HABTM_Relation) { | |
| 531 | + $join_model_obj_after_removal = $relation->get_join_model()->get_one( | |
| 532 | + array( | |
| 533 | + array( | |
| 534 | + $model->primary_key_name() => $model_obj->ID(), | |
| 535 | + $relation->get_other_model()->primary_key_name() => $other_obj->ID() | |
| 536 | + ) | |
| 537 | + ) | |
| 538 | + ); | |
| 539 | +			if ($join_model_obj instanceof EE_Base_Class) { | |
| 540 | + $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = $this->returnModelObjAsJsonResponse($join_model_obj, $request); | |
| 541 | +			} else { | |
| 542 | + $response['join'][ strtolower($relation->get_join_model()->get_this_model_name()) ] = null; | |
| 543 | + } | |
| 544 | + } | |
| 545 | + return $response; | |
| 546 | + } | |
| 547 | 547 | |
| 548 | - /** | |
| 549 | - * Gets the model objects indicated by the model, relation object, and request. | |
| 550 | - * Throws an exception if the first object doesn't exist, and currently if the related object also doesn't exist. | |
| 551 | - * However, this behaviour may change, as we may add support for simultaneously creating and relating data. | |
| 552 | - * @since $VID:$ | |
| 553 | - * @param EEM_Base $model | |
| 554 | - * @param EE_Model_Relation_Base $relation | |
| 555 | - * @param WP_REST_Request $request | |
| 556 | -     * @return array { | |
| 557 | - * @type EE_Base_Class $model_obj | |
| 558 | - * @type EE_Base_Class|null $other_model_obj | |
| 559 | - * } | |
| 560 | - * @throws RestException | |
| 561 | - */ | |
| 562 | - protected function getBothModelObjects(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 563 | -    { | |
| 564 | - // Check generic caps. For now, we're only allowing access to this endpoint to full admins. | |
| 565 | - Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | |
| 566 | - $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 567 | -        if (! current_user_can($default_cap_to_check_for)) { | |
| 568 | - throw new RestException( | |
| 569 | - 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 570 | - sprintf( | |
| 571 | - esc_html__( | |
| 572 | - // @codingStandardsIgnoreStart | |
| 573 | - 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to add relations in Event Espresso.', | |
| 574 | - // @codingStandardsIgnoreEnd | |
| 575 | - 'event_espresso' | |
| 576 | - ), | |
| 577 | - $default_cap_to_check_for | |
| 578 | - ), | |
| 579 | -                array('status' => 403) | |
| 580 | - ); | |
| 581 | - } | |
| 582 | - // Get the main model object. | |
| 583 | -        $model_obj = $this->getOneOrThrowException($model, $request->get_param('id')); | |
| 584 | - // For now, we require the other model object to exist too. This might be relaxed later. | |
| 585 | -        $other_obj = $this->getOneOrThrowException($relation->get_other_model(), $request->get_param('related_id')); | |
| 586 | - return array($model_obj,$other_obj); | |
| 587 | - } | |
| 548 | + /** | |
| 549 | + * Gets the model objects indicated by the model, relation object, and request. | |
| 550 | + * Throws an exception if the first object doesn't exist, and currently if the related object also doesn't exist. | |
| 551 | + * However, this behaviour may change, as we may add support for simultaneously creating and relating data. | |
| 552 | + * @since $VID:$ | |
| 553 | + * @param EEM_Base $model | |
| 554 | + * @param EE_Model_Relation_Base $relation | |
| 555 | + * @param WP_REST_Request $request | |
| 556 | +	 * @return array { | |
| 557 | + * @type EE_Base_Class $model_obj | |
| 558 | + * @type EE_Base_Class|null $other_model_obj | |
| 559 | + * } | |
| 560 | + * @throws RestException | |
| 561 | + */ | |
| 562 | + protected function getBothModelObjects(EEM_Base $model, EE_Model_Relation_Base $relation, WP_REST_Request $request) | |
| 563 | +	{ | |
| 564 | + // Check generic caps. For now, we're only allowing access to this endpoint to full admins. | |
| 565 | + Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit'); | |
| 566 | + $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap(); | |
| 567 | +		if (! current_user_can($default_cap_to_check_for)) { | |
| 568 | + throw new RestException( | |
| 569 | + 'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())), | |
| 570 | + sprintf( | |
| 571 | + esc_html__( | |
| 572 | + // @codingStandardsIgnoreStart | |
| 573 | + 'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to add relations in Event Espresso.', | |
| 574 | + // @codingStandardsIgnoreEnd | |
| 575 | + 'event_espresso' | |
| 576 | + ), | |
| 577 | + $default_cap_to_check_for | |
| 578 | + ), | |
| 579 | +				array('status' => 403) | |
| 580 | + ); | |
| 581 | + } | |
| 582 | + // Get the main model object. | |
| 583 | +		$model_obj = $this->getOneOrThrowException($model, $request->get_param('id')); | |
| 584 | + // For now, we require the other model object to exist too. This might be relaxed later. | |
| 585 | +		$other_obj = $this->getOneOrThrowException($relation->get_other_model(), $request->get_param('related_id')); | |
| 586 | + return array($model_obj,$other_obj); | |
| 587 | + } | |
| 588 | 588 | |
| 589 | - /** | |
| 590 | - * Gets the model with that ID or throws a REST exception. | |
| 591 | - * @since $VID:$ | |
| 592 | - * @param EEM_Base $model | |
| 593 | - * @param $id | |
| 594 | - * @return EE_Base_Class | |
| 595 | - * @throws RestException | |
| 596 | - */ | |
| 597 | - protected function getOneOrThrowException(EEM_Base $model, $id) | |
| 598 | -    { | |
| 599 | - $model_obj = $model->get_one_by_ID($id); | |
| 600 | - // @todo: check they can permission for it. For now unnecessary because only full admins can use this endpoint. | |
| 601 | -        if ($model_obj instanceof EE_Base_Class) { | |
| 602 | - return $model_obj; | |
| 603 | - } | |
| 604 | - $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 605 | - throw new RestException( | |
| 606 | -            sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 607 | -            sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 608 | -            array('status' => 404) | |
| 609 | - ); | |
| 610 | - } | |
| 589 | + /** | |
| 590 | + * Gets the model with that ID or throws a REST exception. | |
| 591 | + * @since $VID:$ | |
| 592 | + * @param EEM_Base $model | |
| 593 | + * @param $id | |
| 594 | + * @return EE_Base_Class | |
| 595 | + * @throws RestException | |
| 596 | + */ | |
| 597 | + protected function getOneOrThrowException(EEM_Base $model, $id) | |
| 598 | +	{ | |
| 599 | + $model_obj = $model->get_one_by_ID($id); | |
| 600 | + // @todo: check they can permission for it. For now unnecessary because only full admins can use this endpoint. | |
| 601 | +		if ($model_obj instanceof EE_Base_Class) { | |
| 602 | + return $model_obj; | |
| 603 | + } | |
| 604 | + $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 605 | + throw new RestException( | |
| 606 | +			sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 607 | +			sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 608 | +			array('status' => 404) | |
| 609 | + ); | |
| 610 | + } | |
| 611 | 611 | } | 
| @@ -765,6 +765,9 @@ | ||
| 765 | 765 | ); | 
| 766 | 766 | } | 
| 767 | 767 | |
| 768 | + /** | |
| 769 | + * @param string $version | |
| 770 | + */ | |
| 768 | 771 | protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version) | 
| 769 | 772 |      { | 
| 770 | 773 | // if they're related through a HABTM relation, check for any non-FKs | 
| @@ -23,1332 +23,1332 @@ | ||
| 23 | 23 | class EED_Core_Rest_Api extends \EED_Module | 
| 24 | 24 |  { | 
| 25 | 25 | |
| 26 | - const ee_api_namespace = Domain::API_NAMESPACE; | |
| 27 | - | |
| 28 | - const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/'; | |
| 29 | - | |
| 30 | - const saved_routes_option_names = 'ee_core_routes'; | |
| 31 | - | |
| 32 | - /** | |
| 33 | - * string used in _links response bodies to make them globally unique. | |
| 34 | - * | |
| 35 | - * @see http://v2.wp-api.org/extending/linking/ | |
| 36 | - */ | |
| 37 | - const ee_api_link_namespace = 'https://api.eventespresso.com/'; | |
| 38 | - | |
| 39 | - /** | |
| 40 | - * @var CalculatedModelFields | |
| 41 | - */ | |
| 42 | - protected static $_field_calculator; | |
| 43 | - | |
| 44 | - | |
| 45 | - /** | |
| 46 | - * @return EED_Core_Rest_Api|EED_Module | |
| 47 | - */ | |
| 48 | - public static function instance() | |
| 49 | -    { | |
| 50 | -        self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields'); | |
| 51 | - return parent::get_instance(__CLASS__); | |
| 52 | - } | |
| 53 | - | |
| 54 | - | |
| 55 | - /** | |
| 56 | - * set_hooks - for hooking into EE Core, other modules, etc | |
| 57 | - * | |
| 58 | - * @access public | |
| 59 | - * @return void | |
| 60 | - */ | |
| 61 | - public static function set_hooks() | |
| 62 | -    { | |
| 63 | - self::set_hooks_both(); | |
| 64 | - } | |
| 65 | - | |
| 66 | - | |
| 67 | - /** | |
| 68 | - * set_hooks_admin - for hooking into EE Admin Core, other modules, etc | |
| 69 | - * | |
| 70 | - * @access public | |
| 71 | - * @return void | |
| 72 | - */ | |
| 73 | - public static function set_hooks_admin() | |
| 74 | -    { | |
| 75 | - self::set_hooks_both(); | |
| 76 | - } | |
| 77 | - | |
| 78 | - | |
| 79 | - public static function set_hooks_both() | |
| 80 | -    { | |
| 81 | -        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10); | |
| 82 | -        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5); | |
| 83 | -        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2); | |
| 84 | - add_filter( | |
| 85 | - 'rest_index', | |
| 86 | -            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex') | |
| 87 | - ); | |
| 88 | - EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change(); | |
| 89 | - } | |
| 90 | - | |
| 91 | - | |
| 92 | - /** | |
| 93 | - * sets up hooks which only need to be included as part of REST API requests; | |
| 94 | - * other requests like to the frontend or admin etc don't need them | |
| 95 | - * | |
| 96 | - * @throws \EE_Error | |
| 97 | - */ | |
| 98 | - public static function set_hooks_rest_api() | |
| 99 | -    { | |
| 100 | - // set hooks which account for changes made to the API | |
| 101 | - EED_Core_Rest_Api::_set_hooks_for_changes(); | |
| 102 | - } | |
| 103 | - | |
| 104 | - | |
| 105 | - /** | |
| 106 | - * public wrapper of _set_hooks_for_changes. | |
| 107 | - * Loads all the hooks which make requests to old versions of the API | |
| 108 | - * appear the same as they always did | |
| 109 | - * | |
| 110 | - * @throws EE_Error | |
| 111 | - */ | |
| 112 | - public static function set_hooks_for_changes() | |
| 113 | -    { | |
| 114 | - self::_set_hooks_for_changes(); | |
| 115 | - } | |
| 116 | - | |
| 117 | - | |
| 118 | - /** | |
| 119 | - * Loads all the hooks which make requests to old versions of the API | |
| 120 | - * appear the same as they always did | |
| 121 | - * | |
| 122 | - * @throws EE_Error | |
| 123 | - */ | |
| 124 | - protected static function _set_hooks_for_changes() | |
| 125 | -    { | |
| 126 | - $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false); | |
| 127 | -        foreach ($folder_contents as $classname_in_namespace => $filepath) { | |
| 128 | - // ignore the base parent class | |
| 129 | - // and legacy named classes | |
| 130 | - if ($classname_in_namespace === 'ChangesInBase' | |
| 131 | - || strpos($classname_in_namespace, 'Changes_In_') === 0 | |
| 132 | -            ) { | |
| 133 | - continue; | |
| 134 | - } | |
| 135 | - $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace; | |
| 136 | -            if (class_exists($full_classname)) { | |
| 137 | - $instance_of_class = new $full_classname; | |
| 138 | -                if ($instance_of_class instanceof ChangesInBase) { | |
| 139 | - $instance_of_class->setHooks(); | |
| 140 | - } | |
| 141 | - } | |
| 142 | - } | |
| 143 | - } | |
| 144 | - | |
| 145 | - | |
| 146 | - /** | |
| 147 | - * Filters the WP routes to add our EE-related ones. This takes a bit of time | |
| 148 | - * so we actually prefer to only do it when an EE plugin is activated or upgraded | |
| 149 | - * | |
| 150 | - * @throws \EE_Error | |
| 151 | - */ | |
| 152 | - public static function register_routes() | |
| 153 | -    { | |
| 154 | -        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) { | |
| 155 | -            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) { | |
| 156 | - /** | |
| 157 | - * @var array $data_for_multiple_endpoints numerically indexed array | |
| 158 | -                 *                                         but can also contain route options like { | |
| 159 | -                 * @type array    $schema                      { | |
| 160 | - * @type callable $schema_callback | |
| 161 | - * @type array $callback_args arguments that will be passed to the callback, after the | |
| 162 | - * WP_REST_Request of course | |
| 163 | - * } | |
| 164 | - * } | |
| 165 | - */ | |
| 166 | - // when registering routes, register all the endpoints' data at the same time | |
| 167 | - $multiple_endpoint_args = array(); | |
| 168 | -                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) { | |
| 169 | - /** | |
| 170 | -                     * @var array     $data_for_single_endpoint { | |
| 171 | - * @type callable $callback | |
| 172 | - * @type string methods | |
| 173 | - * @type array args | |
| 174 | - * @type array _links | |
| 175 | - * @type array $callback_args arguments that will be passed to the callback, after the | |
| 176 | - * WP_REST_Request of course | |
| 177 | - * } | |
| 178 | - */ | |
| 179 | - // skip route options | |
| 180 | -                    if (! is_numeric($endpoint_key)) { | |
| 181 | - continue; | |
| 182 | - } | |
| 183 | -                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) { | |
| 184 | - throw new EE_Error( | |
| 185 | - esc_html__( | |
| 186 | - // @codingStandardsIgnoreStart | |
| 187 | - 'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).', | |
| 188 | - // @codingStandardsIgnoreEnd | |
| 189 | - 'event_espresso' | |
| 190 | - ) | |
| 191 | - ); | |
| 192 | - } | |
| 193 | - $callback = $data_for_single_endpoint['callback']; | |
| 194 | - $single_endpoint_args = array( | |
| 195 | - 'methods' => $data_for_single_endpoint['methods'], | |
| 196 | - 'args' => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args'] | |
| 197 | - : array(), | |
| 198 | - ); | |
| 199 | -                    if (isset($data_for_single_endpoint['_links'])) { | |
| 200 | - $single_endpoint_args['_links'] = $data_for_single_endpoint['_links']; | |
| 201 | - } | |
| 202 | -                    if (isset($data_for_single_endpoint['callback_args'])) { | |
| 203 | - $callback_args = $data_for_single_endpoint['callback_args']; | |
| 204 | - $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use ( | |
| 205 | - $callback, | |
| 206 | - $callback_args | |
| 207 | -                        ) { | |
| 208 | - array_unshift($callback_args, $request); | |
| 209 | - return call_user_func_array( | |
| 210 | - $callback, | |
| 211 | - $callback_args | |
| 212 | - ); | |
| 213 | - }; | |
| 214 | -                    } else { | |
| 215 | - $single_endpoint_args['callback'] = $data_for_single_endpoint['callback']; | |
| 216 | - } | |
| 217 | - $multiple_endpoint_args[] = $single_endpoint_args; | |
| 218 | - } | |
| 219 | -                if (isset($data_for_multiple_endpoints['schema'])) { | |
| 220 | - $schema_route_data = $data_for_multiple_endpoints['schema']; | |
| 221 | - $schema_callback = $schema_route_data['schema_callback']; | |
| 222 | - $callback_args = $schema_route_data['callback_args']; | |
| 223 | -                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) { | |
| 224 | - return call_user_func_array( | |
| 225 | - $schema_callback, | |
| 226 | - $callback_args | |
| 227 | - ); | |
| 228 | - }; | |
| 229 | - } | |
| 230 | - register_rest_route( | |
| 231 | - $namespace, | |
| 232 | - $relative_route, | |
| 233 | - $multiple_endpoint_args | |
| 234 | - ); | |
| 235 | - } | |
| 236 | - } | |
| 237 | - } | |
| 238 | - | |
| 239 | - | |
| 240 | - /** | |
| 241 | - * Checks if there was a version change or something that merits invalidating the cached | |
| 242 | - * route data. If so, invalidates the cached route data so that it gets refreshed | |
| 243 | - * next time the WP API is used | |
| 244 | - */ | |
| 245 | - public static function invalidate_cached_route_data_on_version_change() | |
| 246 | -    { | |
| 247 | -        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) { | |
| 248 | - EED_Core_Rest_Api::invalidate_cached_route_data(); | |
| 249 | - } | |
| 250 | -        foreach (EE_Registry::instance()->addons as $addon) { | |
| 251 | -            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) { | |
| 252 | - EED_Core_Rest_Api::invalidate_cached_route_data(); | |
| 253 | - } | |
| 254 | - } | |
| 255 | - } | |
| 256 | - | |
| 257 | - | |
| 258 | - /** | |
| 259 | - * Removes the cached route data so it will get refreshed next time the WP API is used | |
| 260 | - */ | |
| 261 | - public static function invalidate_cached_route_data() | |
| 262 | -    { | |
| 263 | - // delete the saved EE REST API routes | |
| 264 | -        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) { | |
| 265 | - delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version); | |
| 266 | - } | |
| 267 | - } | |
| 268 | - | |
| 269 | - | |
| 270 | - /** | |
| 271 | - * Gets the EE route data | |
| 272 | - * | |
| 273 | -     * @return array top-level key is the namespace, next-level key is the route and its value is array{ | |
| 274 | - * @throws \EE_Error | |
| 275 | - * @type string|array $callback | |
| 276 | - * @type string $methods | |
| 277 | - * @type boolean $hidden_endpoint | |
| 278 | - * } | |
| 279 | - */ | |
| 280 | - public static function get_ee_route_data() | |
| 281 | -    { | |
| 282 | - $ee_routes = array(); | |
| 283 | -        foreach (self::versions_served() as $version => $hidden_endpoints) { | |
| 284 | - $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version( | |
| 285 | - $version, | |
| 286 | - $hidden_endpoints | |
| 287 | - ); | |
| 288 | - } | |
| 289 | - return $ee_routes; | |
| 290 | - } | |
| 291 | - | |
| 292 | - | |
| 293 | - /** | |
| 294 | - * Gets the EE route data from the wp options if it exists already, | |
| 295 | - * otherwise re-generates it and saves it to the option | |
| 296 | - * | |
| 297 | - * @param string $version | |
| 298 | - * @param boolean $hidden_endpoints | |
| 299 | - * @return array | |
| 300 | - * @throws \EE_Error | |
| 301 | - */ | |
| 302 | - protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false) | |
| 303 | -    { | |
| 304 | - $ee_routes = get_option(self::saved_routes_option_names . $version, null); | |
| 305 | -        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) { | |
| 306 | - $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints); | |
| 307 | - } | |
| 308 | - return $ee_routes; | |
| 309 | - } | |
| 310 | - | |
| 311 | - | |
| 312 | - /** | |
| 313 | - * Saves the EE REST API route data to a wp option and returns it | |
| 314 | - * | |
| 315 | - * @param string $version | |
| 316 | - * @param boolean $hidden_endpoints | |
| 317 | - * @return mixed|null | |
| 318 | - * @throws \EE_Error | |
| 319 | - */ | |
| 320 | - protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false) | |
| 321 | -    { | |
| 322 | - $instance = self::instance(); | |
| 323 | - $routes = apply_filters( | |
| 324 | - 'EED_Core_Rest_Api__save_ee_route_data_for_version__routes', | |
| 325 | - array_replace_recursive( | |
| 326 | - $instance->_get_config_route_data_for_version($version, $hidden_endpoints), | |
| 327 | - $instance->_get_meta_route_data_for_version($version, $hidden_endpoints), | |
| 328 | - $instance->_get_model_route_data_for_version($version, $hidden_endpoints), | |
| 329 | - $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints) | |
| 330 | - ) | |
| 331 | - ); | |
| 332 | - $option_name = self::saved_routes_option_names . $version; | |
| 333 | -        if (get_option($option_name)) { | |
| 334 | - update_option($option_name, $routes, true); | |
| 335 | -        } else { | |
| 336 | - add_option($option_name, $routes, null, 'no'); | |
| 337 | - } | |
| 338 | - return $routes; | |
| 339 | - } | |
| 340 | - | |
| 341 | - | |
| 342 | - /** | |
| 343 | - * Calculates all the EE routes and saves it to a WordPress option so we don't | |
| 344 | - * need to calculate it on every request | |
| 345 | - * | |
| 346 | - * @deprecated since version 4.9.1 | |
| 347 | - * @return void | |
| 348 | - */ | |
| 349 | - public static function save_ee_routes() | |
| 350 | -    { | |
| 351 | -        if (EE_Maintenance_Mode::instance()->models_can_query()) { | |
| 352 | - $instance = self::instance(); | |
| 353 | - $routes = apply_filters( | |
| 354 | - 'EED_Core_Rest_Api__save_ee_routes__routes', | |
| 355 | - array_replace_recursive( | |
| 356 | - $instance->_register_config_routes(), | |
| 357 | - $instance->_register_meta_routes(), | |
| 358 | - $instance->_register_model_routes(), | |
| 359 | - $instance->_register_rpc_routes() | |
| 360 | - ) | |
| 361 | - ); | |
| 362 | - update_option(self::saved_routes_option_names, $routes, true); | |
| 363 | - } | |
| 364 | - } | |
| 365 | - | |
| 366 | - | |
| 367 | - /** | |
| 368 | - * Gets all the route information relating to EE models | |
| 369 | - * | |
| 370 | - * @return array @see get_ee_route_data | |
| 371 | - * @deprecated since version 4.9.1 | |
| 372 | - */ | |
| 373 | - protected function _register_model_routes() | |
| 374 | -    { | |
| 375 | - $model_routes = array(); | |
| 376 | -        foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 377 | - $model_routes[ EED_Core_Rest_Api::ee_api_namespace | |
| 378 | - . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint); | |
| 379 | - } | |
| 380 | - return $model_routes; | |
| 381 | - } | |
| 382 | - | |
| 383 | - | |
| 384 | - /** | |
| 385 | - * Decides whether or not to add write endpoints for this model. | |
| 386 | - * | |
| 387 | - * Currently, this defaults to exclude all global tables and models | |
| 388 | - * which would allow inserting WP core data (we don't want to duplicate | |
| 389 | - * what WP API does, as it's unnecessary, extra work, and potentially extra bugs) | |
| 390 | - * | |
| 391 | - * @param EEM_Base $model | |
| 392 | - * @return bool | |
| 393 | - */ | |
| 394 | - public static function should_have_write_endpoints(EEM_Base $model) | |
| 395 | -    { | |
| 396 | -        if ($model->is_wp_core_model()) { | |
| 397 | - return false; | |
| 398 | - } | |
| 399 | -        foreach ($model->get_tables() as $table) { | |
| 400 | -            if ($table->is_global()) { | |
| 401 | - return false; | |
| 402 | - } | |
| 403 | - } | |
| 404 | - return true; | |
| 405 | - } | |
| 406 | - | |
| 407 | - | |
| 408 | - /** | |
| 409 | - * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`) | |
| 410 | - * in this versioned namespace of EE4 | |
| 411 | - * | |
| 412 | - * @param $version | |
| 413 | - * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event') | |
| 414 | - */ | |
| 415 | - public static function model_names_with_plural_routes($version) | |
| 416 | -    { | |
| 417 | - $model_version_info = new ModelVersionInfo($version); | |
| 418 | - $models_to_register = $model_version_info->modelsForRequestedVersion(); | |
| 419 | - // let's not bother having endpoints for extra metas | |
| 420 | - unset( | |
| 421 | - $models_to_register['Extra_Meta'], | |
| 422 | - $models_to_register['Extra_Join'], | |
| 423 | - $models_to_register['Post_Meta'] | |
| 424 | - ); | |
| 425 | - return apply_filters( | |
| 426 | - 'FHEE__EED_Core_REST_API___register_model_routes', | |
| 427 | - $models_to_register | |
| 428 | - ); | |
| 429 | - } | |
| 430 | - | |
| 431 | - | |
| 432 | - /** | |
| 433 | - * Gets the route data for EE models in the specified version | |
| 434 | - * | |
| 435 | - * @param string $version | |
| 436 | - * @param boolean $hidden_endpoint | |
| 437 | - * @return array | |
| 438 | - * @throws EE_Error | |
| 439 | - */ | |
| 440 | - protected function _get_model_route_data_for_version($version, $hidden_endpoint = false) | |
| 441 | -    { | |
| 442 | - $model_routes = array(); | |
| 443 | - $model_version_info = new ModelVersionInfo($version); | |
| 444 | -        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) { | |
| 445 | - $model = \EE_Registry::instance()->load_model($model_name); | |
| 446 | - // if this isn't a valid model then let's skip iterate to the next item in the loop. | |
| 447 | -            if (! $model instanceof EEM_Base) { | |
| 448 | - continue; | |
| 449 | - } | |
| 450 | - // yes we could just register one route for ALL models, but then they wouldn't show up in the index | |
| 451 | - $plural_model_route = EED_Core_Rest_Api::get_collection_route($model); | |
| 452 | - $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)'); | |
| 453 | - $model_routes[ $plural_model_route ] = array( | |
| 454 | - array( | |
| 455 | - 'callback' => array( | |
| 456 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 457 | - 'handleRequestGetAll', | |
| 458 | - ), | |
| 459 | - 'callback_args' => array($version, $model_name), | |
| 460 | - 'methods' => WP_REST_Server::READABLE, | |
| 461 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 462 | - 'args' => $this->_get_read_query_params($model, $version), | |
| 463 | - '_links' => array( | |
| 464 | - 'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route), | |
| 465 | - ), | |
| 466 | - ), | |
| 467 | - 'schema' => array( | |
| 468 | - 'schema_callback' => array( | |
| 469 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 470 | - 'handleSchemaRequest', | |
| 471 | - ), | |
| 472 | - 'callback_args' => array($version, $model_name), | |
| 473 | - ), | |
| 474 | - ); | |
| 475 | - $model_routes[ $singular_model_route ] = array( | |
| 476 | - array( | |
| 477 | - 'callback' => array( | |
| 478 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 479 | - 'handleRequestGetOne', | |
| 480 | - ), | |
| 481 | - 'callback_args' => array($version, $model_name), | |
| 482 | - 'methods' => WP_REST_Server::READABLE, | |
| 483 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 484 | - 'args' => $this->_get_response_selection_query_params($model, $version, true), | |
| 485 | - ), | |
| 486 | - ); | |
| 487 | - if (apply_filters( | |
| 488 | - 'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints', | |
| 489 | - EED_Core_Rest_Api::should_have_write_endpoints($model), | |
| 490 | - $model | |
| 491 | -            )) { | |
| 492 | - $model_routes[ $plural_model_route ][] = array( | |
| 493 | - 'callback' => array( | |
| 494 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 495 | - 'handleRequestInsert', | |
| 496 | - ), | |
| 497 | - 'callback_args' => array($version, $model_name), | |
| 498 | - 'methods' => WP_REST_Server::CREATABLE, | |
| 499 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 500 | - 'args' => $this->_get_write_params($model_name, $model_version_info, true), | |
| 501 | - ); | |
| 502 | - $model_routes[ $singular_model_route ] = array_merge( | |
| 503 | - $model_routes[ $singular_model_route ], | |
| 504 | - array( | |
| 505 | - array( | |
| 506 | - 'callback' => array( | |
| 507 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 508 | - 'handleRequestUpdate', | |
| 509 | - ), | |
| 510 | - 'callback_args' => array($version, $model_name), | |
| 511 | - 'methods' => WP_REST_Server::EDITABLE, | |
| 512 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 513 | - 'args' => $this->_get_write_params($model_name, $model_version_info), | |
| 514 | - ), | |
| 515 | - array( | |
| 516 | - 'callback' => array( | |
| 517 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 518 | - 'handleRequestDelete', | |
| 519 | - ), | |
| 520 | - 'callback_args' => array($version, $model_name), | |
| 521 | - 'methods' => WP_REST_Server::DELETABLE, | |
| 522 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 523 | - 'args' => $this->_get_delete_query_params($model, $version), | |
| 524 | - ), | |
| 525 | - ) | |
| 526 | - ); | |
| 527 | - } | |
| 528 | -            foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 529 | - $related_route = EED_Core_Rest_Api::get_relation_route_via( | |
| 530 | - $model, | |
| 531 | - '(?P<id>[^\/]+)', | |
| 532 | - $relation_obj | |
| 533 | - ); | |
| 534 | - $model_routes[ $related_route ] = array( | |
| 535 | - array( | |
| 536 | - 'callback' => array( | |
| 537 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 538 | - 'handleRequestGetRelated', | |
| 539 | - ), | |
| 540 | - 'callback_args' => array($version, $model_name, $relation_name), | |
| 541 | - 'methods' => WP_REST_Server::READABLE, | |
| 542 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 543 | - 'args' => $this->_get_read_query_params($relation_obj->get_other_model(), $version), | |
| 544 | - ), | |
| 545 | - ); | |
| 546 | - | |
| 547 | - $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)'; | |
| 548 | - $model_routes[ $related_write_route ] = array( | |
| 549 | - array( | |
| 550 | - 'callback' => array( | |
| 551 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 552 | - 'handleRequestAddRelation', | |
| 553 | - ), | |
| 554 | - 'callback_args' => array($version, $model_name, $relation_name), | |
| 555 | - 'methods' => WP_REST_Server::EDITABLE, | |
| 556 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 557 | - 'args' => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version) | |
| 558 | - ), | |
| 559 | - array( | |
| 560 | - 'callback' => array( | |
| 561 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 562 | - 'handleRequestRemoveRelation', | |
| 563 | - ), | |
| 564 | - 'callback_args' => array($version, $model_name, $relation_name), | |
| 565 | - 'methods' => WP_REST_Server::DELETABLE, | |
| 566 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 567 | - 'args' => array() | |
| 568 | - ), | |
| 569 | - ); | |
| 570 | - } | |
| 571 | - } | |
| 572 | - return $model_routes; | |
| 573 | - } | |
| 574 | - | |
| 575 | - | |
| 576 | - /** | |
| 577 | - * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace, | |
| 578 | - * excluding the preceding slash. | |
| 579 | -     * Eg you pass get_plural_route_to('Event') = 'events' | |
| 580 | - * | |
| 581 | - * @param EEM_Base $model | |
| 582 | - * @return string | |
| 583 | - */ | |
| 584 | - public static function get_collection_route(EEM_Base $model) | |
| 585 | -    { | |
| 586 | - return EEH_Inflector::pluralize_and_lower($model->get_this_model_name()); | |
| 587 | - } | |
| 588 | - | |
| 589 | - | |
| 590 | - /** | |
| 591 | - * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace, | |
| 592 | - * excluding the preceding slash. | |
| 593 | -     * Eg you pass get_plural_route_to('Event', 12) = 'events/12' | |
| 594 | - * | |
| 595 | - * @param EEM_Base $model eg Event or Venue | |
| 596 | - * @param string $id | |
| 597 | - * @return string | |
| 598 | - */ | |
| 599 | - public static function get_entity_route($model, $id) | |
| 600 | -    { | |
| 601 | - return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id; | |
| 602 | - } | |
| 603 | - | |
| 604 | - | |
| 605 | - /** | |
| 606 | - * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace, | |
| 607 | - * excluding the preceding slash. | |
| 608 | -     * Eg you pass get_plural_route_to('Event', 12) = 'events/12' | |
| 609 | - * | |
| 610 | - * @param EEM_Base $model eg Event or Venue | |
| 611 | - * @param string $id | |
| 612 | - * @param EE_Model_Relation_Base $relation_obj | |
| 613 | - * @return string | |
| 614 | - */ | |
| 615 | - public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj) | |
| 616 | -    { | |
| 617 | - $related_model_name_endpoint_part = ModelRead::getRelatedEntityName( | |
| 618 | - $relation_obj->get_other_model()->get_this_model_name(), | |
| 619 | - $relation_obj | |
| 620 | - ); | |
| 621 | - return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part; | |
| 622 | - } | |
| 623 | - | |
| 624 | - | |
| 625 | - /** | |
| 626 | - * Adds onto the $relative_route the EE4 REST API versioned namespace. | |
| 627 | - * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events' | |
| 628 | - * | |
| 629 | - * @param string $relative_route | |
| 630 | - * @param string $version | |
| 631 | - * @return string | |
| 632 | - */ | |
| 633 | - public static function get_versioned_route_to($relative_route, $version = '4.8.36') | |
| 634 | -    { | |
| 635 | - return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route; | |
| 636 | - } | |
| 637 | - | |
| 638 | - | |
| 639 | - /** | |
| 640 | - * Adds all the RPC-style routes (remote procedure call-like routes, ie | |
| 641 | - * routes that don't conform to the traditional REST CRUD-style). | |
| 642 | - * | |
| 643 | - * @deprecated since 4.9.1 | |
| 644 | - */ | |
| 645 | - protected function _register_rpc_routes() | |
| 646 | -    { | |
| 647 | - $routes = array(); | |
| 648 | -        foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 649 | - $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version( | |
| 650 | - $version, | |
| 651 | - $hidden_endpoint | |
| 652 | - ); | |
| 653 | - } | |
| 654 | - return $routes; | |
| 655 | - } | |
| 656 | - | |
| 657 | - | |
| 658 | - /** | |
| 659 | - * @param string $version | |
| 660 | - * @param boolean $hidden_endpoint | |
| 661 | - * @return array | |
| 662 | - */ | |
| 663 | - protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false) | |
| 664 | -    { | |
| 665 | - $this_versions_routes = array(); | |
| 666 | - // checkin endpoint | |
| 667 | - $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array( | |
| 668 | - array( | |
| 669 | - 'callback' => array( | |
| 670 | - 'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin', | |
| 671 | - 'handleRequestToggleCheckin', | |
| 672 | - ), | |
| 673 | - 'methods' => WP_REST_Server::CREATABLE, | |
| 674 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 675 | - 'args' => array( | |
| 676 | - 'force' => array( | |
| 677 | - 'required' => false, | |
| 678 | - 'default' => false, | |
| 679 | - 'description' => __( | |
| 680 | - // @codingStandardsIgnoreStart | |
| 681 | - 'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses', | |
| 682 | - // @codingStandardsIgnoreEnd | |
| 683 | - 'event_espresso' | |
| 684 | - ), | |
| 685 | - ), | |
| 686 | - ), | |
| 687 | - 'callback_args' => array($version), | |
| 688 | - ), | |
| 689 | - ); | |
| 690 | - return apply_filters( | |
| 691 | - 'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes', | |
| 692 | - $this_versions_routes, | |
| 693 | - $version, | |
| 694 | - $hidden_endpoint | |
| 695 | - ); | |
| 696 | - } | |
| 697 | - | |
| 698 | - | |
| 699 | - /** | |
| 700 | - * Gets the query params that can be used when request one or many | |
| 701 | - * | |
| 702 | - * @param EEM_Base $model | |
| 703 | - * @param string $version | |
| 704 | - * @return array | |
| 705 | - */ | |
| 706 | - protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false) | |
| 707 | -    { | |
| 708 | - $query_params = array( | |
| 709 | - 'include' => array( | |
| 710 | - 'required' => false, | |
| 711 | - 'default' => '*', | |
| 712 | - 'type' => 'string', | |
| 713 | - ), | |
| 714 | - 'calculate' => array( | |
| 715 | - 'required' => false, | |
| 716 | - 'default' => '', | |
| 717 | - 'enum' => self::$_field_calculator->retrieveCalculatedFieldsForModel($model), | |
| 718 | - 'type' => 'string', | |
| 719 | - // because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization | |
| 720 | - // freaks out. We'll just validate this argument while handling the request | |
| 721 | - 'validate_callback' => null, | |
| 722 | - 'sanitize_callback' => null, | |
| 723 | - ), | |
| 724 | - 'password' => array( | |
| 725 | - 'required' => false, | |
| 726 | - 'default' => '', | |
| 727 | - 'type' => 'string' | |
| 728 | - ) | |
| 729 | - ); | |
| 730 | - return apply_filters( | |
| 731 | - 'FHEE__EED_Core_Rest_Api___get_response_selection_query_params', | |
| 732 | - $query_params, | |
| 733 | - $model, | |
| 734 | - $version | |
| 735 | - ); | |
| 736 | - } | |
| 737 | - | |
| 738 | - | |
| 739 | - /** | |
| 740 | - * Gets the parameters acceptable for delete requests | |
| 741 | - * | |
| 742 | - * @param \EEM_Base $model | |
| 743 | - * @param string $version | |
| 744 | - * @return array | |
| 745 | - */ | |
| 746 | - protected function _get_delete_query_params(\EEM_Base $model, $version) | |
| 747 | -    { | |
| 748 | - $params_for_delete = array( | |
| 749 | - 'allow_blocking' => array( | |
| 750 | - 'required' => false, | |
| 751 | - 'default' => true, | |
| 752 | - 'type' => 'boolean', | |
| 753 | - ), | |
| 754 | - ); | |
| 755 | - $params_for_delete['force'] = array( | |
| 756 | - 'required' => false, | |
| 757 | - 'default' => false, | |
| 758 | - 'type' => 'boolean', | |
| 759 | - ); | |
| 760 | - return apply_filters( | |
| 761 | - 'FHEE__EED_Core_Rest_Api___get_delete_query_params', | |
| 762 | - $params_for_delete, | |
| 763 | - $model, | |
| 764 | - $version | |
| 765 | - ); | |
| 766 | - } | |
| 767 | - | |
| 768 | - protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version) | |
| 769 | -    { | |
| 770 | - // if they're related through a HABTM relation, check for any non-FKs | |
| 771 | - $all_relation_settings = $source_model->relation_settings(); | |
| 772 | - $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ]; | |
| 773 | - $params = array(); | |
| 774 | -        if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) { | |
| 775 | -            foreach ($relation_settings->getNonKeyFields() as $field) { | |
| 776 | - /* @var $field EE_Model_Field_Base */ | |
| 777 | - $params[ $field->get_name() ] = array( | |
| 778 | - 'required' => ! $field->is_nullable(), | |
| 779 | - 'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version), | |
| 780 | - 'type' => $field->getSchemaType(), | |
| 781 | - 'validate_callbaack' => null, | |
| 782 | - 'sanitize_callback' => null | |
| 783 | - ); | |
| 784 | - } | |
| 785 | - } | |
| 786 | - return $params; | |
| 787 | - } | |
| 788 | - | |
| 789 | - | |
| 790 | - /** | |
| 791 | - * Gets info about reading query params that are acceptable | |
| 792 | - * | |
| 793 | - * @param \EEM_Base $model eg 'Event' or 'Venue' | |
| 794 | - * @param string $version | |
| 795 | - * @return array describing the args acceptable when querying this model | |
| 796 | - * @throws EE_Error | |
| 797 | - */ | |
| 798 | - protected function _get_read_query_params(\EEM_Base $model, $version) | |
| 799 | -    { | |
| 800 | - $default_orderby = array(); | |
| 801 | -        foreach ($model->get_combined_primary_key_fields() as $key_field) { | |
| 802 | - $default_orderby[ $key_field->get_name() ] = 'ASC'; | |
| 803 | - } | |
| 804 | - return array_merge( | |
| 805 | - $this->_get_response_selection_query_params($model, $version), | |
| 806 | - array( | |
| 807 | - 'where' => array( | |
| 808 | - 'required' => false, | |
| 809 | - 'default' => array(), | |
| 810 | - 'type' => 'object', | |
| 811 | - // because we accept an almost infinite list of possible where conditions, WP | |
| 812 | - // core validation and sanitization freaks out. We'll just validate this argument | |
| 813 | - // while handling the request | |
| 814 | - 'validate_callback' => null, | |
| 815 | - 'sanitize_callback' => null, | |
| 816 | - ), | |
| 817 | - 'limit' => array( | |
| 818 | - 'required' => false, | |
| 819 | - 'default' => EED_Core_Rest_Api::get_default_query_limit(), | |
| 820 | - 'type' => array( | |
| 821 | - 'array', | |
| 822 | - 'string', | |
| 823 | - 'integer', | |
| 824 | - ), | |
| 825 | - // because we accept a variety of types, WP core validation and sanitization | |
| 826 | - // freaks out. We'll just validate this argument while handling the request | |
| 827 | - 'validate_callback' => null, | |
| 828 | - 'sanitize_callback' => null, | |
| 829 | - ), | |
| 830 | - 'order_by' => array( | |
| 831 | - 'required' => false, | |
| 832 | - 'default' => $default_orderby, | |
| 833 | - 'type' => array( | |
| 834 | - 'object', | |
| 835 | - 'string', | |
| 836 | - ),// because we accept a variety of types, WP core validation and sanitization | |
| 837 | - // freaks out. We'll just validate this argument while handling the request | |
| 838 | - 'validate_callback' => null, | |
| 839 | - 'sanitize_callback' => null, | |
| 840 | - ), | |
| 841 | - 'group_by' => array( | |
| 842 | - 'required' => false, | |
| 843 | - 'default' => null, | |
| 844 | - 'type' => array( | |
| 845 | - 'object', | |
| 846 | - 'string', | |
| 847 | - ), | |
| 848 | - // because we accept an almost infinite list of possible groupings, | |
| 849 | - // WP core validation and sanitization | |
| 850 | - // freaks out. We'll just validate this argument while handling the request | |
| 851 | - 'validate_callback' => null, | |
| 852 | - 'sanitize_callback' => null, | |
| 853 | - ), | |
| 854 | - 'having' => array( | |
| 855 | - 'required' => false, | |
| 856 | - 'default' => null, | |
| 857 | - 'type' => 'object', | |
| 858 | - // because we accept an almost infinite list of possible where conditions, WP | |
| 859 | - // core validation and sanitization freaks out. We'll just validate this argument | |
| 860 | - // while handling the request | |
| 861 | - 'validate_callback' => null, | |
| 862 | - 'sanitize_callback' => null, | |
| 863 | - ), | |
| 864 | - 'caps' => array( | |
| 865 | - 'required' => false, | |
| 866 | - 'default' => EEM_Base::caps_read, | |
| 867 | - 'type' => 'string', | |
| 868 | - 'enum' => array( | |
| 869 | - EEM_Base::caps_read, | |
| 870 | - EEM_Base::caps_read_admin, | |
| 871 | - EEM_Base::caps_edit, | |
| 872 | - EEM_Base::caps_delete, | |
| 873 | - ), | |
| 874 | - ), | |
| 875 | - ) | |
| 876 | - ); | |
| 877 | - } | |
| 878 | - | |
| 879 | - | |
| 880 | - /** | |
| 881 | - * Gets parameter information for a model regarding writing data | |
| 882 | - * | |
| 883 | - * @param string $model_name | |
| 884 | - * @param ModelVersionInfo $model_version_info | |
| 885 | - * @param boolean $create whether this is for request to create (in | |
| 886 | - * which case we need all required params) or | |
| 887 | - * just to update (in which case we don't | |
| 888 | - * need those on every request) | |
| 889 | - * @return array | |
| 890 | - */ | |
| 891 | - protected function _get_write_params( | |
| 892 | - $model_name, | |
| 893 | - ModelVersionInfo $model_version_info, | |
| 894 | - $create = false | |
| 895 | -    ) { | |
| 896 | - $model = EE_Registry::instance()->load_model($model_name); | |
| 897 | - $fields = $model_version_info->fieldsOnModelInThisVersion($model); | |
| 898 | - $args_info = array(); | |
| 899 | -        foreach ($fields as $field_name => $field_obj) { | |
| 900 | -            if ($field_obj->is_auto_increment()) { | |
| 901 | - // totally ignore auto increment IDs | |
| 902 | - continue; | |
| 903 | - } | |
| 904 | - $arg_info = $field_obj->getSchema(); | |
| 905 | - $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null; | |
| 906 | - $arg_info['required'] = $required; | |
| 907 | - // remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right? | |
| 908 | - unset($arg_info['readonly']); | |
| 909 | - $schema_properties = $field_obj->getSchemaProperties(); | |
| 910 | - if (isset($schema_properties['raw']) | |
| 911 | - && $field_obj->getSchemaType() === 'object' | |
| 912 | -            ) { | |
| 913 | - // if there's a "raw" form of this argument, use those properties instead | |
| 914 | - $arg_info = array_replace( | |
| 915 | - $arg_info, | |
| 916 | - $schema_properties['raw'] | |
| 917 | - ); | |
| 918 | - } | |
| 919 | - $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 920 | - $field_obj, | |
| 921 | - $field_obj->get_default_value(), | |
| 922 | - $model_version_info->requestedVersion() | |
| 923 | - ); | |
| 924 | - // we do our own validation and sanitization within the controller | |
| 925 | -            if (function_exists('rest_validate_value_from_schema')) { | |
| 926 | - $sanitize_callback = array( | |
| 927 | - 'EED_Core_Rest_Api', | |
| 928 | - 'default_sanitize_callback', | |
| 929 | - ); | |
| 930 | -            } else { | |
| 931 | - $sanitize_callback = null; | |
| 932 | - } | |
| 933 | - $arg_info['sanitize_callback'] = $sanitize_callback; | |
| 934 | - $args_info[ $field_name ] = $arg_info; | |
| 935 | -            if ($field_obj instanceof EE_Datetime_Field) { | |
| 936 | - $gmt_arg_info = $arg_info; | |
| 937 | - $gmt_arg_info['description'] = sprintf( | |
| 938 | - esc_html__( | |
| 939 | - '%1$s - the value for this field in UTC. Ignored if %2$s is provided.', | |
| 940 | - 'event_espresso' | |
| 941 | - ), | |
| 942 | - $field_obj->get_nicename(), | |
| 943 | - $field_name | |
| 944 | - ); | |
| 945 | - $args_info[ $field_name . '_gmt' ] = $gmt_arg_info; | |
| 946 | - } | |
| 947 | - } | |
| 948 | - return $args_info; | |
| 949 | - } | |
| 950 | - | |
| 951 | - | |
| 952 | - /** | |
| 953 | - * Replacement for WP API's 'rest_parse_request_arg'. | |
| 954 | - * If the value is blank but not required, don't bother validating it. | |
| 955 | - * Also, it uses our email validation instead of WP API's default. | |
| 956 | - * | |
| 957 | - * @param $value | |
| 958 | - * @param WP_REST_Request $request | |
| 959 | - * @param $param | |
| 960 | - * @return bool|true|WP_Error | |
| 961 | - * @throws InvalidArgumentException | |
| 962 | - * @throws InvalidInterfaceException | |
| 963 | - * @throws InvalidDataTypeException | |
| 964 | - */ | |
| 965 | - public static function default_sanitize_callback($value, WP_REST_Request $request, $param) | |
| 966 | -    { | |
| 967 | - $attributes = $request->get_attributes(); | |
| 968 | - if (! isset($attributes['args'][ $param ]) | |
| 969 | -            || ! is_array($attributes['args'][ $param ])) { | |
| 970 | - $validation_result = true; | |
| 971 | -        } else { | |
| 972 | - $args = $attributes['args'][ $param ]; | |
| 973 | - if (( | |
| 974 | - $value === '' | |
| 975 | - || $value === null | |
| 976 | - ) | |
| 977 | - && (! isset($args['required']) | |
| 978 | - || $args['required'] === false | |
| 979 | - ) | |
| 980 | -            ) { | |
| 981 | - // not required and not provided? that's cool | |
| 982 | - $validation_result = true; | |
| 983 | - } elseif (isset($args['format']) | |
| 984 | - && $args['format'] === 'email' | |
| 985 | -            ) { | |
| 986 | - $validation_result = true; | |
| 987 | -                if (! self::_validate_email($value)) { | |
| 988 | - $validation_result = new WP_Error( | |
| 989 | - 'rest_invalid_param', | |
| 990 | - esc_html__( | |
| 991 | - 'The email address is not valid or does not exist.', | |
| 992 | - 'event_espresso' | |
| 993 | - ) | |
| 994 | - ); | |
| 995 | - } | |
| 996 | -            } else { | |
| 997 | - $validation_result = rest_validate_value_from_schema($value, $args, $param); | |
| 998 | - } | |
| 999 | - } | |
| 1000 | -        if (is_wp_error($validation_result)) { | |
| 1001 | - return $validation_result; | |
| 1002 | - } | |
| 1003 | - return rest_sanitize_request_arg($value, $request, $param); | |
| 1004 | - } | |
| 1005 | - | |
| 1006 | - | |
| 1007 | - /** | |
| 1008 | - * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email() | |
| 1009 | - * | |
| 1010 | - * @param $email | |
| 1011 | - * @return bool | |
| 1012 | - * @throws InvalidArgumentException | |
| 1013 | - * @throws InvalidInterfaceException | |
| 1014 | - * @throws InvalidDataTypeException | |
| 1015 | - */ | |
| 1016 | - protected static function _validate_email($email) | |
| 1017 | -    { | |
| 1018 | -        try { | |
| 1019 | - EmailAddressFactory::create($email); | |
| 1020 | - return true; | |
| 1021 | -        } catch (EmailValidationException $e) { | |
| 1022 | - return false; | |
| 1023 | - } | |
| 1024 | - } | |
| 1025 | - | |
| 1026 | - | |
| 1027 | - /** | |
| 1028 | - * Gets routes for the config | |
| 1029 | - * | |
| 1030 | - * @return array @see _register_model_routes | |
| 1031 | - * @deprecated since version 4.9.1 | |
| 1032 | - */ | |
| 1033 | - protected function _register_config_routes() | |
| 1034 | -    { | |
| 1035 | - $config_routes = array(); | |
| 1036 | -        foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 1037 | - $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version( | |
| 1038 | - $version, | |
| 1039 | - $hidden_endpoint | |
| 1040 | - ); | |
| 1041 | - } | |
| 1042 | - return $config_routes; | |
| 1043 | - } | |
| 1044 | - | |
| 1045 | - | |
| 1046 | - /** | |
| 1047 | - * Gets routes for the config for the specified version | |
| 1048 | - * | |
| 1049 | - * @param string $version | |
| 1050 | - * @param boolean $hidden_endpoint | |
| 1051 | - * @return array | |
| 1052 | - */ | |
| 1053 | - protected function _get_config_route_data_for_version($version, $hidden_endpoint) | |
| 1054 | -    { | |
| 1055 | - return array( | |
| 1056 | - 'config' => array( | |
| 1057 | - array( | |
| 1058 | - 'callback' => array( | |
| 1059 | - 'EventEspresso\core\libraries\rest_api\controllers\config\Read', | |
| 1060 | - 'handleRequest', | |
| 1061 | - ), | |
| 1062 | - 'methods' => WP_REST_Server::READABLE, | |
| 1063 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 1064 | - 'callback_args' => array($version), | |
| 1065 | - ), | |
| 1066 | - ), | |
| 1067 | - 'site_info' => array( | |
| 1068 | - array( | |
| 1069 | - 'callback' => array( | |
| 1070 | - 'EventEspresso\core\libraries\rest_api\controllers\config\Read', | |
| 1071 | - 'handleRequestSiteInfo', | |
| 1072 | - ), | |
| 1073 | - 'methods' => WP_REST_Server::READABLE, | |
| 1074 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 1075 | - 'callback_args' => array($version), | |
| 1076 | - ), | |
| 1077 | - ), | |
| 1078 | - ); | |
| 1079 | - } | |
| 1080 | - | |
| 1081 | - | |
| 1082 | - /** | |
| 1083 | - * Gets the meta info routes | |
| 1084 | - * | |
| 1085 | - * @return array @see _register_model_routes | |
| 1086 | - * @deprecated since version 4.9.1 | |
| 1087 | - */ | |
| 1088 | - protected function _register_meta_routes() | |
| 1089 | -    { | |
| 1090 | - $meta_routes = array(); | |
| 1091 | -        foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 1092 | - $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version( | |
| 1093 | - $version, | |
| 1094 | - $hidden_endpoint | |
| 1095 | - ); | |
| 1096 | - } | |
| 1097 | - return $meta_routes; | |
| 1098 | - } | |
| 1099 | - | |
| 1100 | - | |
| 1101 | - /** | |
| 1102 | - * @param string $version | |
| 1103 | - * @param boolean $hidden_endpoint | |
| 1104 | - * @return array | |
| 1105 | - */ | |
| 1106 | - protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false) | |
| 1107 | -    { | |
| 1108 | - return array( | |
| 1109 | - 'resources' => array( | |
| 1110 | - array( | |
| 1111 | - 'callback' => array( | |
| 1112 | - 'EventEspresso\core\libraries\rest_api\controllers\model\Meta', | |
| 1113 | - 'handleRequestModelsMeta', | |
| 1114 | - ), | |
| 1115 | - 'methods' => WP_REST_Server::READABLE, | |
| 1116 | - 'hidden_endpoint' => $hidden_endpoint, | |
| 1117 | - 'callback_args' => array($version), | |
| 1118 | - ), | |
| 1119 | - ), | |
| 1120 | - ); | |
| 1121 | - } | |
| 1122 | - | |
| 1123 | - | |
| 1124 | - /** | |
| 1125 | - * Tries to hide old 4.6 endpoints from the | |
| 1126 | - * | |
| 1127 | - * @param array $route_data | |
| 1128 | - * @return array | |
| 1129 | - * @throws \EE_Error | |
| 1130 | - */ | |
| 1131 | - public static function hide_old_endpoints($route_data) | |
| 1132 | -    { | |
| 1133 | - // allow API clients to override which endpoints get hidden, in case | |
| 1134 | - // they want to discover particular endpoints | |
| 1135 | - // also, we don't have access to the request so we have to just grab it from the superglobal | |
| 1136 | - $force_show_ee_namespace = ltrim( | |
| 1137 | - EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''), | |
| 1138 | - '/' | |
| 1139 | - ); | |
| 1140 | -        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) { | |
| 1141 | -            foreach ($relative_urls as $resource_name => $endpoints) { | |
| 1142 | -                foreach ($endpoints as $key => $endpoint) { | |
| 1143 | - // skip schema and other route options | |
| 1144 | -                    if (! is_numeric($key)) { | |
| 1145 | - continue; | |
| 1146 | - } | |
| 1147 | - // by default, hide "hidden_endpoint"s, unless the request indicates | |
| 1148 | - // to $force_show_ee_namespace, in which case only show that one | |
| 1149 | - // namespace's endpoints (and hide all others) | |
| 1150 | - if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace) | |
| 1151 | - || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '') | |
| 1152 | -                    ) { | |
| 1153 | - $full_route = '/' . ltrim($namespace, '/'); | |
| 1154 | - $full_route .= '/' . ltrim($resource_name, '/'); | |
| 1155 | - unset($route_data[ $full_route ]); | |
| 1156 | - } | |
| 1157 | - } | |
| 1158 | - } | |
| 1159 | - } | |
| 1160 | - return $route_data; | |
| 1161 | - } | |
| 1162 | - | |
| 1163 | - | |
| 1164 | - /** | |
| 1165 | - * Returns an array describing which versions of core support serving requests for. | |
| 1166 | - * Keys are core versions' major and minor version, and values are the | |
| 1167 | - * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like | |
| 1168 | - * data by just removing a few models and fields from the responses. However, 4.15 might remove | |
| 1169 | - * the answers table entirely, in which case it would be very difficult for | |
| 1170 | - * it to serve 4.6-style responses. | |
| 1171 | - * Versions of core that are missing from this array are unknowns. | |
| 1172 | - * previous ver | |
| 1173 | - * | |
| 1174 | - * @return array | |
| 1175 | - */ | |
| 1176 | - public static function version_compatibilities() | |
| 1177 | -    { | |
| 1178 | - return apply_filters( | |
| 1179 | - 'FHEE__EED_Core_REST_API__version_compatibilities', | |
| 1180 | - array( | |
| 1181 | - '4.8.29' => '4.8.29', | |
| 1182 | - '4.8.33' => '4.8.29', | |
| 1183 | - '4.8.34' => '4.8.29', | |
| 1184 | - '4.8.36' => '4.8.29', | |
| 1185 | - ) | |
| 1186 | - ); | |
| 1187 | - } | |
| 1188 | - | |
| 1189 | - | |
| 1190 | - /** | |
| 1191 | - * Gets the latest API version served. Eg if there | |
| 1192 | - * are two versions served of the API, 4.8.29 and 4.8.32, and | |
| 1193 | - * we are on core version 4.8.34, it will return the string "4.8.32" | |
| 1194 | - * | |
| 1195 | - * @return string | |
| 1196 | - */ | |
| 1197 | - public static function latest_rest_api_version() | |
| 1198 | -    { | |
| 1199 | - $versions_served = \EED_Core_Rest_Api::versions_served(); | |
| 1200 | - $versions_served_keys = array_keys($versions_served); | |
| 1201 | - return end($versions_served_keys); | |
| 1202 | - } | |
| 1203 | - | |
| 1204 | - | |
| 1205 | - /** | |
| 1206 | - * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of | |
| 1207 | - * EE the API can serve requests for. Eg, if we are on 4.15 of core, and | |
| 1208 | - * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ). | |
| 1209 | - * We also indicate whether or not this version should be put in the index or not | |
| 1210 | - * | |
| 1211 | - * @return array keys are API version numbers (just major and minor numbers), and values | |
| 1212 | - * are whether or not they should be hidden | |
| 1213 | - */ | |
| 1214 | - public static function versions_served() | |
| 1215 | -    { | |
| 1216 | - $versions_served = array(); | |
| 1217 | - $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities(); | |
| 1218 | - $lowest_compatible_version = end($possibly_served_versions); | |
| 1219 | - reset($possibly_served_versions); | |
| 1220 | - $versions_served_historically = array_keys($possibly_served_versions); | |
| 1221 | - $latest_version = end($versions_served_historically); | |
| 1222 | - reset($versions_served_historically); | |
| 1223 | - // for each version of core we have ever served: | |
| 1224 | -        foreach ($versions_served_historically as $key_versioned_endpoint) { | |
| 1225 | - // if it's not above the current core version, and it's compatible with the current version of core | |
| 1226 | -            if ($key_versioned_endpoint === $latest_version) { | |
| 1227 | - // don't hide the latest version in the index | |
| 1228 | - $versions_served[ $key_versioned_endpoint ] = false; | |
| 1229 | - } elseif ($key_versioned_endpoint >= $lowest_compatible_version | |
| 1230 | - && $key_versioned_endpoint < EED_Core_Rest_Api::core_version() | |
| 1231 | -            ) { | |
| 1232 | - // include, but hide, previous versions which are still supported | |
| 1233 | - $versions_served[ $key_versioned_endpoint ] = true; | |
| 1234 | - } elseif (apply_filters( | |
| 1235 | - 'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions', | |
| 1236 | - false, | |
| 1237 | - $possibly_served_versions | |
| 1238 | -            )) { | |
| 1239 | - // if a version is no longer supported, don't include it in index or list of versions served | |
| 1240 | - $versions_served[ $key_versioned_endpoint ] = true; | |
| 1241 | - } | |
| 1242 | - } | |
| 1243 | - return $versions_served; | |
| 1244 | - } | |
| 1245 | - | |
| 1246 | - | |
| 1247 | - /** | |
| 1248 | - * Gets the major and minor version of EE core's version string | |
| 1249 | - * | |
| 1250 | - * @return string | |
| 1251 | - */ | |
| 1252 | - public static function core_version() | |
| 1253 | -    { | |
| 1254 | - return apply_filters( | |
| 1255 | - 'FHEE__EED_Core_REST_API__core_version', | |
| 1256 | - implode( | |
| 1257 | - '.', | |
| 1258 | - array_slice( | |
| 1259 | - explode( | |
| 1260 | - '.', | |
| 1261 | - espresso_version() | |
| 1262 | - ), | |
| 1263 | - 0, | |
| 1264 | - 3 | |
| 1265 | - ) | |
| 1266 | - ) | |
| 1267 | - ); | |
| 1268 | - } | |
| 1269 | - | |
| 1270 | - | |
| 1271 | - /** | |
| 1272 | - * Gets the default limit that should be used when querying for resources | |
| 1273 | - * | |
| 1274 | - * @return int | |
| 1275 | - */ | |
| 1276 | - public static function get_default_query_limit() | |
| 1277 | -    { | |
| 1278 | - // we actually don't use a const because we want folks to always use | |
| 1279 | - // this method, not the const directly | |
| 1280 | - return apply_filters( | |
| 1281 | - 'FHEE__EED_Core_Rest_Api__get_default_query_limit', | |
| 1282 | - 50 | |
| 1283 | - ); | |
| 1284 | - } | |
| 1285 | - | |
| 1286 | - | |
| 1287 | - /** | |
| 1288 | - * | |
| 1289 | - * @param string $version api version string (i.e. '4.8.36') | |
| 1290 | - * @return array | |
| 1291 | - */ | |
| 1292 | - public static function getCollectionRoutesIndexedByModelName($version = '') | |
| 1293 | -    { | |
| 1294 | - $version = empty($version) ? self::latest_rest_api_version() : $version; | |
| 1295 | - $model_names = self::model_names_with_plural_routes($version); | |
| 1296 | - $collection_routes = array(); | |
| 1297 | -        foreach ($model_names as $model_name => $model_class_name) { | |
| 1298 | - $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/' | |
| 1299 | - . EEH_Inflector::pluralize_and_lower($model_name); | |
| 1300 | - } | |
| 1301 | - return $collection_routes; | |
| 1302 | - } | |
| 1303 | - | |
| 1304 | - | |
| 1305 | - /** | |
| 1306 | - * Returns an array of primary key names indexed by model names. | |
| 1307 | - * @param string $version | |
| 1308 | - * @return array | |
| 1309 | - */ | |
| 1310 | - public static function getPrimaryKeyNamesIndexedByModelName($version = '') | |
| 1311 | -    { | |
| 1312 | - $version = empty($version) ? self::latest_rest_api_version() : $version; | |
| 1313 | - $model_names = self::model_names_with_plural_routes($version); | |
| 1314 | - $primary_key_items = array(); | |
| 1315 | -        foreach ($model_names as $model_name => $model_class_name) { | |
| 1316 | - $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields(); | |
| 1317 | -            foreach ($primary_keys as $primary_key_name => $primary_key_field) { | |
| 1318 | -                if (count($primary_keys) > 1) { | |
| 1319 | - $primary_key_items[ strtolower($model_name) ][] = $primary_key_name; | |
| 1320 | -                } else { | |
| 1321 | - $primary_key_items[ strtolower($model_name) ] = $primary_key_name; | |
| 1322 | - } | |
| 1323 | - } | |
| 1324 | - } | |
| 1325 | - return $primary_key_items; | |
| 1326 | - } | |
| 1327 | - | |
| 1328 | - /** | |
| 1329 | - * Determines the EE REST API debug mode is activated, or not. | |
| 1330 | - * @since $VID:$ | |
| 1331 | - * @return bool | |
| 1332 | - */ | |
| 1333 | - public static function debugMode() | |
| 1334 | -    { | |
| 1335 | - static $debug_mode = null; // could be class prop | |
| 1336 | -        if ($debug_mode === null) { | |
| 1337 | -            $debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE; | |
| 1338 | - } | |
| 1339 | - return $debug_mode; | |
| 1340 | - } | |
| 1341 | - | |
| 1342 | - | |
| 1343 | - | |
| 1344 | - /** | |
| 1345 | - * run - initial module setup | |
| 1346 | - * | |
| 1347 | - * @access public | |
| 1348 | - * @param WP $WP | |
| 1349 | - * @return void | |
| 1350 | - */ | |
| 1351 | - public function run($WP) | |
| 1352 | -    { | |
| 1353 | - } | |
| 26 | + const ee_api_namespace = Domain::API_NAMESPACE; | |
| 27 | + | |
| 28 | + const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/'; | |
| 29 | + | |
| 30 | + const saved_routes_option_names = 'ee_core_routes'; | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * string used in _links response bodies to make them globally unique. | |
| 34 | + * | |
| 35 | + * @see http://v2.wp-api.org/extending/linking/ | |
| 36 | + */ | |
| 37 | + const ee_api_link_namespace = 'https://api.eventespresso.com/'; | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * @var CalculatedModelFields | |
| 41 | + */ | |
| 42 | + protected static $_field_calculator; | |
| 43 | + | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * @return EED_Core_Rest_Api|EED_Module | |
| 47 | + */ | |
| 48 | + public static function instance() | |
| 49 | +	{ | |
| 50 | +		self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields'); | |
| 51 | + return parent::get_instance(__CLASS__); | |
| 52 | + } | |
| 53 | + | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * set_hooks - for hooking into EE Core, other modules, etc | |
| 57 | + * | |
| 58 | + * @access public | |
| 59 | + * @return void | |
| 60 | + */ | |
| 61 | + public static function set_hooks() | |
| 62 | +	{ | |
| 63 | + self::set_hooks_both(); | |
| 64 | + } | |
| 65 | + | |
| 66 | + | |
| 67 | + /** | |
| 68 | + * set_hooks_admin - for hooking into EE Admin Core, other modules, etc | |
| 69 | + * | |
| 70 | + * @access public | |
| 71 | + * @return void | |
| 72 | + */ | |
| 73 | + public static function set_hooks_admin() | |
| 74 | +	{ | |
| 75 | + self::set_hooks_both(); | |
| 76 | + } | |
| 77 | + | |
| 78 | + | |
| 79 | + public static function set_hooks_both() | |
| 80 | +	{ | |
| 81 | +		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10); | |
| 82 | +		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5); | |
| 83 | +		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2); | |
| 84 | + add_filter( | |
| 85 | + 'rest_index', | |
| 86 | +			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex') | |
| 87 | + ); | |
| 88 | + EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change(); | |
| 89 | + } | |
| 90 | + | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * sets up hooks which only need to be included as part of REST API requests; | |
| 94 | + * other requests like to the frontend or admin etc don't need them | |
| 95 | + * | |
| 96 | + * @throws \EE_Error | |
| 97 | + */ | |
| 98 | + public static function set_hooks_rest_api() | |
| 99 | +	{ | |
| 100 | + // set hooks which account for changes made to the API | |
| 101 | + EED_Core_Rest_Api::_set_hooks_for_changes(); | |
| 102 | + } | |
| 103 | + | |
| 104 | + | |
| 105 | + /** | |
| 106 | + * public wrapper of _set_hooks_for_changes. | |
| 107 | + * Loads all the hooks which make requests to old versions of the API | |
| 108 | + * appear the same as they always did | |
| 109 | + * | |
| 110 | + * @throws EE_Error | |
| 111 | + */ | |
| 112 | + public static function set_hooks_for_changes() | |
| 113 | +	{ | |
| 114 | + self::_set_hooks_for_changes(); | |
| 115 | + } | |
| 116 | + | |
| 117 | + | |
| 118 | + /** | |
| 119 | + * Loads all the hooks which make requests to old versions of the API | |
| 120 | + * appear the same as they always did | |
| 121 | + * | |
| 122 | + * @throws EE_Error | |
| 123 | + */ | |
| 124 | + protected static function _set_hooks_for_changes() | |
| 125 | +	{ | |
| 126 | + $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false); | |
| 127 | +		foreach ($folder_contents as $classname_in_namespace => $filepath) { | |
| 128 | + // ignore the base parent class | |
| 129 | + // and legacy named classes | |
| 130 | + if ($classname_in_namespace === 'ChangesInBase' | |
| 131 | + || strpos($classname_in_namespace, 'Changes_In_') === 0 | |
| 132 | +			) { | |
| 133 | + continue; | |
| 134 | + } | |
| 135 | + $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace; | |
| 136 | +			if (class_exists($full_classname)) { | |
| 137 | + $instance_of_class = new $full_classname; | |
| 138 | +				if ($instance_of_class instanceof ChangesInBase) { | |
| 139 | + $instance_of_class->setHooks(); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + } | |
| 143 | + } | |
| 144 | + | |
| 145 | + | |
| 146 | + /** | |
| 147 | + * Filters the WP routes to add our EE-related ones. This takes a bit of time | |
| 148 | + * so we actually prefer to only do it when an EE plugin is activated or upgraded | |
| 149 | + * | |
| 150 | + * @throws \EE_Error | |
| 151 | + */ | |
| 152 | + public static function register_routes() | |
| 153 | +	{ | |
| 154 | +		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) { | |
| 155 | +			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) { | |
| 156 | + /** | |
| 157 | + * @var array $data_for_multiple_endpoints numerically indexed array | |
| 158 | +				 *                                         but can also contain route options like { | |
| 159 | +				 * @type array    $schema                      { | |
| 160 | + * @type callable $schema_callback | |
| 161 | + * @type array $callback_args arguments that will be passed to the callback, after the | |
| 162 | + * WP_REST_Request of course | |
| 163 | + * } | |
| 164 | + * } | |
| 165 | + */ | |
| 166 | + // when registering routes, register all the endpoints' data at the same time | |
| 167 | + $multiple_endpoint_args = array(); | |
| 168 | +				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) { | |
| 169 | + /** | |
| 170 | +					 * @var array     $data_for_single_endpoint { | |
| 171 | + * @type callable $callback | |
| 172 | + * @type string methods | |
| 173 | + * @type array args | |
| 174 | + * @type array _links | |
| 175 | + * @type array $callback_args arguments that will be passed to the callback, after the | |
| 176 | + * WP_REST_Request of course | |
| 177 | + * } | |
| 178 | + */ | |
| 179 | + // skip route options | |
| 180 | +					if (! is_numeric($endpoint_key)) { | |
| 181 | + continue; | |
| 182 | + } | |
| 183 | +					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) { | |
| 184 | + throw new EE_Error( | |
| 185 | + esc_html__( | |
| 186 | + // @codingStandardsIgnoreStart | |
| 187 | + 'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).', | |
| 188 | + // @codingStandardsIgnoreEnd | |
| 189 | + 'event_espresso' | |
| 190 | + ) | |
| 191 | + ); | |
| 192 | + } | |
| 193 | + $callback = $data_for_single_endpoint['callback']; | |
| 194 | + $single_endpoint_args = array( | |
| 195 | + 'methods' => $data_for_single_endpoint['methods'], | |
| 196 | + 'args' => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args'] | |
| 197 | + : array(), | |
| 198 | + ); | |
| 199 | +					if (isset($data_for_single_endpoint['_links'])) { | |
| 200 | + $single_endpoint_args['_links'] = $data_for_single_endpoint['_links']; | |
| 201 | + } | |
| 202 | +					if (isset($data_for_single_endpoint['callback_args'])) { | |
| 203 | + $callback_args = $data_for_single_endpoint['callback_args']; | |
| 204 | + $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use ( | |
| 205 | + $callback, | |
| 206 | + $callback_args | |
| 207 | +						) { | |
| 208 | + array_unshift($callback_args, $request); | |
| 209 | + return call_user_func_array( | |
| 210 | + $callback, | |
| 211 | + $callback_args | |
| 212 | + ); | |
| 213 | + }; | |
| 214 | +					} else { | |
| 215 | + $single_endpoint_args['callback'] = $data_for_single_endpoint['callback']; | |
| 216 | + } | |
| 217 | + $multiple_endpoint_args[] = $single_endpoint_args; | |
| 218 | + } | |
| 219 | +				if (isset($data_for_multiple_endpoints['schema'])) { | |
| 220 | + $schema_route_data = $data_for_multiple_endpoints['schema']; | |
| 221 | + $schema_callback = $schema_route_data['schema_callback']; | |
| 222 | + $callback_args = $schema_route_data['callback_args']; | |
| 223 | +					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) { | |
| 224 | + return call_user_func_array( | |
| 225 | + $schema_callback, | |
| 226 | + $callback_args | |
| 227 | + ); | |
| 228 | + }; | |
| 229 | + } | |
| 230 | + register_rest_route( | |
| 231 | + $namespace, | |
| 232 | + $relative_route, | |
| 233 | + $multiple_endpoint_args | |
| 234 | + ); | |
| 235 | + } | |
| 236 | + } | |
| 237 | + } | |
| 238 | + | |
| 239 | + | |
| 240 | + /** | |
| 241 | + * Checks if there was a version change or something that merits invalidating the cached | |
| 242 | + * route data. If so, invalidates the cached route data so that it gets refreshed | |
| 243 | + * next time the WP API is used | |
| 244 | + */ | |
| 245 | + public static function invalidate_cached_route_data_on_version_change() | |
| 246 | +	{ | |
| 247 | +		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) { | |
| 248 | + EED_Core_Rest_Api::invalidate_cached_route_data(); | |
| 249 | + } | |
| 250 | +		foreach (EE_Registry::instance()->addons as $addon) { | |
| 251 | +			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) { | |
| 252 | + EED_Core_Rest_Api::invalidate_cached_route_data(); | |
| 253 | + } | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + | |
| 258 | + /** | |
| 259 | + * Removes the cached route data so it will get refreshed next time the WP API is used | |
| 260 | + */ | |
| 261 | + public static function invalidate_cached_route_data() | |
| 262 | +	{ | |
| 263 | + // delete the saved EE REST API routes | |
| 264 | +		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) { | |
| 265 | + delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version); | |
| 266 | + } | |
| 267 | + } | |
| 268 | + | |
| 269 | + | |
| 270 | + /** | |
| 271 | + * Gets the EE route data | |
| 272 | + * | |
| 273 | +	 * @return array top-level key is the namespace, next-level key is the route and its value is array{ | |
| 274 | + * @throws \EE_Error | |
| 275 | + * @type string|array $callback | |
| 276 | + * @type string $methods | |
| 277 | + * @type boolean $hidden_endpoint | |
| 278 | + * } | |
| 279 | + */ | |
| 280 | + public static function get_ee_route_data() | |
| 281 | +	{ | |
| 282 | + $ee_routes = array(); | |
| 283 | +		foreach (self::versions_served() as $version => $hidden_endpoints) { | |
| 284 | + $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version( | |
| 285 | + $version, | |
| 286 | + $hidden_endpoints | |
| 287 | + ); | |
| 288 | + } | |
| 289 | + return $ee_routes; | |
| 290 | + } | |
| 291 | + | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * Gets the EE route data from the wp options if it exists already, | |
| 295 | + * otherwise re-generates it and saves it to the option | |
| 296 | + * | |
| 297 | + * @param string $version | |
| 298 | + * @param boolean $hidden_endpoints | |
| 299 | + * @return array | |
| 300 | + * @throws \EE_Error | |
| 301 | + */ | |
| 302 | + protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false) | |
| 303 | +	{ | |
| 304 | + $ee_routes = get_option(self::saved_routes_option_names . $version, null); | |
| 305 | +		if (! $ee_routes || EED_Core_Rest_Api::debugMode()) { | |
| 306 | + $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints); | |
| 307 | + } | |
| 308 | + return $ee_routes; | |
| 309 | + } | |
| 310 | + | |
| 311 | + | |
| 312 | + /** | |
| 313 | + * Saves the EE REST API route data to a wp option and returns it | |
| 314 | + * | |
| 315 | + * @param string $version | |
| 316 | + * @param boolean $hidden_endpoints | |
| 317 | + * @return mixed|null | |
| 318 | + * @throws \EE_Error | |
| 319 | + */ | |
| 320 | + protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false) | |
| 321 | +	{ | |
| 322 | + $instance = self::instance(); | |
| 323 | + $routes = apply_filters( | |
| 324 | + 'EED_Core_Rest_Api__save_ee_route_data_for_version__routes', | |
| 325 | + array_replace_recursive( | |
| 326 | + $instance->_get_config_route_data_for_version($version, $hidden_endpoints), | |
| 327 | + $instance->_get_meta_route_data_for_version($version, $hidden_endpoints), | |
| 328 | + $instance->_get_model_route_data_for_version($version, $hidden_endpoints), | |
| 329 | + $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints) | |
| 330 | + ) | |
| 331 | + ); | |
| 332 | + $option_name = self::saved_routes_option_names . $version; | |
| 333 | +		if (get_option($option_name)) { | |
| 334 | + update_option($option_name, $routes, true); | |
| 335 | +		} else { | |
| 336 | + add_option($option_name, $routes, null, 'no'); | |
| 337 | + } | |
| 338 | + return $routes; | |
| 339 | + } | |
| 340 | + | |
| 341 | + | |
| 342 | + /** | |
| 343 | + * Calculates all the EE routes and saves it to a WordPress option so we don't | |
| 344 | + * need to calculate it on every request | |
| 345 | + * | |
| 346 | + * @deprecated since version 4.9.1 | |
| 347 | + * @return void | |
| 348 | + */ | |
| 349 | + public static function save_ee_routes() | |
| 350 | +	{ | |
| 351 | +		if (EE_Maintenance_Mode::instance()->models_can_query()) { | |
| 352 | + $instance = self::instance(); | |
| 353 | + $routes = apply_filters( | |
| 354 | + 'EED_Core_Rest_Api__save_ee_routes__routes', | |
| 355 | + array_replace_recursive( | |
| 356 | + $instance->_register_config_routes(), | |
| 357 | + $instance->_register_meta_routes(), | |
| 358 | + $instance->_register_model_routes(), | |
| 359 | + $instance->_register_rpc_routes() | |
| 360 | + ) | |
| 361 | + ); | |
| 362 | + update_option(self::saved_routes_option_names, $routes, true); | |
| 363 | + } | |
| 364 | + } | |
| 365 | + | |
| 366 | + | |
| 367 | + /** | |
| 368 | + * Gets all the route information relating to EE models | |
| 369 | + * | |
| 370 | + * @return array @see get_ee_route_data | |
| 371 | + * @deprecated since version 4.9.1 | |
| 372 | + */ | |
| 373 | + protected function _register_model_routes() | |
| 374 | +	{ | |
| 375 | + $model_routes = array(); | |
| 376 | +		foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 377 | + $model_routes[ EED_Core_Rest_Api::ee_api_namespace | |
| 378 | + . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint); | |
| 379 | + } | |
| 380 | + return $model_routes; | |
| 381 | + } | |
| 382 | + | |
| 383 | + | |
| 384 | + /** | |
| 385 | + * Decides whether or not to add write endpoints for this model. | |
| 386 | + * | |
| 387 | + * Currently, this defaults to exclude all global tables and models | |
| 388 | + * which would allow inserting WP core data (we don't want to duplicate | |
| 389 | + * what WP API does, as it's unnecessary, extra work, and potentially extra bugs) | |
| 390 | + * | |
| 391 | + * @param EEM_Base $model | |
| 392 | + * @return bool | |
| 393 | + */ | |
| 394 | + public static function should_have_write_endpoints(EEM_Base $model) | |
| 395 | +	{ | |
| 396 | +		if ($model->is_wp_core_model()) { | |
| 397 | + return false; | |
| 398 | + } | |
| 399 | +		foreach ($model->get_tables() as $table) { | |
| 400 | +			if ($table->is_global()) { | |
| 401 | + return false; | |
| 402 | + } | |
| 403 | + } | |
| 404 | + return true; | |
| 405 | + } | |
| 406 | + | |
| 407 | + | |
| 408 | + /** | |
| 409 | + * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`) | |
| 410 | + * in this versioned namespace of EE4 | |
| 411 | + * | |
| 412 | + * @param $version | |
| 413 | + * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event') | |
| 414 | + */ | |
| 415 | + public static function model_names_with_plural_routes($version) | |
| 416 | +	{ | |
| 417 | + $model_version_info = new ModelVersionInfo($version); | |
| 418 | + $models_to_register = $model_version_info->modelsForRequestedVersion(); | |
| 419 | + // let's not bother having endpoints for extra metas | |
| 420 | + unset( | |
| 421 | + $models_to_register['Extra_Meta'], | |
| 422 | + $models_to_register['Extra_Join'], | |
| 423 | + $models_to_register['Post_Meta'] | |
| 424 | + ); | |
| 425 | + return apply_filters( | |
| 426 | + 'FHEE__EED_Core_REST_API___register_model_routes', | |
| 427 | + $models_to_register | |
| 428 | + ); | |
| 429 | + } | |
| 430 | + | |
| 431 | + | |
| 432 | + /** | |
| 433 | + * Gets the route data for EE models in the specified version | |
| 434 | + * | |
| 435 | + * @param string $version | |
| 436 | + * @param boolean $hidden_endpoint | |
| 437 | + * @return array | |
| 438 | + * @throws EE_Error | |
| 439 | + */ | |
| 440 | + protected function _get_model_route_data_for_version($version, $hidden_endpoint = false) | |
| 441 | +	{ | |
| 442 | + $model_routes = array(); | |
| 443 | + $model_version_info = new ModelVersionInfo($version); | |
| 444 | +		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) { | |
| 445 | + $model = \EE_Registry::instance()->load_model($model_name); | |
| 446 | + // if this isn't a valid model then let's skip iterate to the next item in the loop. | |
| 447 | +			if (! $model instanceof EEM_Base) { | |
| 448 | + continue; | |
| 449 | + } | |
| 450 | + // yes we could just register one route for ALL models, but then they wouldn't show up in the index | |
| 451 | + $plural_model_route = EED_Core_Rest_Api::get_collection_route($model); | |
| 452 | + $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)'); | |
| 453 | + $model_routes[ $plural_model_route ] = array( | |
| 454 | + array( | |
| 455 | + 'callback' => array( | |
| 456 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 457 | + 'handleRequestGetAll', | |
| 458 | + ), | |
| 459 | + 'callback_args' => array($version, $model_name), | |
| 460 | + 'methods' => WP_REST_Server::READABLE, | |
| 461 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 462 | + 'args' => $this->_get_read_query_params($model, $version), | |
| 463 | + '_links' => array( | |
| 464 | + 'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route), | |
| 465 | + ), | |
| 466 | + ), | |
| 467 | + 'schema' => array( | |
| 468 | + 'schema_callback' => array( | |
| 469 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 470 | + 'handleSchemaRequest', | |
| 471 | + ), | |
| 472 | + 'callback_args' => array($version, $model_name), | |
| 473 | + ), | |
| 474 | + ); | |
| 475 | + $model_routes[ $singular_model_route ] = array( | |
| 476 | + array( | |
| 477 | + 'callback' => array( | |
| 478 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 479 | + 'handleRequestGetOne', | |
| 480 | + ), | |
| 481 | + 'callback_args' => array($version, $model_name), | |
| 482 | + 'methods' => WP_REST_Server::READABLE, | |
| 483 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 484 | + 'args' => $this->_get_response_selection_query_params($model, $version, true), | |
| 485 | + ), | |
| 486 | + ); | |
| 487 | + if (apply_filters( | |
| 488 | + 'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints', | |
| 489 | + EED_Core_Rest_Api::should_have_write_endpoints($model), | |
| 490 | + $model | |
| 491 | +			)) { | |
| 492 | + $model_routes[ $plural_model_route ][] = array( | |
| 493 | + 'callback' => array( | |
| 494 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 495 | + 'handleRequestInsert', | |
| 496 | + ), | |
| 497 | + 'callback_args' => array($version, $model_name), | |
| 498 | + 'methods' => WP_REST_Server::CREATABLE, | |
| 499 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 500 | + 'args' => $this->_get_write_params($model_name, $model_version_info, true), | |
| 501 | + ); | |
| 502 | + $model_routes[ $singular_model_route ] = array_merge( | |
| 503 | + $model_routes[ $singular_model_route ], | |
| 504 | + array( | |
| 505 | + array( | |
| 506 | + 'callback' => array( | |
| 507 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 508 | + 'handleRequestUpdate', | |
| 509 | + ), | |
| 510 | + 'callback_args' => array($version, $model_name), | |
| 511 | + 'methods' => WP_REST_Server::EDITABLE, | |
| 512 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 513 | + 'args' => $this->_get_write_params($model_name, $model_version_info), | |
| 514 | + ), | |
| 515 | + array( | |
| 516 | + 'callback' => array( | |
| 517 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 518 | + 'handleRequestDelete', | |
| 519 | + ), | |
| 520 | + 'callback_args' => array($version, $model_name), | |
| 521 | + 'methods' => WP_REST_Server::DELETABLE, | |
| 522 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 523 | + 'args' => $this->_get_delete_query_params($model, $version), | |
| 524 | + ), | |
| 525 | + ) | |
| 526 | + ); | |
| 527 | + } | |
| 528 | +			foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 529 | + $related_route = EED_Core_Rest_Api::get_relation_route_via( | |
| 530 | + $model, | |
| 531 | + '(?P<id>[^\/]+)', | |
| 532 | + $relation_obj | |
| 533 | + ); | |
| 534 | + $model_routes[ $related_route ] = array( | |
| 535 | + array( | |
| 536 | + 'callback' => array( | |
| 537 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | |
| 538 | + 'handleRequestGetRelated', | |
| 539 | + ), | |
| 540 | + 'callback_args' => array($version, $model_name, $relation_name), | |
| 541 | + 'methods' => WP_REST_Server::READABLE, | |
| 542 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 543 | + 'args' => $this->_get_read_query_params($relation_obj->get_other_model(), $version), | |
| 544 | + ), | |
| 545 | + ); | |
| 546 | + | |
| 547 | + $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)'; | |
| 548 | + $model_routes[ $related_write_route ] = array( | |
| 549 | + array( | |
| 550 | + 'callback' => array( | |
| 551 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 552 | + 'handleRequestAddRelation', | |
| 553 | + ), | |
| 554 | + 'callback_args' => array($version, $model_name, $relation_name), | |
| 555 | + 'methods' => WP_REST_Server::EDITABLE, | |
| 556 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 557 | + 'args' => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version) | |
| 558 | + ), | |
| 559 | + array( | |
| 560 | + 'callback' => array( | |
| 561 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | |
| 562 | + 'handleRequestRemoveRelation', | |
| 563 | + ), | |
| 564 | + 'callback_args' => array($version, $model_name, $relation_name), | |
| 565 | + 'methods' => WP_REST_Server::DELETABLE, | |
| 566 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 567 | + 'args' => array() | |
| 568 | + ), | |
| 569 | + ); | |
| 570 | + } | |
| 571 | + } | |
| 572 | + return $model_routes; | |
| 573 | + } | |
| 574 | + | |
| 575 | + | |
| 576 | + /** | |
| 577 | + * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace, | |
| 578 | + * excluding the preceding slash. | |
| 579 | +	 * Eg you pass get_plural_route_to('Event') = 'events' | |
| 580 | + * | |
| 581 | + * @param EEM_Base $model | |
| 582 | + * @return string | |
| 583 | + */ | |
| 584 | + public static function get_collection_route(EEM_Base $model) | |
| 585 | +	{ | |
| 586 | + return EEH_Inflector::pluralize_and_lower($model->get_this_model_name()); | |
| 587 | + } | |
| 588 | + | |
| 589 | + | |
| 590 | + /** | |
| 591 | + * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace, | |
| 592 | + * excluding the preceding slash. | |
| 593 | +	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12' | |
| 594 | + * | |
| 595 | + * @param EEM_Base $model eg Event or Venue | |
| 596 | + * @param string $id | |
| 597 | + * @return string | |
| 598 | + */ | |
| 599 | + public static function get_entity_route($model, $id) | |
| 600 | +	{ | |
| 601 | + return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id; | |
| 602 | + } | |
| 603 | + | |
| 604 | + | |
| 605 | + /** | |
| 606 | + * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace, | |
| 607 | + * excluding the preceding slash. | |
| 608 | +	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12' | |
| 609 | + * | |
| 610 | + * @param EEM_Base $model eg Event or Venue | |
| 611 | + * @param string $id | |
| 612 | + * @param EE_Model_Relation_Base $relation_obj | |
| 613 | + * @return string | |
| 614 | + */ | |
| 615 | + public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj) | |
| 616 | +	{ | |
| 617 | + $related_model_name_endpoint_part = ModelRead::getRelatedEntityName( | |
| 618 | + $relation_obj->get_other_model()->get_this_model_name(), | |
| 619 | + $relation_obj | |
| 620 | + ); | |
| 621 | + return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part; | |
| 622 | + } | |
| 623 | + | |
| 624 | + | |
| 625 | + /** | |
| 626 | + * Adds onto the $relative_route the EE4 REST API versioned namespace. | |
| 627 | + * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events' | |
| 628 | + * | |
| 629 | + * @param string $relative_route | |
| 630 | + * @param string $version | |
| 631 | + * @return string | |
| 632 | + */ | |
| 633 | + public static function get_versioned_route_to($relative_route, $version = '4.8.36') | |
| 634 | +	{ | |
| 635 | + return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route; | |
| 636 | + } | |
| 637 | + | |
| 638 | + | |
| 639 | + /** | |
| 640 | + * Adds all the RPC-style routes (remote procedure call-like routes, ie | |
| 641 | + * routes that don't conform to the traditional REST CRUD-style). | |
| 642 | + * | |
| 643 | + * @deprecated since 4.9.1 | |
| 644 | + */ | |
| 645 | + protected function _register_rpc_routes() | |
| 646 | +	{ | |
| 647 | + $routes = array(); | |
| 648 | +		foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 649 | + $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version( | |
| 650 | + $version, | |
| 651 | + $hidden_endpoint | |
| 652 | + ); | |
| 653 | + } | |
| 654 | + return $routes; | |
| 655 | + } | |
| 656 | + | |
| 657 | + | |
| 658 | + /** | |
| 659 | + * @param string $version | |
| 660 | + * @param boolean $hidden_endpoint | |
| 661 | + * @return array | |
| 662 | + */ | |
| 663 | + protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false) | |
| 664 | +	{ | |
| 665 | + $this_versions_routes = array(); | |
| 666 | + // checkin endpoint | |
| 667 | + $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array( | |
| 668 | + array( | |
| 669 | + 'callback' => array( | |
| 670 | + 'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin', | |
| 671 | + 'handleRequestToggleCheckin', | |
| 672 | + ), | |
| 673 | + 'methods' => WP_REST_Server::CREATABLE, | |
| 674 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 675 | + 'args' => array( | |
| 676 | + 'force' => array( | |
| 677 | + 'required' => false, | |
| 678 | + 'default' => false, | |
| 679 | + 'description' => __( | |
| 680 | + // @codingStandardsIgnoreStart | |
| 681 | + 'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses', | |
| 682 | + // @codingStandardsIgnoreEnd | |
| 683 | + 'event_espresso' | |
| 684 | + ), | |
| 685 | + ), | |
| 686 | + ), | |
| 687 | + 'callback_args' => array($version), | |
| 688 | + ), | |
| 689 | + ); | |
| 690 | + return apply_filters( | |
| 691 | + 'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes', | |
| 692 | + $this_versions_routes, | |
| 693 | + $version, | |
| 694 | + $hidden_endpoint | |
| 695 | + ); | |
| 696 | + } | |
| 697 | + | |
| 698 | + | |
| 699 | + /** | |
| 700 | + * Gets the query params that can be used when request one or many | |
| 701 | + * | |
| 702 | + * @param EEM_Base $model | |
| 703 | + * @param string $version | |
| 704 | + * @return array | |
| 705 | + */ | |
| 706 | + protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false) | |
| 707 | +	{ | |
| 708 | + $query_params = array( | |
| 709 | + 'include' => array( | |
| 710 | + 'required' => false, | |
| 711 | + 'default' => '*', | |
| 712 | + 'type' => 'string', | |
| 713 | + ), | |
| 714 | + 'calculate' => array( | |
| 715 | + 'required' => false, | |
| 716 | + 'default' => '', | |
| 717 | + 'enum' => self::$_field_calculator->retrieveCalculatedFieldsForModel($model), | |
| 718 | + 'type' => 'string', | |
| 719 | + // because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization | |
| 720 | + // freaks out. We'll just validate this argument while handling the request | |
| 721 | + 'validate_callback' => null, | |
| 722 | + 'sanitize_callback' => null, | |
| 723 | + ), | |
| 724 | + 'password' => array( | |
| 725 | + 'required' => false, | |
| 726 | + 'default' => '', | |
| 727 | + 'type' => 'string' | |
| 728 | + ) | |
| 729 | + ); | |
| 730 | + return apply_filters( | |
| 731 | + 'FHEE__EED_Core_Rest_Api___get_response_selection_query_params', | |
| 732 | + $query_params, | |
| 733 | + $model, | |
| 734 | + $version | |
| 735 | + ); | |
| 736 | + } | |
| 737 | + | |
| 738 | + | |
| 739 | + /** | |
| 740 | + * Gets the parameters acceptable for delete requests | |
| 741 | + * | |
| 742 | + * @param \EEM_Base $model | |
| 743 | + * @param string $version | |
| 744 | + * @return array | |
| 745 | + */ | |
| 746 | + protected function _get_delete_query_params(\EEM_Base $model, $version) | |
| 747 | +	{ | |
| 748 | + $params_for_delete = array( | |
| 749 | + 'allow_blocking' => array( | |
| 750 | + 'required' => false, | |
| 751 | + 'default' => true, | |
| 752 | + 'type' => 'boolean', | |
| 753 | + ), | |
| 754 | + ); | |
| 755 | + $params_for_delete['force'] = array( | |
| 756 | + 'required' => false, | |
| 757 | + 'default' => false, | |
| 758 | + 'type' => 'boolean', | |
| 759 | + ); | |
| 760 | + return apply_filters( | |
| 761 | + 'FHEE__EED_Core_Rest_Api___get_delete_query_params', | |
| 762 | + $params_for_delete, | |
| 763 | + $model, | |
| 764 | + $version | |
| 765 | + ); | |
| 766 | + } | |
| 767 | + | |
| 768 | + protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version) | |
| 769 | +	{ | |
| 770 | + // if they're related through a HABTM relation, check for any non-FKs | |
| 771 | + $all_relation_settings = $source_model->relation_settings(); | |
| 772 | + $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ]; | |
| 773 | + $params = array(); | |
| 774 | +		if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) { | |
| 775 | +			foreach ($relation_settings->getNonKeyFields() as $field) { | |
| 776 | + /* @var $field EE_Model_Field_Base */ | |
| 777 | + $params[ $field->get_name() ] = array( | |
| 778 | + 'required' => ! $field->is_nullable(), | |
| 779 | + 'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version), | |
| 780 | + 'type' => $field->getSchemaType(), | |
| 781 | + 'validate_callbaack' => null, | |
| 782 | + 'sanitize_callback' => null | |
| 783 | + ); | |
| 784 | + } | |
| 785 | + } | |
| 786 | + return $params; | |
| 787 | + } | |
| 788 | + | |
| 789 | + | |
| 790 | + /** | |
| 791 | + * Gets info about reading query params that are acceptable | |
| 792 | + * | |
| 793 | + * @param \EEM_Base $model eg 'Event' or 'Venue' | |
| 794 | + * @param string $version | |
| 795 | + * @return array describing the args acceptable when querying this model | |
| 796 | + * @throws EE_Error | |
| 797 | + */ | |
| 798 | + protected function _get_read_query_params(\EEM_Base $model, $version) | |
| 799 | +	{ | |
| 800 | + $default_orderby = array(); | |
| 801 | +		foreach ($model->get_combined_primary_key_fields() as $key_field) { | |
| 802 | + $default_orderby[ $key_field->get_name() ] = 'ASC'; | |
| 803 | + } | |
| 804 | + return array_merge( | |
| 805 | + $this->_get_response_selection_query_params($model, $version), | |
| 806 | + array( | |
| 807 | + 'where' => array( | |
| 808 | + 'required' => false, | |
| 809 | + 'default' => array(), | |
| 810 | + 'type' => 'object', | |
| 811 | + // because we accept an almost infinite list of possible where conditions, WP | |
| 812 | + // core validation and sanitization freaks out. We'll just validate this argument | |
| 813 | + // while handling the request | |
| 814 | + 'validate_callback' => null, | |
| 815 | + 'sanitize_callback' => null, | |
| 816 | + ), | |
| 817 | + 'limit' => array( | |
| 818 | + 'required' => false, | |
| 819 | + 'default' => EED_Core_Rest_Api::get_default_query_limit(), | |
| 820 | + 'type' => array( | |
| 821 | + 'array', | |
| 822 | + 'string', | |
| 823 | + 'integer', | |
| 824 | + ), | |
| 825 | + // because we accept a variety of types, WP core validation and sanitization | |
| 826 | + // freaks out. We'll just validate this argument while handling the request | |
| 827 | + 'validate_callback' => null, | |
| 828 | + 'sanitize_callback' => null, | |
| 829 | + ), | |
| 830 | + 'order_by' => array( | |
| 831 | + 'required' => false, | |
| 832 | + 'default' => $default_orderby, | |
| 833 | + 'type' => array( | |
| 834 | + 'object', | |
| 835 | + 'string', | |
| 836 | + ),// because we accept a variety of types, WP core validation and sanitization | |
| 837 | + // freaks out. We'll just validate this argument while handling the request | |
| 838 | + 'validate_callback' => null, | |
| 839 | + 'sanitize_callback' => null, | |
| 840 | + ), | |
| 841 | + 'group_by' => array( | |
| 842 | + 'required' => false, | |
| 843 | + 'default' => null, | |
| 844 | + 'type' => array( | |
| 845 | + 'object', | |
| 846 | + 'string', | |
| 847 | + ), | |
| 848 | + // because we accept an almost infinite list of possible groupings, | |
| 849 | + // WP core validation and sanitization | |
| 850 | + // freaks out. We'll just validate this argument while handling the request | |
| 851 | + 'validate_callback' => null, | |
| 852 | + 'sanitize_callback' => null, | |
| 853 | + ), | |
| 854 | + 'having' => array( | |
| 855 | + 'required' => false, | |
| 856 | + 'default' => null, | |
| 857 | + 'type' => 'object', | |
| 858 | + // because we accept an almost infinite list of possible where conditions, WP | |
| 859 | + // core validation and sanitization freaks out. We'll just validate this argument | |
| 860 | + // while handling the request | |
| 861 | + 'validate_callback' => null, | |
| 862 | + 'sanitize_callback' => null, | |
| 863 | + ), | |
| 864 | + 'caps' => array( | |
| 865 | + 'required' => false, | |
| 866 | + 'default' => EEM_Base::caps_read, | |
| 867 | + 'type' => 'string', | |
| 868 | + 'enum' => array( | |
| 869 | + EEM_Base::caps_read, | |
| 870 | + EEM_Base::caps_read_admin, | |
| 871 | + EEM_Base::caps_edit, | |
| 872 | + EEM_Base::caps_delete, | |
| 873 | + ), | |
| 874 | + ), | |
| 875 | + ) | |
| 876 | + ); | |
| 877 | + } | |
| 878 | + | |
| 879 | + | |
| 880 | + /** | |
| 881 | + * Gets parameter information for a model regarding writing data | |
| 882 | + * | |
| 883 | + * @param string $model_name | |
| 884 | + * @param ModelVersionInfo $model_version_info | |
| 885 | + * @param boolean $create whether this is for request to create (in | |
| 886 | + * which case we need all required params) or | |
| 887 | + * just to update (in which case we don't | |
| 888 | + * need those on every request) | |
| 889 | + * @return array | |
| 890 | + */ | |
| 891 | + protected function _get_write_params( | |
| 892 | + $model_name, | |
| 893 | + ModelVersionInfo $model_version_info, | |
| 894 | + $create = false | |
| 895 | +	) { | |
| 896 | + $model = EE_Registry::instance()->load_model($model_name); | |
| 897 | + $fields = $model_version_info->fieldsOnModelInThisVersion($model); | |
| 898 | + $args_info = array(); | |
| 899 | +		foreach ($fields as $field_name => $field_obj) { | |
| 900 | +			if ($field_obj->is_auto_increment()) { | |
| 901 | + // totally ignore auto increment IDs | |
| 902 | + continue; | |
| 903 | + } | |
| 904 | + $arg_info = $field_obj->getSchema(); | |
| 905 | + $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null; | |
| 906 | + $arg_info['required'] = $required; | |
| 907 | + // remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right? | |
| 908 | + unset($arg_info['readonly']); | |
| 909 | + $schema_properties = $field_obj->getSchemaProperties(); | |
| 910 | + if (isset($schema_properties['raw']) | |
| 911 | + && $field_obj->getSchemaType() === 'object' | |
| 912 | +			) { | |
| 913 | + // if there's a "raw" form of this argument, use those properties instead | |
| 914 | + $arg_info = array_replace( | |
| 915 | + $arg_info, | |
| 916 | + $schema_properties['raw'] | |
| 917 | + ); | |
| 918 | + } | |
| 919 | + $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 920 | + $field_obj, | |
| 921 | + $field_obj->get_default_value(), | |
| 922 | + $model_version_info->requestedVersion() | |
| 923 | + ); | |
| 924 | + // we do our own validation and sanitization within the controller | |
| 925 | +			if (function_exists('rest_validate_value_from_schema')) { | |
| 926 | + $sanitize_callback = array( | |
| 927 | + 'EED_Core_Rest_Api', | |
| 928 | + 'default_sanitize_callback', | |
| 929 | + ); | |
| 930 | +			} else { | |
| 931 | + $sanitize_callback = null; | |
| 932 | + } | |
| 933 | + $arg_info['sanitize_callback'] = $sanitize_callback; | |
| 934 | + $args_info[ $field_name ] = $arg_info; | |
| 935 | +			if ($field_obj instanceof EE_Datetime_Field) { | |
| 936 | + $gmt_arg_info = $arg_info; | |
| 937 | + $gmt_arg_info['description'] = sprintf( | |
| 938 | + esc_html__( | |
| 939 | + '%1$s - the value for this field in UTC. Ignored if %2$s is provided.', | |
| 940 | + 'event_espresso' | |
| 941 | + ), | |
| 942 | + $field_obj->get_nicename(), | |
| 943 | + $field_name | |
| 944 | + ); | |
| 945 | + $args_info[ $field_name . '_gmt' ] = $gmt_arg_info; | |
| 946 | + } | |
| 947 | + } | |
| 948 | + return $args_info; | |
| 949 | + } | |
| 950 | + | |
| 951 | + | |
| 952 | + /** | |
| 953 | + * Replacement for WP API's 'rest_parse_request_arg'. | |
| 954 | + * If the value is blank but not required, don't bother validating it. | |
| 955 | + * Also, it uses our email validation instead of WP API's default. | |
| 956 | + * | |
| 957 | + * @param $value | |
| 958 | + * @param WP_REST_Request $request | |
| 959 | + * @param $param | |
| 960 | + * @return bool|true|WP_Error | |
| 961 | + * @throws InvalidArgumentException | |
| 962 | + * @throws InvalidInterfaceException | |
| 963 | + * @throws InvalidDataTypeException | |
| 964 | + */ | |
| 965 | + public static function default_sanitize_callback($value, WP_REST_Request $request, $param) | |
| 966 | +	{ | |
| 967 | + $attributes = $request->get_attributes(); | |
| 968 | + if (! isset($attributes['args'][ $param ]) | |
| 969 | +			|| ! is_array($attributes['args'][ $param ])) { | |
| 970 | + $validation_result = true; | |
| 971 | +		} else { | |
| 972 | + $args = $attributes['args'][ $param ]; | |
| 973 | + if (( | |
| 974 | + $value === '' | |
| 975 | + || $value === null | |
| 976 | + ) | |
| 977 | + && (! isset($args['required']) | |
| 978 | + || $args['required'] === false | |
| 979 | + ) | |
| 980 | +			) { | |
| 981 | + // not required and not provided? that's cool | |
| 982 | + $validation_result = true; | |
| 983 | + } elseif (isset($args['format']) | |
| 984 | + && $args['format'] === 'email' | |
| 985 | +			) { | |
| 986 | + $validation_result = true; | |
| 987 | +				if (! self::_validate_email($value)) { | |
| 988 | + $validation_result = new WP_Error( | |
| 989 | + 'rest_invalid_param', | |
| 990 | + esc_html__( | |
| 991 | + 'The email address is not valid or does not exist.', | |
| 992 | + 'event_espresso' | |
| 993 | + ) | |
| 994 | + ); | |
| 995 | + } | |
| 996 | +			} else { | |
| 997 | + $validation_result = rest_validate_value_from_schema($value, $args, $param); | |
| 998 | + } | |
| 999 | + } | |
| 1000 | +		if (is_wp_error($validation_result)) { | |
| 1001 | + return $validation_result; | |
| 1002 | + } | |
| 1003 | + return rest_sanitize_request_arg($value, $request, $param); | |
| 1004 | + } | |
| 1005 | + | |
| 1006 | + | |
| 1007 | + /** | |
| 1008 | + * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email() | |
| 1009 | + * | |
| 1010 | + * @param $email | |
| 1011 | + * @return bool | |
| 1012 | + * @throws InvalidArgumentException | |
| 1013 | + * @throws InvalidInterfaceException | |
| 1014 | + * @throws InvalidDataTypeException | |
| 1015 | + */ | |
| 1016 | + protected static function _validate_email($email) | |
| 1017 | +	{ | |
| 1018 | +		try { | |
| 1019 | + EmailAddressFactory::create($email); | |
| 1020 | + return true; | |
| 1021 | +		} catch (EmailValidationException $e) { | |
| 1022 | + return false; | |
| 1023 | + } | |
| 1024 | + } | |
| 1025 | + | |
| 1026 | + | |
| 1027 | + /** | |
| 1028 | + * Gets routes for the config | |
| 1029 | + * | |
| 1030 | + * @return array @see _register_model_routes | |
| 1031 | + * @deprecated since version 4.9.1 | |
| 1032 | + */ | |
| 1033 | + protected function _register_config_routes() | |
| 1034 | +	{ | |
| 1035 | + $config_routes = array(); | |
| 1036 | +		foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 1037 | + $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version( | |
| 1038 | + $version, | |
| 1039 | + $hidden_endpoint | |
| 1040 | + ); | |
| 1041 | + } | |
| 1042 | + return $config_routes; | |
| 1043 | + } | |
| 1044 | + | |
| 1045 | + | |
| 1046 | + /** | |
| 1047 | + * Gets routes for the config for the specified version | |
| 1048 | + * | |
| 1049 | + * @param string $version | |
| 1050 | + * @param boolean $hidden_endpoint | |
| 1051 | + * @return array | |
| 1052 | + */ | |
| 1053 | + protected function _get_config_route_data_for_version($version, $hidden_endpoint) | |
| 1054 | +	{ | |
| 1055 | + return array( | |
| 1056 | + 'config' => array( | |
| 1057 | + array( | |
| 1058 | + 'callback' => array( | |
| 1059 | + 'EventEspresso\core\libraries\rest_api\controllers\config\Read', | |
| 1060 | + 'handleRequest', | |
| 1061 | + ), | |
| 1062 | + 'methods' => WP_REST_Server::READABLE, | |
| 1063 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 1064 | + 'callback_args' => array($version), | |
| 1065 | + ), | |
| 1066 | + ), | |
| 1067 | + 'site_info' => array( | |
| 1068 | + array( | |
| 1069 | + 'callback' => array( | |
| 1070 | + 'EventEspresso\core\libraries\rest_api\controllers\config\Read', | |
| 1071 | + 'handleRequestSiteInfo', | |
| 1072 | + ), | |
| 1073 | + 'methods' => WP_REST_Server::READABLE, | |
| 1074 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 1075 | + 'callback_args' => array($version), | |
| 1076 | + ), | |
| 1077 | + ), | |
| 1078 | + ); | |
| 1079 | + } | |
| 1080 | + | |
| 1081 | + | |
| 1082 | + /** | |
| 1083 | + * Gets the meta info routes | |
| 1084 | + * | |
| 1085 | + * @return array @see _register_model_routes | |
| 1086 | + * @deprecated since version 4.9.1 | |
| 1087 | + */ | |
| 1088 | + protected function _register_meta_routes() | |
| 1089 | +	{ | |
| 1090 | + $meta_routes = array(); | |
| 1091 | +		foreach (self::versions_served() as $version => $hidden_endpoint) { | |
| 1092 | + $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version( | |
| 1093 | + $version, | |
| 1094 | + $hidden_endpoint | |
| 1095 | + ); | |
| 1096 | + } | |
| 1097 | + return $meta_routes; | |
| 1098 | + } | |
| 1099 | + | |
| 1100 | + | |
| 1101 | + /** | |
| 1102 | + * @param string $version | |
| 1103 | + * @param boolean $hidden_endpoint | |
| 1104 | + * @return array | |
| 1105 | + */ | |
| 1106 | + protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false) | |
| 1107 | +	{ | |
| 1108 | + return array( | |
| 1109 | + 'resources' => array( | |
| 1110 | + array( | |
| 1111 | + 'callback' => array( | |
| 1112 | + 'EventEspresso\core\libraries\rest_api\controllers\model\Meta', | |
| 1113 | + 'handleRequestModelsMeta', | |
| 1114 | + ), | |
| 1115 | + 'methods' => WP_REST_Server::READABLE, | |
| 1116 | + 'hidden_endpoint' => $hidden_endpoint, | |
| 1117 | + 'callback_args' => array($version), | |
| 1118 | + ), | |
| 1119 | + ), | |
| 1120 | + ); | |
| 1121 | + } | |
| 1122 | + | |
| 1123 | + | |
| 1124 | + /** | |
| 1125 | + * Tries to hide old 4.6 endpoints from the | |
| 1126 | + * | |
| 1127 | + * @param array $route_data | |
| 1128 | + * @return array | |
| 1129 | + * @throws \EE_Error | |
| 1130 | + */ | |
| 1131 | + public static function hide_old_endpoints($route_data) | |
| 1132 | +	{ | |
| 1133 | + // allow API clients to override which endpoints get hidden, in case | |
| 1134 | + // they want to discover particular endpoints | |
| 1135 | + // also, we don't have access to the request so we have to just grab it from the superglobal | |
| 1136 | + $force_show_ee_namespace = ltrim( | |
| 1137 | + EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''), | |
| 1138 | + '/' | |
| 1139 | + ); | |
| 1140 | +		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) { | |
| 1141 | +			foreach ($relative_urls as $resource_name => $endpoints) { | |
| 1142 | +				foreach ($endpoints as $key => $endpoint) { | |
| 1143 | + // skip schema and other route options | |
| 1144 | +					if (! is_numeric($key)) { | |
| 1145 | + continue; | |
| 1146 | + } | |
| 1147 | + // by default, hide "hidden_endpoint"s, unless the request indicates | |
| 1148 | + // to $force_show_ee_namespace, in which case only show that one | |
| 1149 | + // namespace's endpoints (and hide all others) | |
| 1150 | + if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace) | |
| 1151 | + || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '') | |
| 1152 | +					) { | |
| 1153 | + $full_route = '/' . ltrim($namespace, '/'); | |
| 1154 | + $full_route .= '/' . ltrim($resource_name, '/'); | |
| 1155 | + unset($route_data[ $full_route ]); | |
| 1156 | + } | |
| 1157 | + } | |
| 1158 | + } | |
| 1159 | + } | |
| 1160 | + return $route_data; | |
| 1161 | + } | |
| 1162 | + | |
| 1163 | + | |
| 1164 | + /** | |
| 1165 | + * Returns an array describing which versions of core support serving requests for. | |
| 1166 | + * Keys are core versions' major and minor version, and values are the | |
| 1167 | + * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like | |
| 1168 | + * data by just removing a few models and fields from the responses. However, 4.15 might remove | |
| 1169 | + * the answers table entirely, in which case it would be very difficult for | |
| 1170 | + * it to serve 4.6-style responses. | |
| 1171 | + * Versions of core that are missing from this array are unknowns. | |
| 1172 | + * previous ver | |
| 1173 | + * | |
| 1174 | + * @return array | |
| 1175 | + */ | |
| 1176 | + public static function version_compatibilities() | |
| 1177 | +	{ | |
| 1178 | + return apply_filters( | |
| 1179 | + 'FHEE__EED_Core_REST_API__version_compatibilities', | |
| 1180 | + array( | |
| 1181 | + '4.8.29' => '4.8.29', | |
| 1182 | + '4.8.33' => '4.8.29', | |
| 1183 | + '4.8.34' => '4.8.29', | |
| 1184 | + '4.8.36' => '4.8.29', | |
| 1185 | + ) | |
| 1186 | + ); | |
| 1187 | + } | |
| 1188 | + | |
| 1189 | + | |
| 1190 | + /** | |
| 1191 | + * Gets the latest API version served. Eg if there | |
| 1192 | + * are two versions served of the API, 4.8.29 and 4.8.32, and | |
| 1193 | + * we are on core version 4.8.34, it will return the string "4.8.32" | |
| 1194 | + * | |
| 1195 | + * @return string | |
| 1196 | + */ | |
| 1197 | + public static function latest_rest_api_version() | |
| 1198 | +	{ | |
| 1199 | + $versions_served = \EED_Core_Rest_Api::versions_served(); | |
| 1200 | + $versions_served_keys = array_keys($versions_served); | |
| 1201 | + return end($versions_served_keys); | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | + | |
| 1205 | + /** | |
| 1206 | + * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of | |
| 1207 | + * EE the API can serve requests for. Eg, if we are on 4.15 of core, and | |
| 1208 | + * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ). | |
| 1209 | + * We also indicate whether or not this version should be put in the index or not | |
| 1210 | + * | |
| 1211 | + * @return array keys are API version numbers (just major and minor numbers), and values | |
| 1212 | + * are whether or not they should be hidden | |
| 1213 | + */ | |
| 1214 | + public static function versions_served() | |
| 1215 | +	{ | |
| 1216 | + $versions_served = array(); | |
| 1217 | + $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities(); | |
| 1218 | + $lowest_compatible_version = end($possibly_served_versions); | |
| 1219 | + reset($possibly_served_versions); | |
| 1220 | + $versions_served_historically = array_keys($possibly_served_versions); | |
| 1221 | + $latest_version = end($versions_served_historically); | |
| 1222 | + reset($versions_served_historically); | |
| 1223 | + // for each version of core we have ever served: | |
| 1224 | +		foreach ($versions_served_historically as $key_versioned_endpoint) { | |
| 1225 | + // if it's not above the current core version, and it's compatible with the current version of core | |
| 1226 | +			if ($key_versioned_endpoint === $latest_version) { | |
| 1227 | + // don't hide the latest version in the index | |
| 1228 | + $versions_served[ $key_versioned_endpoint ] = false; | |
| 1229 | + } elseif ($key_versioned_endpoint >= $lowest_compatible_version | |
| 1230 | + && $key_versioned_endpoint < EED_Core_Rest_Api::core_version() | |
| 1231 | +			) { | |
| 1232 | + // include, but hide, previous versions which are still supported | |
| 1233 | + $versions_served[ $key_versioned_endpoint ] = true; | |
| 1234 | + } elseif (apply_filters( | |
| 1235 | + 'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions', | |
| 1236 | + false, | |
| 1237 | + $possibly_served_versions | |
| 1238 | +			)) { | |
| 1239 | + // if a version is no longer supported, don't include it in index or list of versions served | |
| 1240 | + $versions_served[ $key_versioned_endpoint ] = true; | |
| 1241 | + } | |
| 1242 | + } | |
| 1243 | + return $versions_served; | |
| 1244 | + } | |
| 1245 | + | |
| 1246 | + | |
| 1247 | + /** | |
| 1248 | + * Gets the major and minor version of EE core's version string | |
| 1249 | + * | |
| 1250 | + * @return string | |
| 1251 | + */ | |
| 1252 | + public static function core_version() | |
| 1253 | +	{ | |
| 1254 | + return apply_filters( | |
| 1255 | + 'FHEE__EED_Core_REST_API__core_version', | |
| 1256 | + implode( | |
| 1257 | + '.', | |
| 1258 | + array_slice( | |
| 1259 | + explode( | |
| 1260 | + '.', | |
| 1261 | + espresso_version() | |
| 1262 | + ), | |
| 1263 | + 0, | |
| 1264 | + 3 | |
| 1265 | + ) | |
| 1266 | + ) | |
| 1267 | + ); | |
| 1268 | + } | |
| 1269 | + | |
| 1270 | + | |
| 1271 | + /** | |
| 1272 | + * Gets the default limit that should be used when querying for resources | |
| 1273 | + * | |
| 1274 | + * @return int | |
| 1275 | + */ | |
| 1276 | + public static function get_default_query_limit() | |
| 1277 | +	{ | |
| 1278 | + // we actually don't use a const because we want folks to always use | |
| 1279 | + // this method, not the const directly | |
| 1280 | + return apply_filters( | |
| 1281 | + 'FHEE__EED_Core_Rest_Api__get_default_query_limit', | |
| 1282 | + 50 | |
| 1283 | + ); | |
| 1284 | + } | |
| 1285 | + | |
| 1286 | + | |
| 1287 | + /** | |
| 1288 | + * | |
| 1289 | + * @param string $version api version string (i.e. '4.8.36') | |
| 1290 | + * @return array | |
| 1291 | + */ | |
| 1292 | + public static function getCollectionRoutesIndexedByModelName($version = '') | |
| 1293 | +	{ | |
| 1294 | + $version = empty($version) ? self::latest_rest_api_version() : $version; | |
| 1295 | + $model_names = self::model_names_with_plural_routes($version); | |
| 1296 | + $collection_routes = array(); | |
| 1297 | +		foreach ($model_names as $model_name => $model_class_name) { | |
| 1298 | + $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/' | |
| 1299 | + . EEH_Inflector::pluralize_and_lower($model_name); | |
| 1300 | + } | |
| 1301 | + return $collection_routes; | |
| 1302 | + } | |
| 1303 | + | |
| 1304 | + | |
| 1305 | + /** | |
| 1306 | + * Returns an array of primary key names indexed by model names. | |
| 1307 | + * @param string $version | |
| 1308 | + * @return array | |
| 1309 | + */ | |
| 1310 | + public static function getPrimaryKeyNamesIndexedByModelName($version = '') | |
| 1311 | +	{ | |
| 1312 | + $version = empty($version) ? self::latest_rest_api_version() : $version; | |
| 1313 | + $model_names = self::model_names_with_plural_routes($version); | |
| 1314 | + $primary_key_items = array(); | |
| 1315 | +		foreach ($model_names as $model_name => $model_class_name) { | |
| 1316 | + $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields(); | |
| 1317 | +			foreach ($primary_keys as $primary_key_name => $primary_key_field) { | |
| 1318 | +				if (count($primary_keys) > 1) { | |
| 1319 | + $primary_key_items[ strtolower($model_name) ][] = $primary_key_name; | |
| 1320 | +				} else { | |
| 1321 | + $primary_key_items[ strtolower($model_name) ] = $primary_key_name; | |
| 1322 | + } | |
| 1323 | + } | |
| 1324 | + } | |
| 1325 | + return $primary_key_items; | |
| 1326 | + } | |
| 1327 | + | |
| 1328 | + /** | |
| 1329 | + * Determines the EE REST API debug mode is activated, or not. | |
| 1330 | + * @since $VID:$ | |
| 1331 | + * @return bool | |
| 1332 | + */ | |
| 1333 | + public static function debugMode() | |
| 1334 | +	{ | |
| 1335 | + static $debug_mode = null; // could be class prop | |
| 1336 | +		if ($debug_mode === null) { | |
| 1337 | +			$debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE; | |
| 1338 | + } | |
| 1339 | + return $debug_mode; | |
| 1340 | + } | |
| 1341 | + | |
| 1342 | + | |
| 1343 | + | |
| 1344 | + /** | |
| 1345 | + * run - initial module setup | |
| 1346 | + * | |
| 1347 | + * @access public | |
| 1348 | + * @param WP $WP | |
| 1349 | + * @return void | |
| 1350 | + */ | |
| 1351 | + public function run($WP) | |
| 1352 | +	{ | |
| 1353 | + } | |
| 1354 | 1354 | } | 
| @@ -123,7 +123,7 @@ discard block | ||
| 123 | 123 | */ | 
| 124 | 124 | protected static function _set_hooks_for_changes() | 
| 125 | 125 |      { | 
| 126 | - $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false); | |
| 126 | + $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api'.DS.'changes'), false); | |
| 127 | 127 |          foreach ($folder_contents as $classname_in_namespace => $filepath) { | 
| 128 | 128 | // ignore the base parent class | 
| 129 | 129 | // and legacy named classes | 
| @@ -132,7 +132,7 @@ discard block | ||
| 132 | 132 |              ) { | 
| 133 | 133 | continue; | 
| 134 | 134 | } | 
| 135 | - $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace; | |
| 135 | + $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace; | |
| 136 | 136 |              if (class_exists($full_classname)) { | 
| 137 | 137 | $instance_of_class = new $full_classname; | 
| 138 | 138 |                  if ($instance_of_class instanceof ChangesInBase) { | 
| @@ -177,10 +177,10 @@ discard block | ||
| 177 | 177 | * } | 
| 178 | 178 | */ | 
| 179 | 179 | // skip route options | 
| 180 | -                    if (! is_numeric($endpoint_key)) { | |
| 180 | +                    if ( ! is_numeric($endpoint_key)) { | |
| 181 | 181 | continue; | 
| 182 | 182 | } | 
| 183 | -                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) { | |
| 183 | +                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) { | |
| 184 | 184 | throw new EE_Error( | 
| 185 | 185 | esc_html__( | 
| 186 | 186 | // @codingStandardsIgnoreStart | 
| @@ -201,7 +201,7 @@ discard block | ||
| 201 | 201 | } | 
| 202 | 202 |                      if (isset($data_for_single_endpoint['callback_args'])) { | 
| 203 | 203 | $callback_args = $data_for_single_endpoint['callback_args']; | 
| 204 | - $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use ( | |
| 204 | + $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use ( | |
| 205 | 205 | $callback, | 
| 206 | 206 | $callback_args | 
| 207 | 207 |                          ) { | 
| @@ -220,7 +220,7 @@ discard block | ||
| 220 | 220 | $schema_route_data = $data_for_multiple_endpoints['schema']; | 
| 221 | 221 | $schema_callback = $schema_route_data['schema_callback']; | 
| 222 | 222 | $callback_args = $schema_route_data['callback_args']; | 
| 223 | -                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) { | |
| 223 | +                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) { | |
| 224 | 224 | return call_user_func_array( | 
| 225 | 225 | $schema_callback, | 
| 226 | 226 | $callback_args | 
| @@ -262,7 +262,7 @@ discard block | ||
| 262 | 262 |      { | 
| 263 | 263 | // delete the saved EE REST API routes | 
| 264 | 264 |          foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) { | 
| 265 | - delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version); | |
| 265 | + delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version); | |
| 266 | 266 | } | 
| 267 | 267 | } | 
| 268 | 268 | |
| @@ -281,7 +281,7 @@ discard block | ||
| 281 | 281 |      { | 
| 282 | 282 | $ee_routes = array(); | 
| 283 | 283 |          foreach (self::versions_served() as $version => $hidden_endpoints) { | 
| 284 | - $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version( | |
| 284 | + $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version( | |
| 285 | 285 | $version, | 
| 286 | 286 | $hidden_endpoints | 
| 287 | 287 | ); | 
| @@ -301,8 +301,8 @@ discard block | ||
| 301 | 301 | */ | 
| 302 | 302 | protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false) | 
| 303 | 303 |      { | 
| 304 | - $ee_routes = get_option(self::saved_routes_option_names . $version, null); | |
| 305 | -        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) { | |
| 304 | + $ee_routes = get_option(self::saved_routes_option_names.$version, null); | |
| 305 | +        if ( ! $ee_routes || EED_Core_Rest_Api::debugMode()) { | |
| 306 | 306 | $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints); | 
| 307 | 307 | } | 
| 308 | 308 | return $ee_routes; | 
| @@ -329,7 +329,7 @@ discard block | ||
| 329 | 329 | $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints) | 
| 330 | 330 | ) | 
| 331 | 331 | ); | 
| 332 | - $option_name = self::saved_routes_option_names . $version; | |
| 332 | + $option_name = self::saved_routes_option_names.$version; | |
| 333 | 333 |          if (get_option($option_name)) { | 
| 334 | 334 | update_option($option_name, $routes, true); | 
| 335 | 335 |          } else { | 
| @@ -374,8 +374,8 @@ discard block | ||
| 374 | 374 |      { | 
| 375 | 375 | $model_routes = array(); | 
| 376 | 376 |          foreach (self::versions_served() as $version => $hidden_endpoint) { | 
| 377 | - $model_routes[ EED_Core_Rest_Api::ee_api_namespace | |
| 378 | - . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint); | |
| 377 | + $model_routes[EED_Core_Rest_Api::ee_api_namespace | |
| 378 | + . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint); | |
| 379 | 379 | } | 
| 380 | 380 | return $model_routes; | 
| 381 | 381 | } | 
| @@ -444,13 +444,13 @@ discard block | ||
| 444 | 444 |          foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) { | 
| 445 | 445 | $model = \EE_Registry::instance()->load_model($model_name); | 
| 446 | 446 | // if this isn't a valid model then let's skip iterate to the next item in the loop. | 
| 447 | -            if (! $model instanceof EEM_Base) { | |
| 447 | +            if ( ! $model instanceof EEM_Base) { | |
| 448 | 448 | continue; | 
| 449 | 449 | } | 
| 450 | 450 | // yes we could just register one route for ALL models, but then they wouldn't show up in the index | 
| 451 | 451 | $plural_model_route = EED_Core_Rest_Api::get_collection_route($model); | 
| 452 | 452 | $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)'); | 
| 453 | - $model_routes[ $plural_model_route ] = array( | |
| 453 | + $model_routes[$plural_model_route] = array( | |
| 454 | 454 | array( | 
| 455 | 455 | 'callback' => array( | 
| 456 | 456 | 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | 
| @@ -461,7 +461,7 @@ discard block | ||
| 461 | 461 | 'hidden_endpoint' => $hidden_endpoint, | 
| 462 | 462 | 'args' => $this->_get_read_query_params($model, $version), | 
| 463 | 463 | '_links' => array( | 
| 464 | - 'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route), | |
| 464 | + 'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route), | |
| 465 | 465 | ), | 
| 466 | 466 | ), | 
| 467 | 467 | 'schema' => array( | 
| @@ -472,7 +472,7 @@ discard block | ||
| 472 | 472 | 'callback_args' => array($version, $model_name), | 
| 473 | 473 | ), | 
| 474 | 474 | ); | 
| 475 | - $model_routes[ $singular_model_route ] = array( | |
| 475 | + $model_routes[$singular_model_route] = array( | |
| 476 | 476 | array( | 
| 477 | 477 | 'callback' => array( | 
| 478 | 478 | 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | 
| @@ -489,7 +489,7 @@ discard block | ||
| 489 | 489 | EED_Core_Rest_Api::should_have_write_endpoints($model), | 
| 490 | 490 | $model | 
| 491 | 491 |              )) { | 
| 492 | - $model_routes[ $plural_model_route ][] = array( | |
| 492 | + $model_routes[$plural_model_route][] = array( | |
| 493 | 493 | 'callback' => array( | 
| 494 | 494 | 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | 
| 495 | 495 | 'handleRequestInsert', | 
| @@ -499,8 +499,8 @@ discard block | ||
| 499 | 499 | 'hidden_endpoint' => $hidden_endpoint, | 
| 500 | 500 | 'args' => $this->_get_write_params($model_name, $model_version_info, true), | 
| 501 | 501 | ); | 
| 502 | - $model_routes[ $singular_model_route ] = array_merge( | |
| 503 | - $model_routes[ $singular_model_route ], | |
| 502 | + $model_routes[$singular_model_route] = array_merge( | |
| 503 | + $model_routes[$singular_model_route], | |
| 504 | 504 | array( | 
| 505 | 505 | array( | 
| 506 | 506 | 'callback' => array( | 
| @@ -531,7 +531,7 @@ discard block | ||
| 531 | 531 | '(?P<id>[^\/]+)', | 
| 532 | 532 | $relation_obj | 
| 533 | 533 | ); | 
| 534 | - $model_routes[ $related_route ] = array( | |
| 534 | + $model_routes[$related_route] = array( | |
| 535 | 535 | array( | 
| 536 | 536 | 'callback' => array( | 
| 537 | 537 | 'EventEspresso\core\libraries\rest_api\controllers\model\Read', | 
| @@ -544,8 +544,8 @@ discard block | ||
| 544 | 544 | ), | 
| 545 | 545 | ); | 
| 546 | 546 | |
| 547 | - $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)'; | |
| 548 | - $model_routes[ $related_write_route ] = array( | |
| 547 | + $related_write_route = $related_route.'/'.'(?P<related_id>[^\/]+)'; | |
| 548 | + $model_routes[$related_write_route] = array( | |
| 549 | 549 | array( | 
| 550 | 550 | 'callback' => array( | 
| 551 | 551 | 'EventEspresso\core\libraries\rest_api\controllers\model\Write', | 
| @@ -598,7 +598,7 @@ discard block | ||
| 598 | 598 | */ | 
| 599 | 599 | public static function get_entity_route($model, $id) | 
| 600 | 600 |      { | 
| 601 | - return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id; | |
| 601 | + return EED_Core_Rest_Api::get_collection_route($model).'/'.$id; | |
| 602 | 602 | } | 
| 603 | 603 | |
| 604 | 604 | |
| @@ -618,7 +618,7 @@ discard block | ||
| 618 | 618 | $relation_obj->get_other_model()->get_this_model_name(), | 
| 619 | 619 | $relation_obj | 
| 620 | 620 | ); | 
| 621 | - return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part; | |
| 621 | + return EED_Core_Rest_Api::get_entity_route($model, $id).'/'.$related_model_name_endpoint_part; | |
| 622 | 622 | } | 
| 623 | 623 | |
| 624 | 624 | |
| @@ -632,7 +632,7 @@ discard block | ||
| 632 | 632 | */ | 
| 633 | 633 | public static function get_versioned_route_to($relative_route, $version = '4.8.36') | 
| 634 | 634 |      { | 
| 635 | - return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route; | |
| 635 | + return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route; | |
| 636 | 636 | } | 
| 637 | 637 | |
| 638 | 638 | |
| @@ -646,7 +646,7 @@ discard block | ||
| 646 | 646 |      { | 
| 647 | 647 | $routes = array(); | 
| 648 | 648 |          foreach (self::versions_served() as $version => $hidden_endpoint) { | 
| 649 | - $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version( | |
| 649 | + $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version( | |
| 650 | 650 | $version, | 
| 651 | 651 | $hidden_endpoint | 
| 652 | 652 | ); | 
| @@ -769,12 +769,12 @@ discard block | ||
| 769 | 769 |      { | 
| 770 | 770 | // if they're related through a HABTM relation, check for any non-FKs | 
| 771 | 771 | $all_relation_settings = $source_model->relation_settings(); | 
| 772 | - $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ]; | |
| 772 | + $relation_settings = $all_relation_settings[$related_model->get_this_model_name()]; | |
| 773 | 773 | $params = array(); | 
| 774 | 774 |          if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) { | 
| 775 | 775 |              foreach ($relation_settings->getNonKeyFields() as $field) { | 
| 776 | 776 | /* @var $field EE_Model_Field_Base */ | 
| 777 | - $params[ $field->get_name() ] = array( | |
| 777 | + $params[$field->get_name()] = array( | |
| 778 | 778 | 'required' => ! $field->is_nullable(), | 
| 779 | 779 | 'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version), | 
| 780 | 780 | 'type' => $field->getSchemaType(), | 
| @@ -799,7 +799,7 @@ discard block | ||
| 799 | 799 |      { | 
| 800 | 800 | $default_orderby = array(); | 
| 801 | 801 |          foreach ($model->get_combined_primary_key_fields() as $key_field) { | 
| 802 | - $default_orderby[ $key_field->get_name() ] = 'ASC'; | |
| 802 | + $default_orderby[$key_field->get_name()] = 'ASC'; | |
| 803 | 803 | } | 
| 804 | 804 | return array_merge( | 
| 805 | 805 | $this->_get_response_selection_query_params($model, $version), | 
| @@ -833,7 +833,7 @@ discard block | ||
| 833 | 833 | 'type' => array( | 
| 834 | 834 | 'object', | 
| 835 | 835 | 'string', | 
| 836 | - ),// because we accept a variety of types, WP core validation and sanitization | |
| 836 | + ), // because we accept a variety of types, WP core validation and sanitization | |
| 837 | 837 | // freaks out. We'll just validate this argument while handling the request | 
| 838 | 838 | 'validate_callback' => null, | 
| 839 | 839 | 'sanitize_callback' => null, | 
| @@ -931,7 +931,7 @@ discard block | ||
| 931 | 931 | $sanitize_callback = null; | 
| 932 | 932 | } | 
| 933 | 933 | $arg_info['sanitize_callback'] = $sanitize_callback; | 
| 934 | - $args_info[ $field_name ] = $arg_info; | |
| 934 | + $args_info[$field_name] = $arg_info; | |
| 935 | 935 |              if ($field_obj instanceof EE_Datetime_Field) { | 
| 936 | 936 | $gmt_arg_info = $arg_info; | 
| 937 | 937 | $gmt_arg_info['description'] = sprintf( | 
| @@ -942,7 +942,7 @@ discard block | ||
| 942 | 942 | $field_obj->get_nicename(), | 
| 943 | 943 | $field_name | 
| 944 | 944 | ); | 
| 945 | - $args_info[ $field_name . '_gmt' ] = $gmt_arg_info; | |
| 945 | + $args_info[$field_name.'_gmt'] = $gmt_arg_info; | |
| 946 | 946 | } | 
| 947 | 947 | } | 
| 948 | 948 | return $args_info; | 
| @@ -965,16 +965,16 @@ discard block | ||
| 965 | 965 | public static function default_sanitize_callback($value, WP_REST_Request $request, $param) | 
| 966 | 966 |      { | 
| 967 | 967 | $attributes = $request->get_attributes(); | 
| 968 | - if (! isset($attributes['args'][ $param ]) | |
| 969 | -            || ! is_array($attributes['args'][ $param ])) { | |
| 968 | + if ( ! isset($attributes['args'][$param]) | |
| 969 | +            || ! is_array($attributes['args'][$param])) { | |
| 970 | 970 | $validation_result = true; | 
| 971 | 971 |          } else { | 
| 972 | - $args = $attributes['args'][ $param ]; | |
| 972 | + $args = $attributes['args'][$param]; | |
| 973 | 973 | if (( | 
| 974 | 974 | $value === '' | 
| 975 | 975 | || $value === null | 
| 976 | 976 | ) | 
| 977 | - && (! isset($args['required']) | |
| 977 | + && ( ! isset($args['required']) | |
| 978 | 978 | || $args['required'] === false | 
| 979 | 979 | ) | 
| 980 | 980 |              ) { | 
| @@ -984,7 +984,7 @@ discard block | ||
| 984 | 984 | && $args['format'] === 'email' | 
| 985 | 985 |              ) { | 
| 986 | 986 | $validation_result = true; | 
| 987 | -                if (! self::_validate_email($value)) { | |
| 987 | +                if ( ! self::_validate_email($value)) { | |
| 988 | 988 | $validation_result = new WP_Error( | 
| 989 | 989 | 'rest_invalid_param', | 
| 990 | 990 | esc_html__( | 
| @@ -1034,7 +1034,7 @@ discard block | ||
| 1034 | 1034 |      { | 
| 1035 | 1035 | $config_routes = array(); | 
| 1036 | 1036 |          foreach (self::versions_served() as $version => $hidden_endpoint) { | 
| 1037 | - $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version( | |
| 1037 | + $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version( | |
| 1038 | 1038 | $version, | 
| 1039 | 1039 | $hidden_endpoint | 
| 1040 | 1040 | ); | 
| @@ -1089,7 +1089,7 @@ discard block | ||
| 1089 | 1089 |      { | 
| 1090 | 1090 | $meta_routes = array(); | 
| 1091 | 1091 |          foreach (self::versions_served() as $version => $hidden_endpoint) { | 
| 1092 | - $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version( | |
| 1092 | + $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version( | |
| 1093 | 1093 | $version, | 
| 1094 | 1094 | $hidden_endpoint | 
| 1095 | 1095 | ); | 
| @@ -1141,7 +1141,7 @@ discard block | ||
| 1141 | 1141 |              foreach ($relative_urls as $resource_name => $endpoints) { | 
| 1142 | 1142 |                  foreach ($endpoints as $key => $endpoint) { | 
| 1143 | 1143 | // skip schema and other route options | 
| 1144 | -                    if (! is_numeric($key)) { | |
| 1144 | +                    if ( ! is_numeric($key)) { | |
| 1145 | 1145 | continue; | 
| 1146 | 1146 | } | 
| 1147 | 1147 | // by default, hide "hidden_endpoint"s, unless the request indicates | 
| @@ -1150,9 +1150,9 @@ discard block | ||
| 1150 | 1150 | if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace) | 
| 1151 | 1151 | || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '') | 
| 1152 | 1152 |                      ) { | 
| 1153 | - $full_route = '/' . ltrim($namespace, '/'); | |
| 1154 | - $full_route .= '/' . ltrim($resource_name, '/'); | |
| 1155 | - unset($route_data[ $full_route ]); | |
| 1153 | + $full_route = '/'.ltrim($namespace, '/'); | |
| 1154 | + $full_route .= '/'.ltrim($resource_name, '/'); | |
| 1155 | + unset($route_data[$full_route]); | |
| 1156 | 1156 | } | 
| 1157 | 1157 | } | 
| 1158 | 1158 | } | 
| @@ -1225,19 +1225,19 @@ discard block | ||
| 1225 | 1225 | // if it's not above the current core version, and it's compatible with the current version of core | 
| 1226 | 1226 |              if ($key_versioned_endpoint === $latest_version) { | 
| 1227 | 1227 | // don't hide the latest version in the index | 
| 1228 | - $versions_served[ $key_versioned_endpoint ] = false; | |
| 1228 | + $versions_served[$key_versioned_endpoint] = false; | |
| 1229 | 1229 | } elseif ($key_versioned_endpoint >= $lowest_compatible_version | 
| 1230 | 1230 | && $key_versioned_endpoint < EED_Core_Rest_Api::core_version() | 
| 1231 | 1231 |              ) { | 
| 1232 | 1232 | // include, but hide, previous versions which are still supported | 
| 1233 | - $versions_served[ $key_versioned_endpoint ] = true; | |
| 1233 | + $versions_served[$key_versioned_endpoint] = true; | |
| 1234 | 1234 | } elseif (apply_filters( | 
| 1235 | 1235 | 'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions', | 
| 1236 | 1236 | false, | 
| 1237 | 1237 | $possibly_served_versions | 
| 1238 | 1238 |              )) { | 
| 1239 | 1239 | // if a version is no longer supported, don't include it in index or list of versions served | 
| 1240 | - $versions_served[ $key_versioned_endpoint ] = true; | |
| 1240 | + $versions_served[$key_versioned_endpoint] = true; | |
| 1241 | 1241 | } | 
| 1242 | 1242 | } | 
| 1243 | 1243 | return $versions_served; | 
| @@ -1295,7 +1295,7 @@ discard block | ||
| 1295 | 1295 | $model_names = self::model_names_with_plural_routes($version); | 
| 1296 | 1296 | $collection_routes = array(); | 
| 1297 | 1297 |          foreach ($model_names as $model_name => $model_class_name) { | 
| 1298 | - $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/' | |
| 1298 | + $collection_routes[strtolower($model_name)] = '/'.self::ee_api_namespace.$version.'/' | |
| 1299 | 1299 | . EEH_Inflector::pluralize_and_lower($model_name); | 
| 1300 | 1300 | } | 
| 1301 | 1301 | return $collection_routes; | 
| @@ -1316,9 +1316,9 @@ discard block | ||
| 1316 | 1316 | $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields(); | 
| 1317 | 1317 |              foreach ($primary_keys as $primary_key_name => $primary_key_field) { | 
| 1318 | 1318 |                  if (count($primary_keys) > 1) { | 
| 1319 | - $primary_key_items[ strtolower($model_name) ][] = $primary_key_name; | |
| 1319 | + $primary_key_items[strtolower($model_name)][] = $primary_key_name; | |
| 1320 | 1320 |                  } else { | 
| 1321 | - $primary_key_items[ strtolower($model_name) ] = $primary_key_name; | |
| 1321 | + $primary_key_items[strtolower($model_name)] = $primary_key_name; | |
| 1322 | 1322 | } | 
| 1323 | 1323 | } | 
| 1324 | 1324 | } | 
| @@ -18,95 +18,95 @@ | ||
| 18 | 18 | class Base extends Controller_Base | 
| 19 | 19 |  { | 
| 20 | 20 | |
| 21 | - /** | |
| 22 | - * Holds reference to the model version info, which knows the requested version | |
| 23 | - * | |
| 24 | - * @var ModelVersionInfo | |
| 25 | - */ | |
| 26 | - protected $model_version_info; | |
| 21 | + /** | |
| 22 | + * Holds reference to the model version info, which knows the requested version | |
| 23 | + * | |
| 24 | + * @var ModelVersionInfo | |
| 25 | + */ | |
| 26 | + protected $model_version_info; | |
| 27 | 27 | |
| 28 | 28 | |
| 29 | 29 | |
| 30 | - /** | |
| 31 | - * Sets the version the user requested | |
| 32 | - * | |
| 33 | - * @param string $version eg '4.8' | |
| 34 | - */ | |
| 35 | - public function setRequestedVersion($version) | |
| 36 | -    { | |
| 37 | - parent::setRequestedVersion($version); | |
| 38 | - $this->model_version_info = new ModelVersionInfo($version); | |
| 39 | - } | |
| 30 | + /** | |
| 31 | + * Sets the version the user requested | |
| 32 | + * | |
| 33 | + * @param string $version eg '4.8' | |
| 34 | + */ | |
| 35 | + public function setRequestedVersion($version) | |
| 36 | +	{ | |
| 37 | + parent::setRequestedVersion($version); | |
| 38 | + $this->model_version_info = new ModelVersionInfo($version); | |
| 39 | + } | |
| 40 | 40 | |
| 41 | 41 | |
| 42 | 42 | |
| 43 | - /** | |
| 44 | - * Gets the object that should be used for getting any info from the models, | |
| 45 | - * because it's takes the requested and current core version into account | |
| 46 | - * | |
| 47 | - * @return \EventEspresso\core\libraries\rest_api\ModelVersionInfo | |
| 48 | - * @throws EE_Error | |
| 49 | - */ | |
| 50 | - public function getModelVersionInfo() | |
| 51 | -    { | |
| 52 | -        if (! $this->model_version_info) { | |
| 53 | - throw new EE_Error( | |
| 54 | - sprintf( | |
| 55 | - __( | |
| 56 | - 'Cannot use model version info before setting the requested version in the controller', | |
| 57 | - 'event_espresso' | |
| 58 | - ) | |
| 59 | - ) | |
| 60 | - ); | |
| 61 | - } | |
| 62 | - return $this->model_version_info; | |
| 63 | - } | |
| 43 | + /** | |
| 44 | + * Gets the object that should be used for getting any info from the models, | |
| 45 | + * because it's takes the requested and current core version into account | |
| 46 | + * | |
| 47 | + * @return \EventEspresso\core\libraries\rest_api\ModelVersionInfo | |
| 48 | + * @throws EE_Error | |
| 49 | + */ | |
| 50 | + public function getModelVersionInfo() | |
| 51 | +	{ | |
| 52 | +		if (! $this->model_version_info) { | |
| 53 | + throw new EE_Error( | |
| 54 | + sprintf( | |
| 55 | + __( | |
| 56 | + 'Cannot use model version info before setting the requested version in the controller', | |
| 57 | + 'event_espresso' | |
| 58 | + ) | |
| 59 | + ) | |
| 60 | + ); | |
| 61 | + } | |
| 62 | + return $this->model_version_info; | |
| 63 | + } | |
| 64 | 64 | |
| 65 | 65 | |
| 66 | 66 | |
| 67 | - /** | |
| 68 | - * Determines if $object is of one of the classes of $classes. Similar to | |
| 69 | - * in_array(), except this checks if $object is a subclass of the classnames provided | |
| 70 | - * in $classnames | |
| 71 | - * | |
| 72 | - * @param object $object | |
| 73 | - * @param array $classnames | |
| 74 | - * @return boolean | |
| 75 | - */ | |
| 76 | - public function isSubclassOfOne($object, $classnames) | |
| 77 | -    { | |
| 78 | -        foreach ($classnames as $classname) { | |
| 79 | -            if (is_a($object, $classname)) { | |
| 80 | - return true; | |
| 81 | - } | |
| 82 | - } | |
| 83 | - return false; | |
| 84 | - } | |
| 67 | + /** | |
| 68 | + * Determines if $object is of one of the classes of $classes. Similar to | |
| 69 | + * in_array(), except this checks if $object is a subclass of the classnames provided | |
| 70 | + * in $classnames | |
| 71 | + * | |
| 72 | + * @param object $object | |
| 73 | + * @param array $classnames | |
| 74 | + * @return boolean | |
| 75 | + */ | |
| 76 | + public function isSubclassOfOne($object, $classnames) | |
| 77 | +	{ | |
| 78 | +		foreach ($classnames as $classname) { | |
| 79 | +			if (is_a($object, $classname)) { | |
| 80 | + return true; | |
| 81 | + } | |
| 82 | + } | |
| 83 | + return false; | |
| 84 | + } | |
| 85 | 85 | |
| 86 | - /** | |
| 87 | - * Verifies the model name provided was valid. If so, returns the model (as an object). Otherwise, throws an | |
| 88 | - * exception. Must be called after `setRequestedVersion()`. | |
| 89 | - * @since $VID:$ | |
| 90 | - * @param $model_name | |
| 91 | - * @return EEM_Base | |
| 92 | - * @throws EE_Error | |
| 93 | - * @throws RestException | |
| 94 | - */ | |
| 95 | - protected function validateModel($model_name) | |
| 96 | -    { | |
| 97 | -        if (! $this->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 98 | - throw new RestException( | |
| 99 | - 'endpoint_parsing_error', | |
| 100 | - sprintf( | |
| 101 | - __( | |
| 102 | - 'There is no model for endpoint %s. Please contact event espresso support', | |
| 103 | - 'event_espresso' | |
| 104 | - ), | |
| 105 | - $model_name | |
| 106 | - ) | |
| 107 | - ); | |
| 108 | - } | |
| 109 | - return $this->getModelVersionInfo()->loadModel($model_name); | |
| 110 | - } | |
| 86 | + /** | |
| 87 | + * Verifies the model name provided was valid. If so, returns the model (as an object). Otherwise, throws an | |
| 88 | + * exception. Must be called after `setRequestedVersion()`. | |
| 89 | + * @since $VID:$ | |
| 90 | + * @param $model_name | |
| 91 | + * @return EEM_Base | |
| 92 | + * @throws EE_Error | |
| 93 | + * @throws RestException | |
| 94 | + */ | |
| 95 | + protected function validateModel($model_name) | |
| 96 | +	{ | |
| 97 | +		if (! $this->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 98 | + throw new RestException( | |
| 99 | + 'endpoint_parsing_error', | |
| 100 | + sprintf( | |
| 101 | + __( | |
| 102 | + 'There is no model for endpoint %s. Please contact event espresso support', | |
| 103 | + 'event_espresso' | |
| 104 | + ), | |
| 105 | + $model_name | |
| 106 | + ) | |
| 107 | + ); | |
| 108 | + } | |
| 109 | + return $this->getModelVersionInfo()->loadModel($model_name); | |
| 110 | + } | |
| 111 | 111 | } | 
| 112 | 112 | // End of file Base.php | 
| @@ -49,7 +49,7 @@ discard block | ||
| 49 | 49 | */ | 
| 50 | 50 | public function getModelVersionInfo() | 
| 51 | 51 |      { | 
| 52 | -        if (! $this->model_version_info) { | |
| 52 | +        if ( ! $this->model_version_info) { | |
| 53 | 53 | throw new EE_Error( | 
| 54 | 54 | sprintf( | 
| 55 | 55 | __( | 
| @@ -94,7 +94,7 @@ discard block | ||
| 94 | 94 | */ | 
| 95 | 95 | protected function validateModel($model_name) | 
| 96 | 96 |      { | 
| 97 | -        if (! $this->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 97 | +        if ( ! $this->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 98 | 98 | throw new RestException( | 
| 99 | 99 | 'endpoint_parsing_error', | 
| 100 | 100 | sprintf( | 
| @@ -13,3144 +13,3144 @@ | ||
| 13 | 13 | abstract class EE_Base_Class | 
| 14 | 14 |  { | 
| 15 | 15 | |
| 16 | - /** | |
| 17 | - * This is an array of the original properties and values provided during construction | |
| 18 | - * of this model object. (keys are model field names, values are their values). | |
| 19 | - * This list is important to remember so that when we are merging data from the db, we know | |
| 20 | - * which values to override and which to not override. | |
| 21 | - * | |
| 22 | - * @var array | |
| 23 | - */ | |
| 24 | - protected $_props_n_values_provided_in_constructor; | |
| 25 | - | |
| 26 | - /** | |
| 27 | - * Timezone | |
| 28 | - * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in. | |
| 29 | - * This can also be used before a get to set what timezone you want strings coming out of the object to be in. NOT | |
| 30 | - * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have | |
| 31 | - * access to it. | |
| 32 | - * | |
| 33 | - * @var string | |
| 34 | - */ | |
| 35 | - protected $_timezone; | |
| 36 | - | |
| 37 | - /** | |
| 38 | - * date format | |
| 39 | - * pattern or format for displaying dates | |
| 40 | - * | |
| 41 | - * @var string $_dt_frmt | |
| 42 | - */ | |
| 43 | - protected $_dt_frmt; | |
| 44 | - | |
| 45 | - /** | |
| 46 | - * time format | |
| 47 | - * pattern or format for displaying time | |
| 48 | - * | |
| 49 | - * @var string $_tm_frmt | |
| 50 | - */ | |
| 51 | - protected $_tm_frmt; | |
| 52 | - | |
| 53 | - /** | |
| 54 | - * This property is for holding a cached array of object properties indexed by property name as the key. | |
| 55 | - * The purpose of this is for setting a cache on properties that may have calculated values after a | |
| 56 | - * prepare_for_get. That way the cache can be checked first and the calculated property returned instead of having | |
| 57 | - * to recalculate. Used by _set_cached_property() and _get_cached_property() methods. | |
| 58 | - * | |
| 59 | - * @var array | |
| 60 | - */ | |
| 61 | - protected $_cached_properties = array(); | |
| 62 | - | |
| 63 | - /** | |
| 64 | - * An array containing keys of the related model, and values are either an array of related mode objects or a | |
| 65 | - * single | |
| 66 | - * related model object. see the model's _model_relations. The keys should match those specified. And if the | |
| 67 | - * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object, | |
| 68 | - * all others have an array) | |
| 69 | - * | |
| 70 | - * @var array | |
| 71 | - */ | |
| 72 | - protected $_model_relations = array(); | |
| 73 | - | |
| 74 | - /** | |
| 75 | - * Array where keys are field names (see the model's _fields property) and values are their values. To see what | |
| 76 | - * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods) | |
| 77 | - * | |
| 78 | - * @var array | |
| 79 | - */ | |
| 80 | - protected $_fields = array(); | |
| 81 | - | |
| 82 | - /** | |
| 83 | - * @var boolean indicating whether or not this model object is intended to ever be saved | |
| 84 | - * For example, we might create model objects intended to only be used for the duration | |
| 85 | - * of this request and to be thrown away, and if they were accidentally saved | |
| 86 | - * it would be a bug. | |
| 87 | - */ | |
| 88 | - protected $_allow_persist = true; | |
| 89 | - | |
| 90 | - /** | |
| 91 | - * @var boolean indicating whether or not this model object's properties have changed since construction | |
| 92 | - */ | |
| 93 | - protected $_has_changes = false; | |
| 94 | - | |
| 95 | - /** | |
| 96 | - * @var EEM_Base | |
| 97 | - */ | |
| 98 | - protected $_model; | |
| 99 | - | |
| 100 | - /** | |
| 101 | - * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose | |
| 102 | - * for these values is for retrieval of the results, they are not further queryable and they are not persisted to | |
| 103 | - * the db. They also do not automatically update if there are any changes to the data that produced their results. | |
| 104 | - * The format is a simple array of field_alias => field_value. So for instance if a custom select was something | |
| 105 | - * like, "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this | |
| 106 | - * array as: | |
| 107 | - * array( | |
| 108 | - * 'Registration_Count' => 24 | |
| 109 | - * ); | |
| 110 | - * Note: if the custom select configuration for the query included a data type, the value will be in the data type | |
| 111 | - * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more | |
| 112 | - * info) | |
| 113 | - * | |
| 114 | - * @var array | |
| 115 | - */ | |
| 116 | - protected $custom_selection_results = array(); | |
| 117 | - | |
| 118 | - | |
| 119 | - /** | |
| 120 | - * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children | |
| 121 | - * play nice | |
| 122 | - * | |
| 123 | - * @param array $fieldValues where each key is a field (ie, array key in the 2nd | |
| 124 | - * layer of the model's _fields array, (eg, EVT_ID, | |
| 125 | - * TXN_amount, QST_name, etc) and values are their values | |
| 126 | - * @param boolean $bydb a flag for setting if the class is instantiated by the | |
| 127 | - * corresponding db model or not. | |
| 128 | - * @param string $timezone indicate what timezone you want any datetime fields to | |
| 129 | - * be in when instantiating a EE_Base_Class object. | |
| 130 | - * @param array $date_formats An array of date formats to set on construct where first | |
| 131 | - * value is the date_format and second value is the time | |
| 132 | - * format. | |
| 133 | - * @throws InvalidArgumentException | |
| 134 | - * @throws InvalidInterfaceException | |
| 135 | - * @throws InvalidDataTypeException | |
| 136 | - * @throws EE_Error | |
| 137 | - * @throws ReflectionException | |
| 138 | - */ | |
| 139 | - protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array()) | |
| 140 | -    { | |
| 141 | - $className = get_class($this); | |
| 142 | -        do_action("AHEE__{$className}__construct", $this, $fieldValues); | |
| 143 | - $model = $this->get_model(); | |
| 144 | - $model_fields = $model->field_settings(false); | |
| 145 | - // ensure $fieldValues is an array | |
| 146 | - $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues); | |
| 147 | - // verify client code has not passed any invalid field names | |
| 148 | -        foreach ($fieldValues as $field_name => $field_value) { | |
| 149 | -            if (! isset($model_fields[ $field_name ])) { | |
| 150 | - throw new EE_Error( | |
| 151 | - sprintf( | |
| 152 | - esc_html__( | |
| 153 | - 'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s', | |
| 154 | - 'event_espresso' | |
| 155 | - ), | |
| 156 | - $field_name, | |
| 157 | - get_class($this), | |
| 158 | -                        implode(', ', array_keys($model_fields)) | |
| 159 | - ) | |
| 160 | - ); | |
| 161 | - } | |
| 162 | - } | |
| 163 | - $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone); | |
| 164 | -        if (! empty($date_formats) && is_array($date_formats)) { | |
| 165 | - list($this->_dt_frmt, $this->_tm_frmt) = $date_formats; | |
| 166 | -        } else { | |
| 167 | - // set default formats for date and time | |
| 168 | -            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d'); | |
| 169 | -            $this->_tm_frmt = (string) get_option('time_format', 'g:i a'); | |
| 170 | - } | |
| 171 | - // if db model is instantiating | |
| 172 | -        if ($bydb) { | |
| 173 | - // client code has indicated these field values are from the database | |
| 174 | -            foreach ($model_fields as $fieldName => $field) { | |
| 175 | - $this->set_from_db( | |
| 176 | - $fieldName, | |
| 177 | - isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null | |
| 178 | - ); | |
| 179 | - } | |
| 180 | -        } else { | |
| 181 | - // we're constructing a brand | |
| 182 | - // new instance of the model object. Generally, this means we'll need to do more field validation | |
| 183 | -            foreach ($model_fields as $fieldName => $field) { | |
| 184 | - $this->set( | |
| 185 | - $fieldName, | |
| 186 | - isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null, | |
| 187 | - true | |
| 188 | - ); | |
| 189 | - } | |
| 190 | - } | |
| 191 | - // remember what values were passed to this constructor | |
| 192 | - $this->_props_n_values_provided_in_constructor = $fieldValues; | |
| 193 | - // remember in entity mapper | |
| 194 | -        if (! $bydb && $model->has_primary_key_field() && $this->ID()) { | |
| 195 | - $model->add_to_entity_map($this); | |
| 196 | - } | |
| 197 | - // setup all the relations | |
| 198 | -        foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 199 | -            if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 200 | - $this->_model_relations[ $relation_name ] = null; | |
| 201 | -            } else { | |
| 202 | - $this->_model_relations[ $relation_name ] = array(); | |
| 203 | - } | |
| 204 | - } | |
| 205 | - /** | |
| 206 | - * Action done at the end of each model object construction | |
| 207 | - * | |
| 208 | - * @param EE_Base_Class $this the model object just created | |
| 209 | - */ | |
| 210 | -        do_action('AHEE__EE_Base_Class__construct__finished', $this); | |
| 211 | - } | |
| 212 | - | |
| 213 | - | |
| 214 | - /** | |
| 215 | - * Gets whether or not this model object is allowed to persist/be saved to the database. | |
| 216 | - * | |
| 217 | - * @return boolean | |
| 218 | - */ | |
| 219 | - public function allow_persist() | |
| 220 | -    { | |
| 221 | - return $this->_allow_persist; | |
| 222 | - } | |
| 223 | - | |
| 224 | - | |
| 225 | - /** | |
| 226 | - * Sets whether or not this model object should be allowed to be saved to the DB. | |
| 227 | - * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless | |
| 228 | - * you got new information that somehow made you change your mind. | |
| 229 | - * | |
| 230 | - * @param boolean $allow_persist | |
| 231 | - * @return boolean | |
| 232 | - */ | |
| 233 | - public function set_allow_persist($allow_persist) | |
| 234 | -    { | |
| 235 | - return $this->_allow_persist = $allow_persist; | |
| 236 | - } | |
| 237 | - | |
| 238 | - | |
| 239 | - /** | |
| 240 | - * Gets the field's original value when this object was constructed during this request. | |
| 241 | - * This can be helpful when determining if a model object has changed or not | |
| 242 | - * | |
| 243 | - * @param string $field_name | |
| 244 | - * @return mixed|null | |
| 245 | - * @throws ReflectionException | |
| 246 | - * @throws InvalidArgumentException | |
| 247 | - * @throws InvalidInterfaceException | |
| 248 | - * @throws InvalidDataTypeException | |
| 249 | - * @throws EE_Error | |
| 250 | - */ | |
| 251 | - public function get_original($field_name) | |
| 252 | -    { | |
| 253 | - if (isset($this->_props_n_values_provided_in_constructor[ $field_name ]) | |
| 254 | - && $field_settings = $this->get_model()->field_settings_for($field_name) | |
| 255 | -        ) { | |
| 256 | - return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]); | |
| 257 | - } | |
| 258 | - return null; | |
| 259 | - } | |
| 260 | - | |
| 261 | - | |
| 262 | - /** | |
| 263 | - * @param EE_Base_Class $obj | |
| 264 | - * @return string | |
| 265 | - */ | |
| 266 | - public function get_class($obj) | |
| 267 | -    { | |
| 268 | - return get_class($obj); | |
| 269 | - } | |
| 270 | - | |
| 271 | - | |
| 272 | - /** | |
| 273 | - * Overrides parent because parent expects old models. | |
| 274 | - * This also doesn't do any validation, and won't work for serialized arrays | |
| 275 | - * | |
| 276 | - * @param string $field_name | |
| 277 | - * @param mixed $field_value | |
| 278 | - * @param bool $use_default | |
| 279 | - * @throws InvalidArgumentException | |
| 280 | - * @throws InvalidInterfaceException | |
| 281 | - * @throws InvalidDataTypeException | |
| 282 | - * @throws EE_Error | |
| 283 | - * @throws ReflectionException | |
| 284 | - * @throws ReflectionException | |
| 285 | - * @throws ReflectionException | |
| 286 | - */ | |
| 287 | - public function set($field_name, $field_value, $use_default = false) | |
| 288 | -    { | |
| 289 | - // if not using default and nothing has changed, and object has already been setup (has ID), | |
| 290 | - // then don't do anything | |
| 291 | - if (! $use_default | |
| 292 | - && $this->_fields[ $field_name ] === $field_value | |
| 293 | - && $this->ID() | |
| 294 | -        ) { | |
| 295 | - return; | |
| 296 | - } | |
| 297 | - $model = $this->get_model(); | |
| 298 | - $this->_has_changes = true; | |
| 299 | - $field_obj = $model->field_settings_for($field_name); | |
| 300 | -        if ($field_obj instanceof EE_Model_Field_Base) { | |
| 301 | -            // if ( method_exists( $field_obj, 'set_timezone' )) { | |
| 302 | -            if ($field_obj instanceof EE_Datetime_Field) { | |
| 303 | - $field_obj->set_timezone($this->_timezone); | |
| 304 | - $field_obj->set_date_format($this->_dt_frmt); | |
| 305 | - $field_obj->set_time_format($this->_tm_frmt); | |
| 306 | - } | |
| 307 | - $holder_of_value = $field_obj->prepare_for_set($field_value); | |
| 308 | - // should the value be null? | |
| 309 | -            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) { | |
| 310 | - $this->_fields[ $field_name ] = $field_obj->get_default_value(); | |
| 311 | - /** | |
| 312 | - * To save having to refactor all the models, if a default value is used for a | |
| 313 | - * EE_Datetime_Field, and that value is not null nor is it a DateTime | |
| 314 | - * object. Then let's do a set again to ensure that it becomes a DateTime | |
| 315 | - * object. | |
| 316 | - * | |
| 317 | - * @since 4.6.10+ | |
| 318 | - */ | |
| 319 | - if ($field_obj instanceof EE_Datetime_Field | |
| 320 | - && $this->_fields[ $field_name ] !== null | |
| 321 | - && ! $this->_fields[ $field_name ] instanceof DateTime | |
| 322 | -                ) { | |
| 323 | - empty($this->_fields[ $field_name ]) | |
| 324 | - ? $this->set($field_name, time()) | |
| 325 | - : $this->set($field_name, $this->_fields[ $field_name ]); | |
| 326 | - } | |
| 327 | -            } else { | |
| 328 | - $this->_fields[ $field_name ] = $holder_of_value; | |
| 329 | - } | |
| 330 | - // if we're not in the constructor... | |
| 331 | - // now check if what we set was a primary key | |
| 332 | - if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor | |
| 333 | - $this->_props_n_values_provided_in_constructor | |
| 334 | - && $field_value | |
| 335 | - && $field_name === $model->primary_key_name() | |
| 336 | -            ) { | |
| 337 | - // if so, we want all this object's fields to be filled either with | |
| 338 | - // what we've explicitly set on this model | |
| 339 | - // or what we have in the db | |
| 340 | - // echo "setting primary key!"; | |
| 341 | - $fields_on_model = self::_get_model(get_class($this))->field_settings(); | |
| 342 | - $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value); | |
| 343 | -                foreach ($fields_on_model as $field_obj) { | |
| 344 | - if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor) | |
| 345 | - && $field_obj->get_name() !== $field_name | |
| 346 | -                    ) { | |
| 347 | - $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name())); | |
| 348 | - } | |
| 349 | - } | |
| 350 | - // oh this model object has an ID? well make sure its in the entity mapper | |
| 351 | - $model->add_to_entity_map($this); | |
| 352 | - } | |
| 353 | - // let's unset any cache for this field_name from the $_cached_properties property. | |
| 354 | - $this->_clear_cached_property($field_name); | |
| 355 | -        } else { | |
| 356 | - throw new EE_Error( | |
| 357 | - sprintf( | |
| 358 | - esc_html__( | |
| 359 | - 'A valid EE_Model_Field_Base could not be found for the given field name: %s', | |
| 360 | - 'event_espresso' | |
| 361 | - ), | |
| 362 | - $field_name | |
| 363 | - ) | |
| 364 | - ); | |
| 365 | - } | |
| 366 | - } | |
| 367 | - | |
| 368 | - | |
| 369 | - /** | |
| 370 | - * Set custom select values for model. | |
| 371 | - * | |
| 372 | - * @param array $custom_select_values | |
| 373 | - */ | |
| 374 | - public function setCustomSelectsValues(array $custom_select_values) | |
| 375 | -    { | |
| 376 | - $this->custom_selection_results = $custom_select_values; | |
| 377 | - } | |
| 378 | - | |
| 379 | - | |
| 380 | - /** | |
| 381 | - * Returns the custom select value for the provided alias if its set. | |
| 382 | - * If not set, returns null. | |
| 383 | - * | |
| 384 | - * @param string $alias | |
| 385 | - * @return string|int|float|null | |
| 386 | - */ | |
| 387 | - public function getCustomSelect($alias) | |
| 388 | -    { | |
| 389 | - return isset($this->custom_selection_results[ $alias ]) | |
| 390 | - ? $this->custom_selection_results[ $alias ] | |
| 391 | - : null; | |
| 392 | - } | |
| 393 | - | |
| 394 | - | |
| 395 | - /** | |
| 396 | - * This sets the field value on the db column if it exists for the given $column_name or | |
| 397 | - * saves it to EE_Extra_Meta if the given $column_name does not match a db column. | |
| 398 | - * | |
| 399 | - * @see EE_message::get_column_value for related documentation on the necessity of this method. | |
| 400 | - * @param string $field_name Must be the exact column name. | |
| 401 | - * @param mixed $field_value The value to set. | |
| 402 | - * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs. | |
| 403 | - * @throws InvalidArgumentException | |
| 404 | - * @throws InvalidInterfaceException | |
| 405 | - * @throws InvalidDataTypeException | |
| 406 | - * @throws EE_Error | |
| 407 | - * @throws ReflectionException | |
| 408 | - */ | |
| 409 | - public function set_field_or_extra_meta($field_name, $field_value) | |
| 410 | -    { | |
| 411 | -        if ($this->get_model()->has_field($field_name)) { | |
| 412 | - $this->set($field_name, $field_value); | |
| 413 | - return true; | |
| 414 | - } | |
| 415 | - // ensure this object is saved first so that extra meta can be properly related. | |
| 416 | - $this->save(); | |
| 417 | - return $this->update_extra_meta($field_name, $field_value); | |
| 418 | - } | |
| 419 | - | |
| 420 | - | |
| 421 | - /** | |
| 422 | - * This retrieves the value of the db column set on this class or if that's not present | |
| 423 | - * it will attempt to retrieve from extra_meta if found. | |
| 424 | - * Example Usage: | |
| 425 | - * Via EE_Message child class: | |
| 426 | - * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to", | |
| 427 | - * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may | |
| 428 | - * also have additional main fields specific to the messenger. The system accommodates those extra | |
| 429 | - * fields through the EE_Extra_Meta table. This method allows for EE_messengers to retrieve the | |
| 430 | - * value for those extra fields dynamically via the EE_message object. | |
| 431 | - * | |
| 432 | - * @param string $field_name expecting the fully qualified field name. | |
| 433 | - * @return mixed|null value for the field if found. null if not found. | |
| 434 | - * @throws ReflectionException | |
| 435 | - * @throws InvalidArgumentException | |
| 436 | - * @throws InvalidInterfaceException | |
| 437 | - * @throws InvalidDataTypeException | |
| 438 | - * @throws EE_Error | |
| 439 | - */ | |
| 440 | - public function get_field_or_extra_meta($field_name) | |
| 441 | -    { | |
| 442 | -        if ($this->get_model()->has_field($field_name)) { | |
| 443 | - $column_value = $this->get($field_name); | |
| 444 | -        } else { | |
| 445 | - // This isn't a column in the main table, let's see if it is in the extra meta. | |
| 446 | - $column_value = $this->get_extra_meta($field_name, true, null); | |
| 447 | - } | |
| 448 | - return $column_value; | |
| 449 | - } | |
| 450 | - | |
| 451 | - | |
| 452 | - /** | |
| 453 | - * See $_timezone property for description of what the timezone property is for. This SETS the timezone internally | |
| 454 | - * for being able to reference what timezone we are running conversions on when converting TO the internal timezone | |
| 455 | - * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is | |
| 456 | - * available to all child classes that may be using the EE_Datetime_Field for a field data type. | |
| 457 | - * | |
| 458 | - * @access public | |
| 459 | - * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php | |
| 460 | - * @return void | |
| 461 | - * @throws InvalidArgumentException | |
| 462 | - * @throws InvalidInterfaceException | |
| 463 | - * @throws InvalidDataTypeException | |
| 464 | - * @throws EE_Error | |
| 465 | - * @throws ReflectionException | |
| 466 | - */ | |
| 467 | - public function set_timezone($timezone = '') | |
| 468 | -    { | |
| 469 | - $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone); | |
| 470 | - // make sure we clear all cached properties because they won't be relevant now | |
| 471 | - $this->_clear_cached_properties(); | |
| 472 | - // make sure we update field settings and the date for all EE_Datetime_Fields | |
| 473 | - $model_fields = $this->get_model()->field_settings(false); | |
| 474 | -        foreach ($model_fields as $field_name => $field_obj) { | |
| 475 | -            if ($field_obj instanceof EE_Datetime_Field) { | |
| 476 | - $field_obj->set_timezone($this->_timezone); | |
| 477 | -                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) { | |
| 478 | - EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone)); | |
| 479 | - } | |
| 480 | - } | |
| 481 | - } | |
| 482 | - } | |
| 483 | - | |
| 484 | - | |
| 485 | - /** | |
| 486 | - * This just returns whatever is set for the current timezone. | |
| 487 | - * | |
| 488 | - * @access public | |
| 489 | - * @return string timezone string | |
| 490 | - */ | |
| 491 | - public function get_timezone() | |
| 492 | -    { | |
| 493 | - return $this->_timezone; | |
| 494 | - } | |
| 495 | - | |
| 496 | - | |
| 497 | - /** | |
| 498 | - * This sets the internal date format to what is sent in to be used as the new default for the class | |
| 499 | - * internally instead of wp set date format options | |
| 500 | - * | |
| 501 | - * @since 4.6 | |
| 502 | - * @param string $format should be a format recognizable by PHP date() functions. | |
| 503 | - */ | |
| 504 | - public function set_date_format($format) | |
| 505 | -    { | |
| 506 | - $this->_dt_frmt = $format; | |
| 507 | - // clear cached_properties because they won't be relevant now. | |
| 508 | - $this->_clear_cached_properties(); | |
| 509 | - } | |
| 510 | - | |
| 511 | - | |
| 512 | - /** | |
| 513 | - * This sets the internal time format string to what is sent in to be used as the new default for the | |
| 514 | - * class internally instead of wp set time format options. | |
| 515 | - * | |
| 516 | - * @since 4.6 | |
| 517 | - * @param string $format should be a format recognizable by PHP date() functions. | |
| 518 | - */ | |
| 519 | - public function set_time_format($format) | |
| 520 | -    { | |
| 521 | - $this->_tm_frmt = $format; | |
| 522 | - // clear cached_properties because they won't be relevant now. | |
| 523 | - $this->_clear_cached_properties(); | |
| 524 | - } | |
| 525 | - | |
| 526 | - | |
| 527 | - /** | |
| 528 | - * This returns the current internal set format for the date and time formats. | |
| 529 | - * | |
| 530 | - * @param bool $full if true (default), then return the full format. Otherwise will return an array | |
| 531 | - * where the first value is the date format and the second value is the time format. | |
| 532 | - * @return mixed string|array | |
| 533 | - */ | |
| 534 | - public function get_format($full = true) | |
| 535 | -    { | |
| 536 | - return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt); | |
| 537 | - } | |
| 538 | - | |
| 539 | - | |
| 540 | - /** | |
| 541 | - * cache | |
| 542 | - * stores the passed model object on the current model object. | |
| 543 | - * In certain circumstances, we can use this cached model object instead of querying for another one entirely. | |
| 544 | - * | |
| 545 | - * @param string $relationName one of the keys in the _model_relations array on the model. Eg | |
| 546 | - * 'Registration' associated with this model object | |
| 547 | - * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction, | |
| 548 | - * that could be a payment or a registration) | |
| 549 | - * @param null $cache_id a string or number that will be used as the key for any Belongs_To_Many | |
| 550 | - * items which will be stored in an array on this object | |
| 551 | - * @throws ReflectionException | |
| 552 | - * @throws InvalidArgumentException | |
| 553 | - * @throws InvalidInterfaceException | |
| 554 | - * @throws InvalidDataTypeException | |
| 555 | - * @throws EE_Error | |
| 556 | - * @return mixed index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one | |
| 557 | - * related thing, no array) | |
| 558 | - */ | |
| 559 | - public function cache($relationName = '', $object_to_cache = null, $cache_id = null) | |
| 560 | -    { | |
| 561 | - // its entirely possible that there IS no related object yet in which case there is nothing to cache. | |
| 562 | -        if (! $object_to_cache instanceof EE_Base_Class) { | |
| 563 | - return false; | |
| 564 | - } | |
| 565 | - // also get "how" the object is related, or throw an error | |
| 566 | -        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) { | |
| 567 | - throw new EE_Error( | |
| 568 | - sprintf( | |
| 569 | -                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'), | |
| 570 | - $relationName, | |
| 571 | - get_class($this) | |
| 572 | - ) | |
| 573 | - ); | |
| 574 | - } | |
| 575 | - // how many things are related ? | |
| 576 | -        if ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 577 | - // if it's a "belongs to" relationship, then there's only one related model object | |
| 578 | - // eg, if this is a registration, there's only 1 attendee for it | |
| 579 | - // so for these model objects just set it to be cached | |
| 580 | - $this->_model_relations[ $relationName ] = $object_to_cache; | |
| 581 | - $return = true; | |
| 582 | -        } else { | |
| 583 | - // otherwise, this is the "many" side of a one to many relationship, | |
| 584 | - // so we'll add the object to the array of related objects for that type. | |
| 585 | - // eg: if this is an event, there are many registrations for that event, | |
| 586 | - // so we cache the registrations in an array | |
| 587 | -            if (! is_array($this->_model_relations[ $relationName ])) { | |
| 588 | - // if for some reason, the cached item is a model object, | |
| 589 | - // then stick that in the array, otherwise start with an empty array | |
| 590 | - $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ] | |
| 591 | - instanceof | |
| 592 | - EE_Base_Class | |
| 593 | - ? array($this->_model_relations[ $relationName ]) : array(); | |
| 594 | - } | |
| 595 | - // first check for a cache_id which is normally empty | |
| 596 | -            if (! empty($cache_id)) { | |
| 597 | - // if the cache_id exists, then it means we are purposely trying to cache this | |
| 598 | - // with a known key that can then be used to retrieve the object later on | |
| 599 | - $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache; | |
| 600 | - $return = $cache_id; | |
| 601 | -            } elseif ($object_to_cache->ID()) { | |
| 602 | - // OR the cached object originally came from the db, so let's just use it's PK for an ID | |
| 603 | - $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache; | |
| 604 | - $return = $object_to_cache->ID(); | |
| 605 | -            } else { | |
| 606 | - // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID | |
| 607 | - $this->_model_relations[ $relationName ][] = $object_to_cache; | |
| 608 | - // move the internal pointer to the end of the array | |
| 609 | - end($this->_model_relations[ $relationName ]); | |
| 610 | - // and grab the key so that we can return it | |
| 611 | - $return = key($this->_model_relations[ $relationName ]); | |
| 612 | - } | |
| 613 | - } | |
| 614 | - return $return; | |
| 615 | - } | |
| 616 | - | |
| 617 | - | |
| 618 | - /** | |
| 619 | - * For adding an item to the cached_properties property. | |
| 620 | - * | |
| 621 | - * @access protected | |
| 622 | - * @param string $fieldname the property item the corresponding value is for. | |
| 623 | - * @param mixed $value The value we are caching. | |
| 624 | - * @param string|null $cache_type | |
| 625 | - * @return void | |
| 626 | - * @throws ReflectionException | |
| 627 | - * @throws InvalidArgumentException | |
| 628 | - * @throws InvalidInterfaceException | |
| 629 | - * @throws InvalidDataTypeException | |
| 630 | - * @throws EE_Error | |
| 631 | - */ | |
| 632 | - protected function _set_cached_property($fieldname, $value, $cache_type = null) | |
| 633 | -    { | |
| 634 | - // first make sure this property exists | |
| 635 | - $this->get_model()->field_settings_for($fieldname); | |
| 636 | - $cache_type = empty($cache_type) ? 'standard' : $cache_type; | |
| 637 | - $this->_cached_properties[ $fieldname ][ $cache_type ] = $value; | |
| 638 | - } | |
| 639 | - | |
| 640 | - | |
| 641 | - /** | |
| 642 | - * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist. | |
| 643 | - * This also SETS the cache if we return the actual property! | |
| 644 | - * | |
| 645 | - * @param string $fieldname the name of the property we're trying to retrieve | |
| 646 | - * @param bool $pretty | |
| 647 | - * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 648 | - * (in cases where the same property may be used for different outputs | |
| 649 | - * - i.e. datetime, money etc.) | |
| 650 | - * It can also accept certain pre-defined "schema" strings | |
| 651 | - * to define how to output the property. | |
| 652 | - * see the field's prepare_for_pretty_echoing for what strings can be used | |
| 653 | - * @return mixed whatever the value for the property is we're retrieving | |
| 654 | - * @throws ReflectionException | |
| 655 | - * @throws InvalidArgumentException | |
| 656 | - * @throws InvalidInterfaceException | |
| 657 | - * @throws InvalidDataTypeException | |
| 658 | - * @throws EE_Error | |
| 659 | - */ | |
| 660 | - protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null) | |
| 661 | -    { | |
| 662 | - // verify the field exists | |
| 663 | - $model = $this->get_model(); | |
| 664 | - $model->field_settings_for($fieldname); | |
| 665 | - $cache_type = $pretty ? 'pretty' : 'standard'; | |
| 666 | - $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : ''; | |
| 667 | -        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) { | |
| 668 | - return $this->_cached_properties[ $fieldname ][ $cache_type ]; | |
| 669 | - } | |
| 670 | - $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref); | |
| 671 | - $this->_set_cached_property($fieldname, $value, $cache_type); | |
| 672 | - return $value; | |
| 673 | - } | |
| 674 | - | |
| 675 | - | |
| 676 | - /** | |
| 677 | - * If the cache didn't fetch the needed item, this fetches it. | |
| 678 | - * | |
| 679 | - * @param string $fieldname | |
| 680 | - * @param bool $pretty | |
| 681 | - * @param string $extra_cache_ref | |
| 682 | - * @return mixed | |
| 683 | - * @throws InvalidArgumentException | |
| 684 | - * @throws InvalidInterfaceException | |
| 685 | - * @throws InvalidDataTypeException | |
| 686 | - * @throws EE_Error | |
| 687 | - * @throws ReflectionException | |
| 688 | - */ | |
| 689 | - protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null) | |
| 690 | -    { | |
| 691 | - $field_obj = $this->get_model()->field_settings_for($fieldname); | |
| 692 | - // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct | |
| 693 | -        if ($field_obj instanceof EE_Datetime_Field) { | |
| 694 | - $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref); | |
| 695 | - } | |
| 696 | -        if (! isset($this->_fields[ $fieldname ])) { | |
| 697 | - $this->_fields[ $fieldname ] = null; | |
| 698 | - } | |
| 699 | - $value = $pretty | |
| 700 | - ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref) | |
| 701 | - : $field_obj->prepare_for_get($this->_fields[ $fieldname ]); | |
| 702 | - return $value; | |
| 703 | - } | |
| 704 | - | |
| 705 | - | |
| 706 | - /** | |
| 707 | - * set timezone, formats, and output for EE_Datetime_Field objects | |
| 708 | - * | |
| 709 | - * @param \EE_Datetime_Field $datetime_field | |
| 710 | - * @param bool $pretty | |
| 711 | - * @param null $date_or_time | |
| 712 | - * @return void | |
| 713 | - * @throws InvalidArgumentException | |
| 714 | - * @throws InvalidInterfaceException | |
| 715 | - * @throws InvalidDataTypeException | |
| 716 | - * @throws EE_Error | |
| 717 | - */ | |
| 718 | - protected function _prepare_datetime_field( | |
| 719 | - EE_Datetime_Field $datetime_field, | |
| 720 | - $pretty = false, | |
| 721 | - $date_or_time = null | |
| 722 | -    ) { | |
| 723 | - $datetime_field->set_timezone($this->_timezone); | |
| 724 | - $datetime_field->set_date_format($this->_dt_frmt, $pretty); | |
| 725 | - $datetime_field->set_time_format($this->_tm_frmt, $pretty); | |
| 726 | - // set the output returned | |
| 727 | -        switch ($date_or_time) { | |
| 728 | - case 'D': | |
| 729 | -                $datetime_field->set_date_time_output('date'); | |
| 730 | - break; | |
| 731 | - case 'T': | |
| 732 | -                $datetime_field->set_date_time_output('time'); | |
| 733 | - break; | |
| 734 | - default: | |
| 735 | - $datetime_field->set_date_time_output(); | |
| 736 | - } | |
| 737 | - } | |
| 738 | - | |
| 739 | - | |
| 740 | - /** | |
| 741 | - * This just takes care of clearing out the cached_properties | |
| 742 | - * | |
| 743 | - * @return void | |
| 744 | - */ | |
| 745 | - protected function _clear_cached_properties() | |
| 746 | -    { | |
| 747 | - $this->_cached_properties = array(); | |
| 748 | - } | |
| 749 | - | |
| 750 | - | |
| 751 | - /** | |
| 752 | - * This just clears out ONE property if it exists in the cache | |
| 753 | - * | |
| 754 | - * @param string $property_name the property to remove if it exists (from the _cached_properties array) | |
| 755 | - * @return void | |
| 756 | - */ | |
| 757 | - protected function _clear_cached_property($property_name) | |
| 758 | -    { | |
| 759 | -        if (isset($this->_cached_properties[ $property_name ])) { | |
| 760 | - unset($this->_cached_properties[ $property_name ]); | |
| 761 | - } | |
| 762 | - } | |
| 763 | - | |
| 764 | - | |
| 765 | - /** | |
| 766 | - * Ensures that this related thing is a model object. | |
| 767 | - * | |
| 768 | - * @param mixed $object_or_id EE_base_Class/int/string either a related model object, or its ID | |
| 769 | - * @param string $model_name name of the related thing, eg 'Attendee', | |
| 770 | - * @return EE_Base_Class | |
| 771 | - * @throws ReflectionException | |
| 772 | - * @throws InvalidArgumentException | |
| 773 | - * @throws InvalidInterfaceException | |
| 774 | - * @throws InvalidDataTypeException | |
| 775 | - * @throws EE_Error | |
| 776 | - */ | |
| 777 | - protected function ensure_related_thing_is_model_obj($object_or_id, $model_name) | |
| 778 | -    { | |
| 779 | - $other_model_instance = self::_get_model_instance_with_name( | |
| 780 | - self::_get_model_classname($model_name), | |
| 781 | - $this->_timezone | |
| 782 | - ); | |
| 783 | - return $other_model_instance->ensure_is_obj($object_or_id); | |
| 784 | - } | |
| 785 | - | |
| 786 | - | |
| 787 | - /** | |
| 788 | - * Forgets the cached model of the given relation Name. So the next time we request it, | |
| 789 | - * we will fetch it again from the database. (Handy if you know it's changed somehow). | |
| 790 | - * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM, | |
| 791 | - * then only remove that one object from our cached array. Otherwise, clear the entire list | |
| 792 | - * | |
| 793 | - * @param string $relationName one of the keys in the _model_relations array on the model. | |
| 794 | - * Eg 'Registration' | |
| 795 | - * @param mixed $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL | |
| 796 | - * if you intend to use $clear_all = TRUE, or the relation only | |
| 797 | - * has 1 object anyways (ie, it's a BelongsToRelation) | |
| 798 | - * @param bool $clear_all This flags clearing the entire cache relation property if | |
| 799 | - * this is HasMany or HABTM. | |
| 800 | - * @throws ReflectionException | |
| 801 | - * @throws InvalidArgumentException | |
| 802 | - * @throws InvalidInterfaceException | |
| 803 | - * @throws InvalidDataTypeException | |
| 804 | - * @throws EE_Error | |
| 805 | - * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a | |
| 806 | - * relation from all | |
| 807 | - */ | |
| 808 | - public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false) | |
| 809 | -    { | |
| 810 | - $relationship_to_model = $this->get_model()->related_settings_for($relationName); | |
| 811 | - $index_in_cache = ''; | |
| 812 | -        if (! $relationship_to_model) { | |
| 813 | - throw new EE_Error( | |
| 814 | - sprintf( | |
| 815 | -                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'), | |
| 816 | - $relationName, | |
| 817 | - get_class($this) | |
| 818 | - ) | |
| 819 | - ); | |
| 820 | - } | |
| 821 | -        if ($clear_all) { | |
| 822 | - $obj_removed = true; | |
| 823 | - $this->_model_relations[ $relationName ] = null; | |
| 824 | -        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 825 | - $obj_removed = $this->_model_relations[ $relationName ]; | |
| 826 | - $this->_model_relations[ $relationName ] = null; | |
| 827 | -        } else { | |
| 828 | - if ($object_to_remove_or_index_into_array instanceof EE_Base_Class | |
| 829 | - && $object_to_remove_or_index_into_array->ID() | |
| 830 | -            ) { | |
| 831 | - $index_in_cache = $object_to_remove_or_index_into_array->ID(); | |
| 832 | - if (is_array($this->_model_relations[ $relationName ]) | |
| 833 | - && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ]) | |
| 834 | -                ) { | |
| 835 | - $index_found_at = null; | |
| 836 | - // find this object in the array even though it has a different key | |
| 837 | -                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) { | |
| 838 | - /** @noinspection TypeUnsafeComparisonInspection */ | |
| 839 | - if ($obj instanceof EE_Base_Class | |
| 840 | - && ( | |
| 841 | - $obj == $object_to_remove_or_index_into_array | |
| 842 | - || $obj->ID() === $object_to_remove_or_index_into_array->ID() | |
| 843 | - ) | |
| 844 | -                        ) { | |
| 845 | - $index_found_at = $index; | |
| 846 | - break; | |
| 847 | - } | |
| 848 | - } | |
| 849 | -                    if ($index_found_at) { | |
| 850 | - $index_in_cache = $index_found_at; | |
| 851 | -                    } else { | |
| 852 | - // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache | |
| 853 | - // if it wasn't in it to begin with. So we're done | |
| 854 | - return $object_to_remove_or_index_into_array; | |
| 855 | - } | |
| 856 | - } | |
| 857 | -            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) { | |
| 858 | - // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it! | |
| 859 | -                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) { | |
| 860 | - /** @noinspection TypeUnsafeComparisonInspection */ | |
| 861 | -                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) { | |
| 862 | - $index_in_cache = $index; | |
| 863 | - } | |
| 864 | - } | |
| 865 | -            } else { | |
| 866 | - $index_in_cache = $object_to_remove_or_index_into_array; | |
| 867 | - } | |
| 868 | - // supposedly we've found it. But it could just be that the client code | |
| 869 | - // provided a bad index/object | |
| 870 | -            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) { | |
| 871 | - $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ]; | |
| 872 | - unset($this->_model_relations[ $relationName ][ $index_in_cache ]); | |
| 873 | -            } else { | |
| 874 | - // that thing was never cached anyways. | |
| 875 | - $obj_removed = null; | |
| 876 | - } | |
| 877 | - } | |
| 878 | - return $obj_removed; | |
| 879 | - } | |
| 880 | - | |
| 881 | - | |
| 882 | - /** | |
| 883 | - * update_cache_after_object_save | |
| 884 | - * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has | |
| 885 | - * obtained after being saved to the db | |
| 886 | - * | |
| 887 | - * @param string $relationName - the type of object that is cached | |
| 888 | - * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached | |
| 889 | - * @param string $current_cache_id - the ID that was used when originally caching the object | |
| 890 | - * @return boolean TRUE on success, FALSE on fail | |
| 891 | - * @throws ReflectionException | |
| 892 | - * @throws InvalidArgumentException | |
| 893 | - * @throws InvalidInterfaceException | |
| 894 | - * @throws InvalidDataTypeException | |
| 895 | - * @throws EE_Error | |
| 896 | - */ | |
| 897 | - public function update_cache_after_object_save( | |
| 898 | - $relationName, | |
| 899 | - EE_Base_Class $newly_saved_object, | |
| 900 | - $current_cache_id = '' | |
| 901 | -    ) { | |
| 902 | - // verify that incoming object is of the correct type | |
| 903 | - $obj_class = 'EE_' . $relationName; | |
| 904 | -        if ($newly_saved_object instanceof $obj_class) { | |
| 905 | - /* @type EE_Base_Class $newly_saved_object */ | |
| 906 | - // now get the type of relation | |
| 907 | - $relationship_to_model = $this->get_model()->related_settings_for($relationName); | |
| 908 | - // if this is a 1:1 relationship | |
| 909 | -            if ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 910 | - // then just replace the cached object with the newly saved object | |
| 911 | - $this->_model_relations[ $relationName ] = $newly_saved_object; | |
| 912 | - return true; | |
| 913 | - // or if it's some kind of sordid feral polyamorous relationship... | |
| 914 | - } | |
| 915 | - if (is_array($this->_model_relations[ $relationName ]) | |
| 916 | - && isset($this->_model_relations[ $relationName ][ $current_cache_id ]) | |
| 917 | -            ) { | |
| 918 | - // then remove the current cached item | |
| 919 | - unset($this->_model_relations[ $relationName ][ $current_cache_id ]); | |
| 920 | - // and cache the newly saved object using it's new ID | |
| 921 | - $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object; | |
| 922 | - return true; | |
| 923 | - } | |
| 924 | - } | |
| 925 | - return false; | |
| 926 | - } | |
| 927 | - | |
| 928 | - | |
| 929 | - /** | |
| 930 | - * Fetches a single EE_Base_Class on that relation. (If the relation is of type | |
| 931 | - * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects) | |
| 932 | - * | |
| 933 | - * @param string $relationName | |
| 934 | - * @return EE_Base_Class | |
| 935 | - */ | |
| 936 | - public function get_one_from_cache($relationName) | |
| 937 | -    { | |
| 938 | - $cached_array_or_object = isset($this->_model_relations[ $relationName ]) | |
| 939 | - ? $this->_model_relations[ $relationName ] | |
| 940 | - : null; | |
| 941 | -        if (is_array($cached_array_or_object)) { | |
| 942 | - return array_shift($cached_array_or_object); | |
| 943 | - } | |
| 944 | - return $cached_array_or_object; | |
| 945 | - } | |
| 946 | - | |
| 947 | - | |
| 948 | - /** | |
| 949 | - * Fetches a single EE_Base_Class on that relation. (If the relation is of type | |
| 950 | - * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects) | |
| 951 | - * | |
| 952 | - * @param string $relationName | |
| 953 | - * @throws ReflectionException | |
| 954 | - * @throws InvalidArgumentException | |
| 955 | - * @throws InvalidInterfaceException | |
| 956 | - * @throws InvalidDataTypeException | |
| 957 | - * @throws EE_Error | |
| 958 | - * @return EE_Base_Class[] NOT necessarily indexed by primary keys | |
| 959 | - */ | |
| 960 | - public function get_all_from_cache($relationName) | |
| 961 | -    { | |
| 962 | - $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array(); | |
| 963 | - // if the result is not an array, but exists, make it an array | |
| 964 | - $objects = is_array($objects) ? $objects : array($objects); | |
| 965 | - // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143 | |
| 966 | - // basically, if this model object was stored in the session, and these cached model objects | |
| 967 | - // already have IDs, let's make sure they're in their model's entity mapper | |
| 968 | - // otherwise we will have duplicates next time we call | |
| 969 | - // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() ); | |
| 970 | - $model = EE_Registry::instance()->load_model($relationName); | |
| 971 | -        foreach ($objects as $model_object) { | |
| 972 | -            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) { | |
| 973 | - // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved | |
| 974 | -                if ($model_object->ID()) { | |
| 975 | - $model->add_to_entity_map($model_object); | |
| 976 | - } | |
| 977 | -            } else { | |
| 978 | - throw new EE_Error( | |
| 979 | - sprintf( | |
| 980 | - esc_html__( | |
| 981 | - 'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object', | |
| 982 | - 'event_espresso' | |
| 983 | - ), | |
| 984 | - $relationName, | |
| 985 | - gettype($model_object) | |
| 986 | - ) | |
| 987 | - ); | |
| 988 | - } | |
| 989 | - } | |
| 990 | - return $objects; | |
| 991 | - } | |
| 992 | - | |
| 993 | - | |
| 994 | - /** | |
| 995 | - * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database | |
| 996 | - * matching the given query conditions. | |
| 997 | - * | |
| 998 | - * @param null $field_to_order_by What field is being used as the reference point. | |
| 999 | - * @param int $limit How many objects to return. | |
| 1000 | - * @param array $query_params Any additional conditions on the query. | |
| 1001 | - * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1002 | - * you can indicate just the columns you want returned | |
| 1003 | - * @return array|EE_Base_Class[] | |
| 1004 | - * @throws ReflectionException | |
| 1005 | - * @throws InvalidArgumentException | |
| 1006 | - * @throws InvalidInterfaceException | |
| 1007 | - * @throws InvalidDataTypeException | |
| 1008 | - * @throws EE_Error | |
| 1009 | - */ | |
| 1010 | - public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null) | |
| 1011 | -    { | |
| 1012 | - $model = $this->get_model(); | |
| 1013 | - $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1014 | - ? $model->get_primary_key_field()->get_name() | |
| 1015 | - : $field_to_order_by; | |
| 1016 | - $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1017 | -        if (empty($field) || empty($current_value)) { | |
| 1018 | - return array(); | |
| 1019 | - } | |
| 1020 | - return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select); | |
| 1021 | - } | |
| 1022 | - | |
| 1023 | - | |
| 1024 | - /** | |
| 1025 | - * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database | |
| 1026 | - * matching the given query conditions. | |
| 1027 | - * | |
| 1028 | - * @param null $field_to_order_by What field is being used as the reference point. | |
| 1029 | - * @param int $limit How many objects to return. | |
| 1030 | - * @param array $query_params Any additional conditions on the query. | |
| 1031 | - * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1032 | - * you can indicate just the columns you want returned | |
| 1033 | - * @return array|EE_Base_Class[] | |
| 1034 | - * @throws ReflectionException | |
| 1035 | - * @throws InvalidArgumentException | |
| 1036 | - * @throws InvalidInterfaceException | |
| 1037 | - * @throws InvalidDataTypeException | |
| 1038 | - * @throws EE_Error | |
| 1039 | - */ | |
| 1040 | - public function previous_x( | |
| 1041 | - $field_to_order_by = null, | |
| 1042 | - $limit = 1, | |
| 1043 | - $query_params = array(), | |
| 1044 | - $columns_to_select = null | |
| 1045 | -    ) { | |
| 1046 | - $model = $this->get_model(); | |
| 1047 | - $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1048 | - ? $model->get_primary_key_field()->get_name() | |
| 1049 | - : $field_to_order_by; | |
| 1050 | - $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1051 | -        if (empty($field) || empty($current_value)) { | |
| 1052 | - return array(); | |
| 1053 | - } | |
| 1054 | - return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select); | |
| 1055 | - } | |
| 1056 | - | |
| 1057 | - | |
| 1058 | - /** | |
| 1059 | - * Returns the next EE_Base_Class object in sequence from this object as found in the database | |
| 1060 | - * matching the given query conditions. | |
| 1061 | - * | |
| 1062 | - * @param null $field_to_order_by What field is being used as the reference point. | |
| 1063 | - * @param array $query_params Any additional conditions on the query. | |
| 1064 | - * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1065 | - * you can indicate just the columns you want returned | |
| 1066 | - * @return array|EE_Base_Class | |
| 1067 | - * @throws ReflectionException | |
| 1068 | - * @throws InvalidArgumentException | |
| 1069 | - * @throws InvalidInterfaceException | |
| 1070 | - * @throws InvalidDataTypeException | |
| 1071 | - * @throws EE_Error | |
| 1072 | - */ | |
| 1073 | - public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null) | |
| 1074 | -    { | |
| 1075 | - $model = $this->get_model(); | |
| 1076 | - $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1077 | - ? $model->get_primary_key_field()->get_name() | |
| 1078 | - : $field_to_order_by; | |
| 1079 | - $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1080 | -        if (empty($field) || empty($current_value)) { | |
| 1081 | - return array(); | |
| 1082 | - } | |
| 1083 | - return $model->next($current_value, $field, $query_params, $columns_to_select); | |
| 1084 | - } | |
| 1085 | - | |
| 1086 | - | |
| 1087 | - /** | |
| 1088 | - * Returns the previous EE_Base_Class object in sequence from this object as found in the database | |
| 1089 | - * matching the given query conditions. | |
| 1090 | - * | |
| 1091 | - * @param null $field_to_order_by What field is being used as the reference point. | |
| 1092 | - * @param array $query_params Any additional conditions on the query. | |
| 1093 | - * @param null $columns_to_select If left null, then an EE_Base_Class object is returned, otherwise | |
| 1094 | - * you can indicate just the column you want returned | |
| 1095 | - * @return array|EE_Base_Class | |
| 1096 | - * @throws ReflectionException | |
| 1097 | - * @throws InvalidArgumentException | |
| 1098 | - * @throws InvalidInterfaceException | |
| 1099 | - * @throws InvalidDataTypeException | |
| 1100 | - * @throws EE_Error | |
| 1101 | - */ | |
| 1102 | - public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null) | |
| 1103 | -    { | |
| 1104 | - $model = $this->get_model(); | |
| 1105 | - $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1106 | - ? $model->get_primary_key_field()->get_name() | |
| 1107 | - : $field_to_order_by; | |
| 1108 | - $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1109 | -        if (empty($field) || empty($current_value)) { | |
| 1110 | - return array(); | |
| 1111 | - } | |
| 1112 | - return $model->previous($current_value, $field, $query_params, $columns_to_select); | |
| 1113 | - } | |
| 1114 | - | |
| 1115 | - | |
| 1116 | - /** | |
| 1117 | - * Overrides parent because parent expects old models. | |
| 1118 | - * This also doesn't do any validation, and won't work for serialized arrays | |
| 1119 | - * | |
| 1120 | - * @param string $field_name | |
| 1121 | - * @param mixed $field_value_from_db | |
| 1122 | - * @throws ReflectionException | |
| 1123 | - * @throws InvalidArgumentException | |
| 1124 | - * @throws InvalidInterfaceException | |
| 1125 | - * @throws InvalidDataTypeException | |
| 1126 | - * @throws EE_Error | |
| 1127 | - */ | |
| 1128 | - public function set_from_db($field_name, $field_value_from_db) | |
| 1129 | -    { | |
| 1130 | - $field_obj = $this->get_model()->field_settings_for($field_name); | |
| 1131 | -        if ($field_obj instanceof EE_Model_Field_Base) { | |
| 1132 | - // you would think the DB has no NULLs for non-null label fields right? wrong! | |
| 1133 | - // eg, a CPT model object could have an entry in the posts table, but no | |
| 1134 | - // entry in the meta table. Meaning that all its columns in the meta table | |
| 1135 | - // are null! yikes! so when we find one like that, use defaults for its meta columns | |
| 1136 | -            if ($field_value_from_db === null) { | |
| 1137 | -                if ($field_obj->is_nullable()) { | |
| 1138 | - // if the field allows nulls, then let it be null | |
| 1139 | - $field_value = null; | |
| 1140 | -                } else { | |
| 1141 | - $field_value = $field_obj->get_default_value(); | |
| 1142 | - } | |
| 1143 | -            } else { | |
| 1144 | - $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db); | |
| 1145 | - } | |
| 1146 | - $this->_fields[ $field_name ] = $field_value; | |
| 1147 | - $this->_clear_cached_property($field_name); | |
| 1148 | - } | |
| 1149 | - } | |
| 1150 | - | |
| 1151 | - | |
| 1152 | - /** | |
| 1153 | - * verifies that the specified field is of the correct type | |
| 1154 | - * | |
| 1155 | - * @param string $field_name | |
| 1156 | - * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1157 | - * (in cases where the same property may be used for different outputs | |
| 1158 | - * - i.e. datetime, money etc.) | |
| 1159 | - * @return mixed | |
| 1160 | - * @throws ReflectionException | |
| 1161 | - * @throws InvalidArgumentException | |
| 1162 | - * @throws InvalidInterfaceException | |
| 1163 | - * @throws InvalidDataTypeException | |
| 1164 | - * @throws EE_Error | |
| 1165 | - */ | |
| 1166 | - public function get($field_name, $extra_cache_ref = null) | |
| 1167 | -    { | |
| 1168 | - return $this->_get_cached_property($field_name, false, $extra_cache_ref); | |
| 1169 | - } | |
| 1170 | - | |
| 1171 | - | |
| 1172 | - /** | |
| 1173 | - * This method simply returns the RAW unprocessed value for the given property in this class | |
| 1174 | - * | |
| 1175 | - * @param string $field_name A valid fieldname | |
| 1176 | - * @return mixed Whatever the raw value stored on the property is. | |
| 1177 | - * @throws ReflectionException | |
| 1178 | - * @throws InvalidArgumentException | |
| 1179 | - * @throws InvalidInterfaceException | |
| 1180 | - * @throws InvalidDataTypeException | |
| 1181 | - * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist. | |
| 1182 | - */ | |
| 1183 | - public function get_raw($field_name) | |
| 1184 | -    { | |
| 1185 | - $field_settings = $this->get_model()->field_settings_for($field_name); | |
| 1186 | - return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime | |
| 1187 | -            ? $this->_fields[ $field_name ]->format('U') | |
| 1188 | - : $this->_fields[ $field_name ]; | |
| 1189 | - } | |
| 1190 | - | |
| 1191 | - | |
| 1192 | - /** | |
| 1193 | - * This is used to return the internal DateTime object used for a field that is a | |
| 1194 | - * EE_Datetime_Field. | |
| 1195 | - * | |
| 1196 | - * @param string $field_name The field name retrieving the DateTime object. | |
| 1197 | - * @return mixed null | false | DateTime If the requested field is NOT a EE_Datetime_Field then | |
| 1198 | - * @throws EE_Error an error is set and false returned. If the field IS an | |
| 1199 | - * EE_Datetime_Field and but the field value is null, then | |
| 1200 | - * just null is returned (because that indicates that likely | |
| 1201 | - * this field is nullable). | |
| 1202 | - * @throws InvalidArgumentException | |
| 1203 | - * @throws InvalidDataTypeException | |
| 1204 | - * @throws InvalidInterfaceException | |
| 1205 | - * @throws ReflectionException | |
| 1206 | - */ | |
| 1207 | - public function get_DateTime_object($field_name) | |
| 1208 | -    { | |
| 1209 | - $field_settings = $this->get_model()->field_settings_for($field_name); | |
| 1210 | -        if (! $field_settings instanceof EE_Datetime_Field) { | |
| 1211 | - EE_Error::add_error( | |
| 1212 | - sprintf( | |
| 1213 | - esc_html__( | |
| 1214 | - 'The field %s is not an EE_Datetime_Field field. There is no DateTime object stored on this field type.', | |
| 1215 | - 'event_espresso' | |
| 1216 | - ), | |
| 1217 | - $field_name | |
| 1218 | - ), | |
| 1219 | - __FILE__, | |
| 1220 | - __FUNCTION__, | |
| 1221 | - __LINE__ | |
| 1222 | - ); | |
| 1223 | - return false; | |
| 1224 | - } | |
| 1225 | - return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime | |
| 1226 | - ? clone $this->_fields[ $field_name ] | |
| 1227 | - : null; | |
| 1228 | - } | |
| 1229 | - | |
| 1230 | - | |
| 1231 | - /** | |
| 1232 | - * To be used in template to immediately echo out the value, and format it for output. | |
| 1233 | - * Eg, should call stripslashes and whatnot before echoing | |
| 1234 | - * | |
| 1235 | - * @param string $field_name the name of the field as it appears in the DB | |
| 1236 | - * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1237 | - * (in cases where the same property may be used for different outputs | |
| 1238 | - * - i.e. datetime, money etc.) | |
| 1239 | - * @return void | |
| 1240 | - * @throws ReflectionException | |
| 1241 | - * @throws InvalidArgumentException | |
| 1242 | - * @throws InvalidInterfaceException | |
| 1243 | - * @throws InvalidDataTypeException | |
| 1244 | - * @throws EE_Error | |
| 1245 | - */ | |
| 1246 | - public function e($field_name, $extra_cache_ref = null) | |
| 1247 | -    { | |
| 1248 | - echo $this->get_pretty($field_name, $extra_cache_ref); | |
| 1249 | - } | |
| 1250 | - | |
| 1251 | - | |
| 1252 | - /** | |
| 1253 | - * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it | |
| 1254 | - * can be easily used as the value of form input. | |
| 1255 | - * | |
| 1256 | - * @param string $field_name | |
| 1257 | - * @return void | |
| 1258 | - * @throws ReflectionException | |
| 1259 | - * @throws InvalidArgumentException | |
| 1260 | - * @throws InvalidInterfaceException | |
| 1261 | - * @throws InvalidDataTypeException | |
| 1262 | - * @throws EE_Error | |
| 1263 | - */ | |
| 1264 | - public function f($field_name) | |
| 1265 | -    { | |
| 1266 | - $this->e($field_name, 'form_input'); | |
| 1267 | - } | |
| 1268 | - | |
| 1269 | - | |
| 1270 | - /** | |
| 1271 | - * Same as `f()` but just returns the value instead of echoing it | |
| 1272 | - * | |
| 1273 | - * @param string $field_name | |
| 1274 | - * @return string | |
| 1275 | - * @throws ReflectionException | |
| 1276 | - * @throws InvalidArgumentException | |
| 1277 | - * @throws InvalidInterfaceException | |
| 1278 | - * @throws InvalidDataTypeException | |
| 1279 | - * @throws EE_Error | |
| 1280 | - */ | |
| 1281 | - public function get_f($field_name) | |
| 1282 | -    { | |
| 1283 | - return (string) $this->get_pretty($field_name, 'form_input'); | |
| 1284 | - } | |
| 1285 | - | |
| 1286 | - | |
| 1287 | - /** | |
| 1288 | - * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this. | |
| 1289 | - * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class | |
| 1290 | - * to see what options are available. | |
| 1291 | - * | |
| 1292 | - * @param string $field_name | |
| 1293 | - * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1294 | - * (in cases where the same property may be used for different outputs | |
| 1295 | - * - i.e. datetime, money etc.) | |
| 1296 | - * @return mixed | |
| 1297 | - * @throws ReflectionException | |
| 1298 | - * @throws InvalidArgumentException | |
| 1299 | - * @throws InvalidInterfaceException | |
| 1300 | - * @throws InvalidDataTypeException | |
| 1301 | - * @throws EE_Error | |
| 1302 | - */ | |
| 1303 | - public function get_pretty($field_name, $extra_cache_ref = null) | |
| 1304 | -    { | |
| 1305 | - return $this->_get_cached_property($field_name, true, $extra_cache_ref); | |
| 1306 | - } | |
| 1307 | - | |
| 1308 | - | |
| 1309 | - /** | |
| 1310 | - * This simply returns the datetime for the given field name | |
| 1311 | - * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions | |
| 1312 | - * (and the equivalent e_date, e_time, e_datetime). | |
| 1313 | - * | |
| 1314 | - * @access protected | |
| 1315 | - * @param string $field_name Field on the instantiated EE_Base_Class child object | |
| 1316 | - * @param string $dt_frmt valid datetime format used for date | |
| 1317 | - * (if '' then we just use the default on the field, | |
| 1318 | - * if NULL we use the last-used format) | |
| 1319 | - * @param string $tm_frmt Same as above except this is for time format | |
| 1320 | - * @param string $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time. | |
| 1321 | - * @param boolean $echo Whether the dtt is echoing using pretty echoing or just returned using vanilla get | |
| 1322 | - * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown | |
| 1323 | - * if field is not a valid dtt field, or void if echoing | |
| 1324 | - * @throws ReflectionException | |
| 1325 | - * @throws InvalidArgumentException | |
| 1326 | - * @throws InvalidInterfaceException | |
| 1327 | - * @throws InvalidDataTypeException | |
| 1328 | - * @throws EE_Error | |
| 1329 | - */ | |
| 1330 | - protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false) | |
| 1331 | -    { | |
| 1332 | - // clear cached property | |
| 1333 | - $this->_clear_cached_property($field_name); | |
| 1334 | - // reset format properties because they are used in get() | |
| 1335 | - $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt; | |
| 1336 | - $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt; | |
| 1337 | -        if ($echo) { | |
| 1338 | - $this->e($field_name, $date_or_time); | |
| 1339 | - return ''; | |
| 1340 | - } | |
| 1341 | - return $this->get($field_name, $date_or_time); | |
| 1342 | - } | |
| 1343 | - | |
| 1344 | - | |
| 1345 | - /** | |
| 1346 | - * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date | |
| 1347 | - * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1348 | - * other echoes the pretty value for dtt) | |
| 1349 | - * | |
| 1350 | - * @param string $field_name name of model object datetime field holding the value | |
| 1351 | - * @param string $format format for the date returned (if NULL we use default in dt_frmt property) | |
| 1352 | - * @return string datetime value formatted | |
| 1353 | - * @throws ReflectionException | |
| 1354 | - * @throws InvalidArgumentException | |
| 1355 | - * @throws InvalidInterfaceException | |
| 1356 | - * @throws InvalidDataTypeException | |
| 1357 | - * @throws EE_Error | |
| 1358 | - */ | |
| 1359 | - public function get_date($field_name, $format = '') | |
| 1360 | -    { | |
| 1361 | - return $this->_get_datetime($field_name, $format, null, 'D'); | |
| 1362 | - } | |
| 1363 | - | |
| 1364 | - | |
| 1365 | - /** | |
| 1366 | - * @param $field_name | |
| 1367 | - * @param string $format | |
| 1368 | - * @throws ReflectionException | |
| 1369 | - * @throws InvalidArgumentException | |
| 1370 | - * @throws InvalidInterfaceException | |
| 1371 | - * @throws InvalidDataTypeException | |
| 1372 | - * @throws EE_Error | |
| 1373 | - */ | |
| 1374 | - public function e_date($field_name, $format = '') | |
| 1375 | -    { | |
| 1376 | - $this->_get_datetime($field_name, $format, null, 'D', true); | |
| 1377 | - } | |
| 1378 | - | |
| 1379 | - | |
| 1380 | - /** | |
| 1381 | - * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time | |
| 1382 | - * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1383 | - * other echoes the pretty value for dtt) | |
| 1384 | - * | |
| 1385 | - * @param string $field_name name of model object datetime field holding the value | |
| 1386 | - * @param string $format format for the time returned ( if NULL we use default in tm_frmt property) | |
| 1387 | - * @return string datetime value formatted | |
| 1388 | - * @throws ReflectionException | |
| 1389 | - * @throws InvalidArgumentException | |
| 1390 | - * @throws InvalidInterfaceException | |
| 1391 | - * @throws InvalidDataTypeException | |
| 1392 | - * @throws EE_Error | |
| 1393 | - */ | |
| 1394 | - public function get_time($field_name, $format = '') | |
| 1395 | -    { | |
| 1396 | - return $this->_get_datetime($field_name, null, $format, 'T'); | |
| 1397 | - } | |
| 1398 | - | |
| 1399 | - | |
| 1400 | - /** | |
| 1401 | - * @param $field_name | |
| 1402 | - * @param string $format | |
| 1403 | - * @throws ReflectionException | |
| 1404 | - * @throws InvalidArgumentException | |
| 1405 | - * @throws InvalidInterfaceException | |
| 1406 | - * @throws InvalidDataTypeException | |
| 1407 | - * @throws EE_Error | |
| 1408 | - */ | |
| 1409 | - public function e_time($field_name, $format = '') | |
| 1410 | -    { | |
| 1411 | - $this->_get_datetime($field_name, null, $format, 'T', true); | |
| 1412 | - } | |
| 1413 | - | |
| 1414 | - | |
| 1415 | - /** | |
| 1416 | - * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND | |
| 1417 | - * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1418 | - * other echoes the pretty value for dtt) | |
| 1419 | - * | |
| 1420 | - * @param string $field_name name of model object datetime field holding the value | |
| 1421 | - * @param string $dt_frmt format for the date returned (if NULL we use default in dt_frmt property) | |
| 1422 | - * @param string $tm_frmt format for the time returned (if NULL we use default in tm_frmt property) | |
| 1423 | - * @return string datetime value formatted | |
| 1424 | - * @throws ReflectionException | |
| 1425 | - * @throws InvalidArgumentException | |
| 1426 | - * @throws InvalidInterfaceException | |
| 1427 | - * @throws InvalidDataTypeException | |
| 1428 | - * @throws EE_Error | |
| 1429 | - */ | |
| 1430 | - public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '') | |
| 1431 | -    { | |
| 1432 | - return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt); | |
| 1433 | - } | |
| 1434 | - | |
| 1435 | - | |
| 1436 | - /** | |
| 1437 | - * @param string $field_name | |
| 1438 | - * @param string $dt_frmt | |
| 1439 | - * @param string $tm_frmt | |
| 1440 | - * @throws ReflectionException | |
| 1441 | - * @throws InvalidArgumentException | |
| 1442 | - * @throws InvalidInterfaceException | |
| 1443 | - * @throws InvalidDataTypeException | |
| 1444 | - * @throws EE_Error | |
| 1445 | - */ | |
| 1446 | - public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '') | |
| 1447 | -    { | |
| 1448 | - $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true); | |
| 1449 | - } | |
| 1450 | - | |
| 1451 | - | |
| 1452 | - /** | |
| 1453 | - * Get the i8ln value for a date using the WordPress @see date_i18n function. | |
| 1454 | - * | |
| 1455 | - * @param string $field_name The EE_Datetime_Field reference for the date being retrieved. | |
| 1456 | - * @param string $format PHP valid date/time string format. If none is provided then the internal set format | |
| 1457 | - * on the object will be used. | |
| 1458 | - * @return string Date and time string in set locale or false if no field exists for the given | |
| 1459 | - * @throws ReflectionException | |
| 1460 | - * @throws InvalidArgumentException | |
| 1461 | - * @throws InvalidInterfaceException | |
| 1462 | - * @throws InvalidDataTypeException | |
| 1463 | - * @throws EE_Error | |
| 1464 | - * field name. | |
| 1465 | - */ | |
| 1466 | - public function get_i18n_datetime($field_name, $format = '') | |
| 1467 | -    { | |
| 1468 | - $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format; | |
| 1469 | - return date_i18n( | |
| 1470 | - $format, | |
| 1471 | - EEH_DTT_Helper::get_timestamp_with_offset( | |
| 1472 | - $this->get_raw($field_name), | |
| 1473 | - $this->_timezone | |
| 1474 | - ) | |
| 1475 | - ); | |
| 1476 | - } | |
| 1477 | - | |
| 1478 | - | |
| 1479 | - /** | |
| 1480 | - * This method validates whether the given field name is a valid field on the model object as well as it is of a | |
| 1481 | - * type EE_Datetime_Field. On success there will be returned the field settings. On fail an EE_Error exception is | |
| 1482 | - * thrown. | |
| 1483 | - * | |
| 1484 | - * @param string $field_name The field name being checked | |
| 1485 | - * @throws ReflectionException | |
| 1486 | - * @throws InvalidArgumentException | |
| 1487 | - * @throws InvalidInterfaceException | |
| 1488 | - * @throws InvalidDataTypeException | |
| 1489 | - * @throws EE_Error | |
| 1490 | - * @return EE_Datetime_Field | |
| 1491 | - */ | |
| 1492 | - protected function _get_dtt_field_settings($field_name) | |
| 1493 | -    { | |
| 1494 | - $field = $this->get_model()->field_settings_for($field_name); | |
| 1495 | - // check if field is dtt | |
| 1496 | -        if ($field instanceof EE_Datetime_Field) { | |
| 1497 | - return $field; | |
| 1498 | - } | |
| 1499 | - throw new EE_Error( | |
| 1500 | - sprintf( | |
| 1501 | - esc_html__( | |
| 1502 | - 'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field. Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor', | |
| 1503 | - 'event_espresso' | |
| 1504 | - ), | |
| 1505 | - $field_name, | |
| 1506 | - self::_get_model_classname(get_class($this)) | |
| 1507 | - ) | |
| 1508 | - ); | |
| 1509 | - } | |
| 1510 | - | |
| 1511 | - | |
| 1512 | - | |
| 1513 | - | |
| 1514 | - /** | |
| 1515 | - * NOTE ABOUT BELOW: | |
| 1516 | - * These convenience date and time setters are for setting date and time independently. In other words you might | |
| 1517 | - * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand | |
| 1518 | - * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value) | |
| 1519 | - * method and make sure you send the entire datetime value for setting. | |
| 1520 | - */ | |
| 1521 | - /** | |
| 1522 | - * sets the time on a datetime property | |
| 1523 | - * | |
| 1524 | - * @access protected | |
| 1525 | - * @param string|Datetime $time a valid time string for php datetime functions (or DateTime object) | |
| 1526 | - * @param string $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field) | |
| 1527 | - * @throws ReflectionException | |
| 1528 | - * @throws InvalidArgumentException | |
| 1529 | - * @throws InvalidInterfaceException | |
| 1530 | - * @throws InvalidDataTypeException | |
| 1531 | - * @throws EE_Error | |
| 1532 | - */ | |
| 1533 | - protected function _set_time_for($time, $fieldname) | |
| 1534 | -    { | |
| 1535 | -        $this->_set_date_time('T', $time, $fieldname); | |
| 1536 | - } | |
| 1537 | - | |
| 1538 | - | |
| 1539 | - /** | |
| 1540 | - * sets the date on a datetime property | |
| 1541 | - * | |
| 1542 | - * @access protected | |
| 1543 | - * @param string|DateTime $date a valid date string for php datetime functions ( or DateTime object) | |
| 1544 | - * @param string $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field) | |
| 1545 | - * @throws ReflectionException | |
| 1546 | - * @throws InvalidArgumentException | |
| 1547 | - * @throws InvalidInterfaceException | |
| 1548 | - * @throws InvalidDataTypeException | |
| 1549 | - * @throws EE_Error | |
| 1550 | - */ | |
| 1551 | - protected function _set_date_for($date, $fieldname) | |
| 1552 | -    { | |
| 1553 | -        $this->_set_date_time('D', $date, $fieldname); | |
| 1554 | - } | |
| 1555 | - | |
| 1556 | - | |
| 1557 | - /** | |
| 1558 | - * This takes care of setting a date or time independently on a given model object property. This method also | |
| 1559 | - * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field | |
| 1560 | - * | |
| 1561 | - * @access protected | |
| 1562 | - * @param string $what "T" for time, 'B' for both, 'D' for Date. | |
| 1563 | - * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object) | |
| 1564 | - * @param string $fieldname the name of the field the date OR time is being set on (must match a | |
| 1565 | - * EE_Datetime_Field property) | |
| 1566 | - * @throws ReflectionException | |
| 1567 | - * @throws InvalidArgumentException | |
| 1568 | - * @throws InvalidInterfaceException | |
| 1569 | - * @throws InvalidDataTypeException | |
| 1570 | - * @throws EE_Error | |
| 1571 | - */ | |
| 1572 | - protected function _set_date_time($what = 'T', $datetime_value, $fieldname) | |
| 1573 | -    { | |
| 1574 | - $field = $this->_get_dtt_field_settings($fieldname); | |
| 1575 | - $field->set_timezone($this->_timezone); | |
| 1576 | - $field->set_date_format($this->_dt_frmt); | |
| 1577 | - $field->set_time_format($this->_tm_frmt); | |
| 1578 | -        switch ($what) { | |
| 1579 | - case 'T': | |
| 1580 | - $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time( | |
| 1581 | - $datetime_value, | |
| 1582 | - $this->_fields[ $fieldname ] | |
| 1583 | - ); | |
| 1584 | - break; | |
| 1585 | - case 'D': | |
| 1586 | - $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date( | |
| 1587 | - $datetime_value, | |
| 1588 | - $this->_fields[ $fieldname ] | |
| 1589 | - ); | |
| 1590 | - break; | |
| 1591 | - case 'B': | |
| 1592 | - $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value); | |
| 1593 | - break; | |
| 1594 | - } | |
| 1595 | - $this->_clear_cached_property($fieldname); | |
| 1596 | - } | |
| 1597 | - | |
| 1598 | - | |
| 1599 | - /** | |
| 1600 | - * This will return a timestamp for the website timezone but ONLY when the current website timezone is different | |
| 1601 | - * than the timezone set for the website. NOTE, this currently only works well with methods that return values. If | |
| 1602 | - * you use it with methods that echo values the $_timestamp property may not get reset to its original value and | |
| 1603 | - * that could lead to some unexpected results! | |
| 1604 | - * | |
| 1605 | - * @access public | |
| 1606 | - * @param string $field_name This is the name of the field on the object that contains the date/time | |
| 1607 | - * value being returned. | |
| 1608 | - * @param string $callback must match a valid method in this class (defaults to get_datetime) | |
| 1609 | - * @param mixed (array|string) $args This is the arguments that will be passed to the callback. | |
| 1610 | - * @param string $prepend You can include something to prepend on the timestamp | |
| 1611 | - * @param string $append You can include something to append on the timestamp | |
| 1612 | - * @throws ReflectionException | |
| 1613 | - * @throws InvalidArgumentException | |
| 1614 | - * @throws InvalidInterfaceException | |
| 1615 | - * @throws InvalidDataTypeException | |
| 1616 | - * @throws EE_Error | |
| 1617 | - * @return string timestamp | |
| 1618 | - */ | |
| 1619 | - public function display_in_my_timezone( | |
| 1620 | - $field_name, | |
| 1621 | - $callback = 'get_datetime', | |
| 1622 | - $args = null, | |
| 1623 | - $prepend = '', | |
| 1624 | - $append = '' | |
| 1625 | -    ) { | |
| 1626 | - $timezone = EEH_DTT_Helper::get_timezone(); | |
| 1627 | -        if ($timezone === $this->_timezone) { | |
| 1628 | - return ''; | |
| 1629 | - } | |
| 1630 | - $original_timezone = $this->_timezone; | |
| 1631 | - $this->set_timezone($timezone); | |
| 1632 | - $fn = (array) $field_name; | |
| 1633 | - $args = array_merge($fn, (array) $args); | |
| 1634 | -        if (! method_exists($this, $callback)) { | |
| 1635 | - throw new EE_Error( | |
| 1636 | - sprintf( | |
| 1637 | - esc_html__( | |
| 1638 | - 'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist. Please check your spelling', | |
| 1639 | - 'event_espresso' | |
| 1640 | - ), | |
| 1641 | - $callback | |
| 1642 | - ) | |
| 1643 | - ); | |
| 1644 | - } | |
| 1645 | - $args = (array) $args; | |
| 1646 | - $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append; | |
| 1647 | - $this->set_timezone($original_timezone); | |
| 1648 | - return $return; | |
| 1649 | - } | |
| 1650 | - | |
| 1651 | - | |
| 1652 | - /** | |
| 1653 | - * Deletes this model object. | |
| 1654 | - * This calls the `EE_Base_Class::_delete` method. Child classes wishing to change default behaviour should | |
| 1655 | - * override | |
| 1656 | - * `EE_Base_Class::_delete` NOT this class. | |
| 1657 | - * | |
| 1658 | - * @return boolean | int | |
| 1659 | - * @throws ReflectionException | |
| 1660 | - * @throws InvalidArgumentException | |
| 1661 | - * @throws InvalidInterfaceException | |
| 1662 | - * @throws InvalidDataTypeException | |
| 1663 | - * @throws EE_Error | |
| 1664 | - */ | |
| 1665 | - public function delete() | |
| 1666 | -    { | |
| 1667 | - /** | |
| 1668 | - * Called just before the `EE_Base_Class::_delete` method call. | |
| 1669 | - * Note: | |
| 1670 | - * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions | |
| 1671 | - * should be aware that `_delete` may not always result in a permanent delete. | |
| 1672 | - * For example, `EE_Soft_Delete_Base_Class::_delete` | |
| 1673 | - * soft deletes (trash) the object and does not permanently delete it. | |
| 1674 | - * | |
| 1675 | - * @param EE_Base_Class $model_object about to be 'deleted' | |
| 1676 | - */ | |
| 1677 | -        do_action('AHEE__EE_Base_Class__delete__before', $this); | |
| 1678 | - $result = $this->_delete(); | |
| 1679 | - /** | |
| 1680 | - * Called just after the `EE_Base_Class::_delete` method call. | |
| 1681 | - * Note: | |
| 1682 | - * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions | |
| 1683 | - * should be aware that `_delete` may not always result in a permanent delete. | |
| 1684 | - * For example `EE_Soft_Base_Class::_delete` | |
| 1685 | - * soft deletes (trash) the object and does not permanently delete it. | |
| 1686 | - * | |
| 1687 | - * @param EE_Base_Class $model_object that was just 'deleted' | |
| 1688 | - * @param boolean $result | |
| 1689 | - */ | |
| 1690 | -        do_action('AHEE__EE_Base_Class__delete__end', $this, $result); | |
| 1691 | - return $result; | |
| 1692 | - } | |
| 1693 | - | |
| 1694 | - | |
| 1695 | - /** | |
| 1696 | - * Calls the specific delete method for the instantiated class. | |
| 1697 | - * This method is called by the public `EE_Base_Class::delete` method. Any child classes desiring to override | |
| 1698 | - * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT | |
| 1699 | - * `EE_Base_Class::delete` | |
| 1700 | - * | |
| 1701 | - * @return bool|int | |
| 1702 | - * @throws ReflectionException | |
| 1703 | - * @throws InvalidArgumentException | |
| 1704 | - * @throws InvalidInterfaceException | |
| 1705 | - * @throws InvalidDataTypeException | |
| 1706 | - * @throws EE_Error | |
| 1707 | - */ | |
| 1708 | - protected function _delete() | |
| 1709 | -    { | |
| 1710 | - return $this->delete_permanently(); | |
| 1711 | - } | |
| 1712 | - | |
| 1713 | - | |
| 1714 | - /** | |
| 1715 | - * Deletes this model object permanently from db | |
| 1716 | - * (but keep in mind related models may block the delete and return an error) | |
| 1717 | - * | |
| 1718 | - * @return bool | int | |
| 1719 | - * @throws ReflectionException | |
| 1720 | - * @throws InvalidArgumentException | |
| 1721 | - * @throws InvalidInterfaceException | |
| 1722 | - * @throws InvalidDataTypeException | |
| 1723 | - * @throws EE_Error | |
| 1724 | - */ | |
| 1725 | - public function delete_permanently() | |
| 1726 | -    { | |
| 1727 | - /** | |
| 1728 | - * Called just before HARD deleting a model object | |
| 1729 | - * | |
| 1730 | - * @param EE_Base_Class $model_object about to be 'deleted' | |
| 1731 | - */ | |
| 1732 | -        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this); | |
| 1733 | - $model = $this->get_model(); | |
| 1734 | - $result = $model->delete_permanently_by_ID($this->ID()); | |
| 1735 | - $this->refresh_cache_of_related_objects(); | |
| 1736 | - /** | |
| 1737 | - * Called just after HARD deleting a model object | |
| 1738 | - * | |
| 1739 | - * @param EE_Base_Class $model_object that was just 'deleted' | |
| 1740 | - * @param boolean $result | |
| 1741 | - */ | |
| 1742 | -        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result); | |
| 1743 | - return $result; | |
| 1744 | - } | |
| 1745 | - | |
| 1746 | - | |
| 1747 | - /** | |
| 1748 | - * When this model object is deleted, it may still be cached on related model objects. This clears the cache of | |
| 1749 | - * related model objects | |
| 1750 | - * | |
| 1751 | - * @throws ReflectionException | |
| 1752 | - * @throws InvalidArgumentException | |
| 1753 | - * @throws InvalidInterfaceException | |
| 1754 | - * @throws InvalidDataTypeException | |
| 1755 | - * @throws EE_Error | |
| 1756 | - */ | |
| 1757 | - public function refresh_cache_of_related_objects() | |
| 1758 | -    { | |
| 1759 | - $model = $this->get_model(); | |
| 1760 | -        foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 1761 | -            if (! empty($this->_model_relations[ $relation_name ])) { | |
| 1762 | - $related_objects = $this->_model_relations[ $relation_name ]; | |
| 1763 | -                if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 1764 | - // this relation only stores a single model object, not an array | |
| 1765 | - // but let's make it consistent | |
| 1766 | - $related_objects = array($related_objects); | |
| 1767 | - } | |
| 1768 | -                foreach ($related_objects as $related_object) { | |
| 1769 | - // only refresh their cache if they're in memory | |
| 1770 | -                    if ($related_object instanceof EE_Base_Class) { | |
| 1771 | - $related_object->clear_cache( | |
| 1772 | - $model->get_this_model_name(), | |
| 1773 | - $this | |
| 1774 | - ); | |
| 1775 | - } | |
| 1776 | - } | |
| 1777 | - } | |
| 1778 | - } | |
| 1779 | - } | |
| 1780 | - | |
| 1781 | - | |
| 1782 | - /** | |
| 1783 | - * Saves this object to the database. An array may be supplied to set some values on this | |
| 1784 | - * object just before saving. | |
| 1785 | - * | |
| 1786 | - * @access public | |
| 1787 | - * @param array $set_cols_n_values keys are field names, values are their new values, | |
| 1788 | - * if provided during the save() method (often client code will change the fields' | |
| 1789 | - * values before calling save) | |
| 1790 | - * @throws InvalidArgumentException | |
| 1791 | - * @throws InvalidInterfaceException | |
| 1792 | - * @throws InvalidDataTypeException | |
| 1793 | - * @throws EE_Error | |
| 1794 | - * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object | |
| 1795 | - * isn't allowed to persist (as determined by EE_Base_Class::allow_persist()) | |
| 1796 | - * @throws ReflectionException | |
| 1797 | - * @throws ReflectionException | |
| 1798 | - * @throws ReflectionException | |
| 1799 | - */ | |
| 1800 | - public function save($set_cols_n_values = array()) | |
| 1801 | -    { | |
| 1802 | - $model = $this->get_model(); | |
| 1803 | - /** | |
| 1804 | - * Filters the fields we're about to save on the model object | |
| 1805 | - * | |
| 1806 | - * @param array $set_cols_n_values | |
| 1807 | - * @param EE_Base_Class $model_object | |
| 1808 | - */ | |
| 1809 | - $set_cols_n_values = (array) apply_filters( | |
| 1810 | - 'FHEE__EE_Base_Class__save__set_cols_n_values', | |
| 1811 | - $set_cols_n_values, | |
| 1812 | - $this | |
| 1813 | - ); | |
| 1814 | - // set attributes as provided in $set_cols_n_values | |
| 1815 | -        foreach ($set_cols_n_values as $column => $value) { | |
| 1816 | - $this->set($column, $value); | |
| 1817 | - } | |
| 1818 | - // no changes ? then don't do anything | |
| 1819 | -        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) { | |
| 1820 | - return 0; | |
| 1821 | - } | |
| 1822 | - /** | |
| 1823 | - * Saving a model object. | |
| 1824 | - * Before we perform a save, this action is fired. | |
| 1825 | - * | |
| 1826 | - * @param EE_Base_Class $model_object the model object about to be saved. | |
| 1827 | - */ | |
| 1828 | -        do_action('AHEE__EE_Base_Class__save__begin', $this); | |
| 1829 | -        if (! $this->allow_persist()) { | |
| 1830 | - return 0; | |
| 1831 | - } | |
| 1832 | - // now get current attribute values | |
| 1833 | - $save_cols_n_values = $this->_fields; | |
| 1834 | - // if the object already has an ID, update it. Otherwise, insert it | |
| 1835 | - // also: change the assumption about values passed to the model NOT being prepare dby the model object. | |
| 1836 | - // They have been | |
| 1837 | - $old_assumption_concerning_value_preparation = $model | |
| 1838 | - ->get_assumption_concerning_values_already_prepared_by_model_object(); | |
| 1839 | - $model->assume_values_already_prepared_by_model_object(true); | |
| 1840 | - // does this model have an autoincrement PK? | |
| 1841 | -        if ($model->has_primary_key_field()) { | |
| 1842 | -            if ($model->get_primary_key_field()->is_auto_increment()) { | |
| 1843 | - // ok check if it's set, if so: update; if not, insert | |
| 1844 | -                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) { | |
| 1845 | - $results = $model->update_by_ID($save_cols_n_values, $this->ID()); | |
| 1846 | -                } else { | |
| 1847 | - unset($save_cols_n_values[ $model->primary_key_name() ]); | |
| 1848 | - $results = $model->insert($save_cols_n_values); | |
| 1849 | -                    if ($results) { | |
| 1850 | - // if successful, set the primary key | |
| 1851 | - // but don't use the normal SET method, because it will check if | |
| 1852 | - // an item with the same ID exists in the mapper & db, then | |
| 1853 | - // will find it in the db (because we just added it) and THAT object | |
| 1854 | - // will get added to the mapper before we can add this one! | |
| 1855 | - // but if we just avoid using the SET method, all that headache can be avoided | |
| 1856 | - $pk_field_name = $model->primary_key_name(); | |
| 1857 | - $this->_fields[ $pk_field_name ] = $results; | |
| 1858 | - $this->_clear_cached_property($pk_field_name); | |
| 1859 | - $model->add_to_entity_map($this); | |
| 1860 | - $this->_update_cached_related_model_objs_fks(); | |
| 1861 | - } | |
| 1862 | - } | |
| 1863 | -            } else {// PK is NOT auto-increment | |
| 1864 | - // so check if one like it already exists in the db | |
| 1865 | -                if ($model->exists_by_ID($this->ID())) { | |
| 1866 | -                    if (WP_DEBUG && ! $this->in_entity_map()) { | |
| 1867 | - throw new EE_Error( | |
| 1868 | - sprintf( | |
| 1869 | - esc_html__( | |
| 1870 | - 'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s', | |
| 1871 | - 'event_espresso' | |
| 1872 | - ), | |
| 1873 | - get_class($this), | |
| 1874 | - get_class($model) . '::instance()->add_to_entity_map()', | |
| 1875 | - get_class($model) . '::instance()->get_one_by_ID()', | |
| 1876 | - '<br />' | |
| 1877 | - ) | |
| 1878 | - ); | |
| 1879 | - } | |
| 1880 | - $results = $model->update_by_ID($save_cols_n_values, $this->ID()); | |
| 1881 | -                } else { | |
| 1882 | - $results = $model->insert($save_cols_n_values); | |
| 1883 | - $this->_update_cached_related_model_objs_fks(); | |
| 1884 | - } | |
| 1885 | - } | |
| 1886 | -        } else {// there is NO primary key | |
| 1887 | - $already_in_db = false; | |
| 1888 | -            foreach ($model->unique_indexes() as $index) { | |
| 1889 | - $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields()); | |
| 1890 | -                if ($model->exists(array($uniqueness_where_params))) { | |
| 1891 | - $already_in_db = true; | |
| 1892 | - } | |
| 1893 | - } | |
| 1894 | -            if ($already_in_db) { | |
| 1895 | - $combined_pk_fields_n_values = array_intersect_key( | |
| 1896 | - $save_cols_n_values, | |
| 1897 | - $model->get_combined_primary_key_fields() | |
| 1898 | - ); | |
| 1899 | - $results = $model->update( | |
| 1900 | - $save_cols_n_values, | |
| 1901 | - $combined_pk_fields_n_values | |
| 1902 | - ); | |
| 1903 | -            } else { | |
| 1904 | - $results = $model->insert($save_cols_n_values); | |
| 1905 | - } | |
| 1906 | - } | |
| 1907 | - // restore the old assumption about values being prepared by the model object | |
| 1908 | - $model->assume_values_already_prepared_by_model_object( | |
| 1909 | - $old_assumption_concerning_value_preparation | |
| 1910 | - ); | |
| 1911 | - /** | |
| 1912 | - * After saving the model object this action is called | |
| 1913 | - * | |
| 1914 | - * @param EE_Base_Class $model_object which was just saved | |
| 1915 | - * @param boolean|int $results if it were updated, TRUE or FALSE; if it were newly inserted | |
| 1916 | - * the new ID (or 0 if an error occurred and it wasn't updated) | |
| 1917 | - */ | |
| 1918 | -        do_action('AHEE__EE_Base_Class__save__end', $this, $results); | |
| 1919 | - $this->_has_changes = false; | |
| 1920 | - return $results; | |
| 1921 | - } | |
| 1922 | - | |
| 1923 | - | |
| 1924 | - /** | |
| 1925 | - * Updates the foreign key on related models objects pointing to this to have this model object's ID | |
| 1926 | - * as their foreign key. If the cached related model objects already exist in the db, saves them (so that the DB | |
| 1927 | - * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its | |
| 1928 | - * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't | |
| 1929 | - * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the | |
| 1930 | - * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether | |
| 1931 | - * or not they exist in the DB (if they do, their DB records will be automatically updated) | |
| 1932 | - * | |
| 1933 | - * @return void | |
| 1934 | - * @throws ReflectionException | |
| 1935 | - * @throws InvalidArgumentException | |
| 1936 | - * @throws InvalidInterfaceException | |
| 1937 | - * @throws InvalidDataTypeException | |
| 1938 | - * @throws EE_Error | |
| 1939 | - */ | |
| 1940 | - protected function _update_cached_related_model_objs_fks() | |
| 1941 | -    { | |
| 1942 | - $model = $this->get_model(); | |
| 1943 | -        foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 1944 | -            if ($relation_obj instanceof EE_Has_Many_Relation) { | |
| 1945 | -                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) { | |
| 1946 | - $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to( | |
| 1947 | - $model->get_this_model_name() | |
| 1948 | - ); | |
| 1949 | - $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID()); | |
| 1950 | -                    if ($related_model_obj_in_cache->ID()) { | |
| 1951 | - $related_model_obj_in_cache->save(); | |
| 1952 | - } | |
| 1953 | - } | |
| 1954 | - } | |
| 1955 | - } | |
| 1956 | - } | |
| 1957 | - | |
| 1958 | - | |
| 1959 | - /** | |
| 1960 | - * Saves this model object and its NEW cached relations to the database. | |
| 1961 | - * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB. | |
| 1962 | - * In order for that to work, we would need to mark model objects as dirty/clean... | |
| 1963 | - * because otherwise, there's a potential for infinite looping of saving | |
| 1964 | - * Saves the cached related model objects, and ensures the relation between them | |
| 1965 | - * and this object and properly setup | |
| 1966 | - * | |
| 1967 | - * @return int ID of new model object on save; 0 on failure+ | |
| 1968 | - * @throws ReflectionException | |
| 1969 | - * @throws InvalidArgumentException | |
| 1970 | - * @throws InvalidInterfaceException | |
| 1971 | - * @throws InvalidDataTypeException | |
| 1972 | - * @throws EE_Error | |
| 1973 | - */ | |
| 1974 | - public function save_new_cached_related_model_objs() | |
| 1975 | -    { | |
| 1976 | - // make sure this has been saved | |
| 1977 | -        if (! $this->ID()) { | |
| 1978 | - $id = $this->save(); | |
| 1979 | -        } else { | |
| 1980 | - $id = $this->ID(); | |
| 1981 | - } | |
| 1982 | - // now save all the NEW cached model objects (ie they don't exist in the DB) | |
| 1983 | -        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) { | |
| 1984 | -            if ($this->_model_relations[ $relationName ]) { | |
| 1985 | - // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation) | |
| 1986 | - // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)? | |
| 1987 | - /* @var $related_model_obj EE_Base_Class */ | |
| 1988 | -                if ($relationObj instanceof EE_Belongs_To_Relation) { | |
| 1989 | - // add a relation to that relation type (which saves the appropriate thing in the process) | |
| 1990 | - // but ONLY if it DOES NOT exist in the DB | |
| 1991 | - $related_model_obj = $this->_model_relations[ $relationName ]; | |
| 1992 | -                    // if( ! $related_model_obj->ID()){ | |
| 1993 | - $this->_add_relation_to($related_model_obj, $relationName); | |
| 1994 | - $related_model_obj->save_new_cached_related_model_objs(); | |
| 1995 | - // } | |
| 1996 | -                } else { | |
| 1997 | -                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) { | |
| 1998 | - // add a relation to that relation type (which saves the appropriate thing in the process) | |
| 1999 | - // but ONLY if it DOES NOT exist in the DB | |
| 2000 | -                        // if( ! $related_model_obj->ID()){ | |
| 2001 | - $this->_add_relation_to($related_model_obj, $relationName); | |
| 2002 | - $related_model_obj->save_new_cached_related_model_objs(); | |
| 2003 | - // } | |
| 2004 | - } | |
| 2005 | - } | |
| 2006 | - } | |
| 2007 | - } | |
| 2008 | - return $id; | |
| 2009 | - } | |
| 2010 | - | |
| 2011 | - | |
| 2012 | - /** | |
| 2013 | - * for getting a model while instantiated. | |
| 2014 | - * | |
| 2015 | - * @return EEM_Base | EEM_CPT_Base | |
| 2016 | - * @throws ReflectionException | |
| 2017 | - * @throws InvalidArgumentException | |
| 2018 | - * @throws InvalidInterfaceException | |
| 2019 | - * @throws InvalidDataTypeException | |
| 2020 | - * @throws EE_Error | |
| 2021 | - */ | |
| 2022 | - public function get_model() | |
| 2023 | -    { | |
| 2024 | -        if (! $this->_model) { | |
| 2025 | - $modelName = self::_get_model_classname(get_class($this)); | |
| 2026 | - $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone); | |
| 2027 | -        } else { | |
| 2028 | - $this->_model->set_timezone($this->_timezone); | |
| 2029 | - } | |
| 2030 | - return $this->_model; | |
| 2031 | - } | |
| 2032 | - | |
| 2033 | - | |
| 2034 | - /** | |
| 2035 | - * @param $props_n_values | |
| 2036 | - * @param $classname | |
| 2037 | - * @return mixed bool|EE_Base_Class|EEM_CPT_Base | |
| 2038 | - * @throws ReflectionException | |
| 2039 | - * @throws InvalidArgumentException | |
| 2040 | - * @throws InvalidInterfaceException | |
| 2041 | - * @throws InvalidDataTypeException | |
| 2042 | - * @throws EE_Error | |
| 2043 | - */ | |
| 2044 | - protected static function _get_object_from_entity_mapper($props_n_values, $classname) | |
| 2045 | -    { | |
| 2046 | - // TODO: will not work for Term_Relationships because they have no PK! | |
| 2047 | - $primary_id_ref = self::_get_primary_key_name($classname); | |
| 2048 | - if (array_key_exists($primary_id_ref, $props_n_values) | |
| 2049 | - && ! empty($props_n_values[ $primary_id_ref ]) | |
| 2050 | -        ) { | |
| 2051 | - $id = $props_n_values[ $primary_id_ref ]; | |
| 2052 | - return self::_get_model($classname)->get_from_entity_map($id); | |
| 2053 | - } | |
| 2054 | - return false; | |
| 2055 | - } | |
| 2056 | - | |
| 2057 | - | |
| 2058 | - /** | |
| 2059 | - * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for | |
| 2060 | - * the primary key (if present in incoming values). If there is a key in the incoming array that matches the | |
| 2061 | - * primary key for the model AND it is not null, then we check the db. If there's a an object we return it. If not | |
| 2062 | - * we return false. | |
| 2063 | - * | |
| 2064 | - * @param array $props_n_values incoming array of properties and their values | |
| 2065 | - * @param string $classname the classname of the child class | |
| 2066 | - * @param null $timezone | |
| 2067 | - * @param array $date_formats incoming date_formats in an array where the first value is the | |
| 2068 | - * date_format and the second value is the time format | |
| 2069 | - * @return mixed (EE_Base_Class|bool) | |
| 2070 | - * @throws InvalidArgumentException | |
| 2071 | - * @throws InvalidInterfaceException | |
| 2072 | - * @throws InvalidDataTypeException | |
| 2073 | - * @throws EE_Error | |
| 2074 | - * @throws ReflectionException | |
| 2075 | - * @throws ReflectionException | |
| 2076 | - * @throws ReflectionException | |
| 2077 | - */ | |
| 2078 | - protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array()) | |
| 2079 | -    { | |
| 2080 | - $existing = null; | |
| 2081 | - $model = self::_get_model($classname, $timezone); | |
| 2082 | -        if ($model->has_primary_key_field()) { | |
| 2083 | - $primary_id_ref = self::_get_primary_key_name($classname); | |
| 2084 | - if (array_key_exists($primary_id_ref, $props_n_values) | |
| 2085 | - && ! empty($props_n_values[ $primary_id_ref ]) | |
| 2086 | -            ) { | |
| 2087 | - $existing = $model->get_one_by_ID( | |
| 2088 | - $props_n_values[ $primary_id_ref ] | |
| 2089 | - ); | |
| 2090 | - } | |
| 2091 | -        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) { | |
| 2092 | - // no primary key on this model, but there's still a matching item in the DB | |
| 2093 | - $existing = self::_get_model($classname, $timezone)->get_one_by_ID( | |
| 2094 | - self::_get_model($classname, $timezone) | |
| 2095 | - ->get_index_primary_key_string($props_n_values) | |
| 2096 | - ); | |
| 2097 | - } | |
| 2098 | -        if ($existing) { | |
| 2099 | - // set date formats if present before setting values | |
| 2100 | -            if (! empty($date_formats) && is_array($date_formats)) { | |
| 2101 | - $existing->set_date_format($date_formats[0]); | |
| 2102 | - $existing->set_time_format($date_formats[1]); | |
| 2103 | -            } else { | |
| 2104 | - // set default formats for date and time | |
| 2105 | -                $existing->set_date_format(get_option('date_format')); | |
| 2106 | -                $existing->set_time_format(get_option('time_format')); | |
| 2107 | - } | |
| 2108 | -            foreach ($props_n_values as $property => $field_value) { | |
| 2109 | - $existing->set($property, $field_value); | |
| 2110 | - } | |
| 2111 | - return $existing; | |
| 2112 | - } | |
| 2113 | - return false; | |
| 2114 | - } | |
| 2115 | - | |
| 2116 | - | |
| 2117 | - /** | |
| 2118 | - * Gets the EEM_*_Model for this class | |
| 2119 | - * | |
| 2120 | - * @access public now, as this is more convenient | |
| 2121 | - * @param $classname | |
| 2122 | - * @param null $timezone | |
| 2123 | - * @throws ReflectionException | |
| 2124 | - * @throws InvalidArgumentException | |
| 2125 | - * @throws InvalidInterfaceException | |
| 2126 | - * @throws InvalidDataTypeException | |
| 2127 | - * @throws EE_Error | |
| 2128 | - * @return EEM_Base | |
| 2129 | - */ | |
| 2130 | - protected static function _get_model($classname, $timezone = null) | |
| 2131 | -    { | |
| 2132 | - // find model for this class | |
| 2133 | -        if (! $classname) { | |
| 2134 | - throw new EE_Error( | |
| 2135 | - sprintf( | |
| 2136 | - esc_html__( | |
| 2137 | - 'What were you thinking calling _get_model(%s)?? You need to specify the class name', | |
| 2138 | - 'event_espresso' | |
| 2139 | - ), | |
| 2140 | - $classname | |
| 2141 | - ) | |
| 2142 | - ); | |
| 2143 | - } | |
| 2144 | - $modelName = self::_get_model_classname($classname); | |
| 2145 | - return self::_get_model_instance_with_name($modelName, $timezone); | |
| 2146 | - } | |
| 2147 | - | |
| 2148 | - | |
| 2149 | - /** | |
| 2150 | - * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee) | |
| 2151 | - * | |
| 2152 | - * @param string $model_classname | |
| 2153 | - * @param null $timezone | |
| 2154 | - * @return EEM_Base | |
| 2155 | - * @throws ReflectionException | |
| 2156 | - * @throws InvalidArgumentException | |
| 2157 | - * @throws InvalidInterfaceException | |
| 2158 | - * @throws InvalidDataTypeException | |
| 2159 | - * @throws EE_Error | |
| 2160 | - */ | |
| 2161 | - protected static function _get_model_instance_with_name($model_classname, $timezone = null) | |
| 2162 | -    { | |
| 2163 | -        $model_classname = str_replace('EEM_', '', $model_classname); | |
| 2164 | - $model = EE_Registry::instance()->load_model($model_classname); | |
| 2165 | - $model->set_timezone($timezone); | |
| 2166 | - return $model; | |
| 2167 | - } | |
| 2168 | - | |
| 2169 | - | |
| 2170 | - /** | |
| 2171 | - * If a model name is provided (eg Registration), gets the model classname for that model. | |
| 2172 | - * Also works if a model class's classname is provided (eg EE_Registration). | |
| 2173 | - * | |
| 2174 | - * @param null $model_name | |
| 2175 | - * @return string like EEM_Attendee | |
| 2176 | - */ | |
| 2177 | - private static function _get_model_classname($model_name = null) | |
| 2178 | -    { | |
| 2179 | -        if (strpos($model_name, 'EE_') === 0) { | |
| 2180 | -            $model_classname = str_replace('EE_', 'EEM_', $model_name); | |
| 2181 | -        } else { | |
| 2182 | - $model_classname = 'EEM_' . $model_name; | |
| 2183 | - } | |
| 2184 | - return $model_classname; | |
| 2185 | - } | |
| 2186 | - | |
| 2187 | - | |
| 2188 | - /** | |
| 2189 | - * returns the name of the primary key attribute | |
| 2190 | - * | |
| 2191 | - * @param null $classname | |
| 2192 | - * @throws ReflectionException | |
| 2193 | - * @throws InvalidArgumentException | |
| 2194 | - * @throws InvalidInterfaceException | |
| 2195 | - * @throws InvalidDataTypeException | |
| 2196 | - * @throws EE_Error | |
| 2197 | - * @return string | |
| 2198 | - */ | |
| 2199 | - protected static function _get_primary_key_name($classname = null) | |
| 2200 | -    { | |
| 2201 | -        if (! $classname) { | |
| 2202 | - throw new EE_Error( | |
| 2203 | - sprintf( | |
| 2204 | -                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'), | |
| 2205 | - $classname | |
| 2206 | - ) | |
| 2207 | - ); | |
| 2208 | - } | |
| 2209 | - return self::_get_model($classname)->get_primary_key_field()->get_name(); | |
| 2210 | - } | |
| 2211 | - | |
| 2212 | - | |
| 2213 | - /** | |
| 2214 | - * Gets the value of the primary key. | |
| 2215 | - * If the object hasn't yet been saved, it should be whatever the model field's default was | |
| 2216 | - * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value | |
| 2217 | - * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL). | |
| 2218 | - * | |
| 2219 | - * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string | |
| 2220 | - * @throws ReflectionException | |
| 2221 | - * @throws InvalidArgumentException | |
| 2222 | - * @throws InvalidInterfaceException | |
| 2223 | - * @throws InvalidDataTypeException | |
| 2224 | - * @throws EE_Error | |
| 2225 | - */ | |
| 2226 | - public function ID() | |
| 2227 | -    { | |
| 2228 | - $model = $this->get_model(); | |
| 2229 | - // now that we know the name of the variable, use a variable variable to get its value and return its | |
| 2230 | -        if ($model->has_primary_key_field()) { | |
| 2231 | - return $this->_fields[ $model->primary_key_name() ]; | |
| 2232 | - } | |
| 2233 | - return $model->get_index_primary_key_string($this->_fields); | |
| 2234 | - } | |
| 2235 | - | |
| 2236 | - | |
| 2237 | - /** | |
| 2238 | - * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current | |
| 2239 | - * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE | |
| 2240 | - * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing | |
| 2241 | - * | |
| 2242 | - * @param mixed $otherObjectModelObjectOrID EE_Base_Class or the ID of the other object | |
| 2243 | - * @param string $relationName eg 'Events','Question',etc. | |
| 2244 | - * an attendee to a group, you also want to specify which role they | |
| 2245 | - * will have in that group. So you would use this parameter to | |
| 2246 | -     *                                                 specify array('role-column-name'=>'role-id') | |
| 2247 | - * @param array $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that | |
| 2248 | - * allow you to further constrict the relation to being added. | |
| 2249 | - * However, keep in mind that the columns (keys) given must match a | |
| 2250 | - * column on the JOIN table and currently only the HABTM models | |
| 2251 | - * accept these additional conditions. Also remember that if an | |
| 2252 | - * exact match isn't found for these extra cols/val pairs, then a | |
| 2253 | - * NEW row is created in the join table. | |
| 2254 | - * @param null $cache_id | |
| 2255 | - * @throws ReflectionException | |
| 2256 | - * @throws InvalidArgumentException | |
| 2257 | - * @throws InvalidInterfaceException | |
| 2258 | - * @throws InvalidDataTypeException | |
| 2259 | - * @throws EE_Error | |
| 2260 | - * @return EE_Base_Class the object the relation was added to | |
| 2261 | - */ | |
| 2262 | - public function _add_relation_to( | |
| 2263 | - $otherObjectModelObjectOrID, | |
| 2264 | - $relationName, | |
| 2265 | - $extra_join_model_fields_n_values = array(), | |
| 2266 | - $cache_id = null | |
| 2267 | -    ) { | |
| 2268 | - $model = $this->get_model(); | |
| 2269 | - // if this thing exists in the DB, save the relation to the DB | |
| 2270 | -        if ($this->ID()) { | |
| 2271 | - $otherObject = $model->add_relationship_to( | |
| 2272 | - $this, | |
| 2273 | - $otherObjectModelObjectOrID, | |
| 2274 | - $relationName, | |
| 2275 | - $extra_join_model_fields_n_values | |
| 2276 | - ); | |
| 2277 | - // clear cache so future get_many_related and get_first_related() return new results. | |
| 2278 | - $this->clear_cache($relationName, $otherObject, true); | |
| 2279 | -            if ($otherObject instanceof EE_Base_Class) { | |
| 2280 | - $otherObject->clear_cache($model->get_this_model_name(), $this); | |
| 2281 | - } | |
| 2282 | -        } else { | |
| 2283 | - // this thing doesn't exist in the DB, so just cache it | |
| 2284 | -            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) { | |
| 2285 | - throw new EE_Error( | |
| 2286 | - sprintf( | |
| 2287 | - esc_html__( | |
| 2288 | - 'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s', | |
| 2289 | - 'event_espresso' | |
| 2290 | - ), | |
| 2291 | - $otherObjectModelObjectOrID, | |
| 2292 | - get_class($this) | |
| 2293 | - ) | |
| 2294 | - ); | |
| 2295 | - } | |
| 2296 | - $otherObject = $otherObjectModelObjectOrID; | |
| 2297 | - $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id); | |
| 2298 | - } | |
| 2299 | -        if ($otherObject instanceof EE_Base_Class) { | |
| 2300 | - // fix the reciprocal relation too | |
| 2301 | -            if ($otherObject->ID()) { | |
| 2302 | - // its saved so assumed relations exist in the DB, so we can just | |
| 2303 | - // clear the cache so future queries use the updated info in the DB | |
| 2304 | - $otherObject->clear_cache( | |
| 2305 | - $model->get_this_model_name(), | |
| 2306 | - null, | |
| 2307 | - true | |
| 2308 | - ); | |
| 2309 | -            } else { | |
| 2310 | - // it's not saved, so it caches relations like this | |
| 2311 | - $otherObject->cache($model->get_this_model_name(), $this); | |
| 2312 | - } | |
| 2313 | - } | |
| 2314 | - return $otherObject; | |
| 2315 | - } | |
| 2316 | - | |
| 2317 | - | |
| 2318 | - /** | |
| 2319 | - * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current | |
| 2320 | - * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE | |
| 2321 | - * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing | |
| 2322 | - * from the cache | |
| 2323 | - * | |
| 2324 | - * @param mixed $otherObjectModelObjectOrID | |
| 2325 | - * EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved | |
| 2326 | - * to the DB yet | |
| 2327 | - * @param string $relationName | |
| 2328 | - * @param array $where_query | |
| 2329 | - * You can optionally include an array of key=>value pairs that allow you to further constrict the | |
| 2330 | - * relation to being added. However, keep in mind that the columns (keys) given must match a column | |
| 2331 | - * on the JOIN table and currently only the HABTM models accept these additional conditions. Also | |
| 2332 | - * remember that if an exact match isn't found for these extra cols/val pairs, then no row is | |
| 2333 | - * deleted. | |
| 2334 | - * @return EE_Base_Class the relation was removed from | |
| 2335 | - * @throws ReflectionException | |
| 2336 | - * @throws InvalidArgumentException | |
| 2337 | - * @throws InvalidInterfaceException | |
| 2338 | - * @throws InvalidDataTypeException | |
| 2339 | - * @throws EE_Error | |
| 2340 | - */ | |
| 2341 | - public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array()) | |
| 2342 | -    { | |
| 2343 | -        if ($this->ID()) { | |
| 2344 | - // if this exists in the DB, save the relation change to the DB too | |
| 2345 | - $otherObject = $this->get_model()->remove_relationship_to( | |
| 2346 | - $this, | |
| 2347 | - $otherObjectModelObjectOrID, | |
| 2348 | - $relationName, | |
| 2349 | - $where_query | |
| 2350 | - ); | |
| 2351 | - $this->clear_cache( | |
| 2352 | - $relationName, | |
| 2353 | - $otherObject | |
| 2354 | - ); | |
| 2355 | -        } else { | |
| 2356 | - // this doesn't exist in the DB, just remove it from the cache | |
| 2357 | - $otherObject = $this->clear_cache( | |
| 2358 | - $relationName, | |
| 2359 | - $otherObjectModelObjectOrID | |
| 2360 | - ); | |
| 2361 | - } | |
| 2362 | -        if ($otherObject instanceof EE_Base_Class) { | |
| 2363 | - $otherObject->clear_cache( | |
| 2364 | - $this->get_model()->get_this_model_name(), | |
| 2365 | - $this | |
| 2366 | - ); | |
| 2367 | - } | |
| 2368 | - return $otherObject; | |
| 2369 | - } | |
| 2370 | - | |
| 2371 | - | |
| 2372 | - /** | |
| 2373 | - * Removes ALL the related things for the $relationName. | |
| 2374 | - * | |
| 2375 | - * @param string $relationName | |
| 2376 | - * @param array $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions | |
| 2377 | - * @return EE_Base_Class | |
| 2378 | - * @throws ReflectionException | |
| 2379 | - * @throws InvalidArgumentException | |
| 2380 | - * @throws InvalidInterfaceException | |
| 2381 | - * @throws InvalidDataTypeException | |
| 2382 | - * @throws EE_Error | |
| 2383 | - */ | |
| 2384 | - public function _remove_relations($relationName, $where_query_params = array()) | |
| 2385 | -    { | |
| 2386 | -        if ($this->ID()) { | |
| 2387 | - // if this exists in the DB, save the relation change to the DB too | |
| 2388 | - $otherObjects = $this->get_model()->remove_relations( | |
| 2389 | - $this, | |
| 2390 | - $relationName, | |
| 2391 | - $where_query_params | |
| 2392 | - ); | |
| 2393 | - $this->clear_cache( | |
| 2394 | - $relationName, | |
| 2395 | - null, | |
| 2396 | - true | |
| 2397 | - ); | |
| 2398 | -        } else { | |
| 2399 | - // this doesn't exist in the DB, just remove it from the cache | |
| 2400 | - $otherObjects = $this->clear_cache( | |
| 2401 | - $relationName, | |
| 2402 | - null, | |
| 2403 | - true | |
| 2404 | - ); | |
| 2405 | - } | |
| 2406 | -        if (is_array($otherObjects)) { | |
| 2407 | -            foreach ($otherObjects as $otherObject) { | |
| 2408 | - $otherObject->clear_cache( | |
| 2409 | - $this->get_model()->get_this_model_name(), | |
| 2410 | - $this | |
| 2411 | - ); | |
| 2412 | - } | |
| 2413 | - } | |
| 2414 | - return $otherObjects; | |
| 2415 | - } | |
| 2416 | - | |
| 2417 | - | |
| 2418 | - /** | |
| 2419 | - * Gets all the related model objects of the specified type. Eg, if the current class if | |
| 2420 | -     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the | |
| 2421 | - * EE_Registration objects which related to this event. Note: by default, we remove the "default query params" | |
| 2422 | - * because we want to get even deleted items etc. | |
| 2423 | - * | |
| 2424 | - * @param string $relationName key in the model's _model_relations array | |
| 2425 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions | |
| 2426 | - * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary | |
| 2427 | - * keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these | |
| 2428 | - * results if you want IDs | |
| 2429 | - * @throws ReflectionException | |
| 2430 | - * @throws InvalidArgumentException | |
| 2431 | - * @throws InvalidInterfaceException | |
| 2432 | - * @throws InvalidDataTypeException | |
| 2433 | - * @throws EE_Error | |
| 2434 | - */ | |
| 2435 | - public function get_many_related($relationName, $query_params = array()) | |
| 2436 | -    { | |
| 2437 | -        if ($this->ID()) { | |
| 2438 | - // this exists in the DB, so get the related things from either the cache or the DB | |
| 2439 | - // if there are query parameters, forget about caching the related model objects. | |
| 2440 | -            if ($query_params) { | |
| 2441 | - $related_model_objects = $this->get_model()->get_all_related( | |
| 2442 | - $this, | |
| 2443 | - $relationName, | |
| 2444 | - $query_params | |
| 2445 | - ); | |
| 2446 | -            } else { | |
| 2447 | - // did we already cache the result of this query? | |
| 2448 | - $cached_results = $this->get_all_from_cache($relationName); | |
| 2449 | -                if (! $cached_results) { | |
| 2450 | - $related_model_objects = $this->get_model()->get_all_related( | |
| 2451 | - $this, | |
| 2452 | - $relationName, | |
| 2453 | - $query_params | |
| 2454 | - ); | |
| 2455 | - // if no query parameters were passed, then we got all the related model objects | |
| 2456 | - // for that relation. We can cache them then. | |
| 2457 | -                    foreach ($related_model_objects as $related_model_object) { | |
| 2458 | - $this->cache($relationName, $related_model_object); | |
| 2459 | - } | |
| 2460 | -                } else { | |
| 2461 | - $related_model_objects = $cached_results; | |
| 2462 | - } | |
| 2463 | - } | |
| 2464 | -        } else { | |
| 2465 | - // this doesn't exist in the DB, so just get the related things from the cache | |
| 2466 | - $related_model_objects = $this->get_all_from_cache($relationName); | |
| 2467 | - } | |
| 2468 | - return $related_model_objects; | |
| 2469 | - } | |
| 2470 | - | |
| 2471 | - | |
| 2472 | - /** | |
| 2473 | - * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default, | |
| 2474 | - * unless otherwise specified in the $query_params | |
| 2475 | - * | |
| 2476 | - * @param string $relation_name model_name like 'Event', or 'Registration' | |
| 2477 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2478 | - * @param string $field_to_count name of field to count by. By default, uses primary key | |
| 2479 | - * @param bool $distinct if we want to only count the distinct values for the column then you can trigger | |
| 2480 | - * that by the setting $distinct to TRUE; | |
| 2481 | - * @return int | |
| 2482 | - * @throws ReflectionException | |
| 2483 | - * @throws InvalidArgumentException | |
| 2484 | - * @throws InvalidInterfaceException | |
| 2485 | - * @throws InvalidDataTypeException | |
| 2486 | - * @throws EE_Error | |
| 2487 | - */ | |
| 2488 | - public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false) | |
| 2489 | -    { | |
| 2490 | - return $this->get_model()->count_related( | |
| 2491 | - $this, | |
| 2492 | - $relation_name, | |
| 2493 | - $query_params, | |
| 2494 | - $field_to_count, | |
| 2495 | - $distinct | |
| 2496 | - ); | |
| 2497 | - } | |
| 2498 | - | |
| 2499 | - | |
| 2500 | - /** | |
| 2501 | - * Instead of getting the related model objects, simply sums up the values of the specified field. | |
| 2502 | - * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params | |
| 2503 | - * | |
| 2504 | - * @param string $relation_name model_name like 'Event', or 'Registration' | |
| 2505 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2506 | - * @param string $field_to_sum name of field to count by. | |
| 2507 | - * By default, uses primary key | |
| 2508 | - * (which doesn't make much sense, so you should probably change it) | |
| 2509 | - * @return int | |
| 2510 | - * @throws ReflectionException | |
| 2511 | - * @throws InvalidArgumentException | |
| 2512 | - * @throws InvalidInterfaceException | |
| 2513 | - * @throws InvalidDataTypeException | |
| 2514 | - * @throws EE_Error | |
| 2515 | - */ | |
| 2516 | - public function sum_related($relation_name, $query_params = array(), $field_to_sum = null) | |
| 2517 | -    { | |
| 2518 | - return $this->get_model()->sum_related( | |
| 2519 | - $this, | |
| 2520 | - $relation_name, | |
| 2521 | - $query_params, | |
| 2522 | - $field_to_sum | |
| 2523 | - ); | |
| 2524 | - } | |
| 2525 | - | |
| 2526 | - | |
| 2527 | - /** | |
| 2528 | - * Gets the first (ie, one) related model object of the specified type. | |
| 2529 | - * | |
| 2530 | - * @param string $relationName key in the model's _model_relations array | |
| 2531 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2532 | - * @return EE_Base_Class (not an array, a single object) | |
| 2533 | - * @throws ReflectionException | |
| 2534 | - * @throws InvalidArgumentException | |
| 2535 | - * @throws InvalidInterfaceException | |
| 2536 | - * @throws InvalidDataTypeException | |
| 2537 | - * @throws EE_Error | |
| 2538 | - */ | |
| 2539 | - public function get_first_related($relationName, $query_params = array()) | |
| 2540 | -    { | |
| 2541 | - $model = $this->get_model(); | |
| 2542 | -        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB | |
| 2543 | - // if they've provided some query parameters, don't bother trying to cache the result | |
| 2544 | - // also make sure we're not caching the result of get_first_related | |
| 2545 | - // on a relation which should have an array of objects (because the cache might have an array of objects) | |
| 2546 | - if ($query_params | |
| 2547 | - || ! $model->related_settings_for($relationName) | |
| 2548 | - instanceof | |
| 2549 | - EE_Belongs_To_Relation | |
| 2550 | -            ) { | |
| 2551 | - $related_model_object = $model->get_first_related( | |
| 2552 | - $this, | |
| 2553 | - $relationName, | |
| 2554 | - $query_params | |
| 2555 | - ); | |
| 2556 | -            } else { | |
| 2557 | - // first, check if we've already cached the result of this query | |
| 2558 | - $cached_result = $this->get_one_from_cache($relationName); | |
| 2559 | -                if (! $cached_result) { | |
| 2560 | - $related_model_object = $model->get_first_related( | |
| 2561 | - $this, | |
| 2562 | - $relationName, | |
| 2563 | - $query_params | |
| 2564 | - ); | |
| 2565 | - $this->cache($relationName, $related_model_object); | |
| 2566 | -                } else { | |
| 2567 | - $related_model_object = $cached_result; | |
| 2568 | - } | |
| 2569 | - } | |
| 2570 | -        } else { | |
| 2571 | - $related_model_object = null; | |
| 2572 | - // this doesn't exist in the Db, | |
| 2573 | - // but maybe the relation is of type belongs to, and so the related thing might | |
| 2574 | -            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) { | |
| 2575 | - $related_model_object = $model->get_first_related( | |
| 2576 | - $this, | |
| 2577 | - $relationName, | |
| 2578 | - $query_params | |
| 2579 | - ); | |
| 2580 | - } | |
| 2581 | - // this doesn't exist in the DB and apparently the thing it belongs to doesn't either, | |
| 2582 | - // just get what's cached on this object | |
| 2583 | -            if (! $related_model_object) { | |
| 2584 | - $related_model_object = $this->get_one_from_cache($relationName); | |
| 2585 | - } | |
| 2586 | - } | |
| 2587 | - return $related_model_object; | |
| 2588 | - } | |
| 2589 | - | |
| 2590 | - | |
| 2591 | - /** | |
| 2592 | - * Does a delete on all related objects of type $relationName and removes | |
| 2593 | - * the current model object's relation to them. If they can't be deleted (because | |
| 2594 | - * of blocking related model objects) does nothing. If the related model objects are | |
| 2595 | - * soft-deletable, they will be soft-deleted regardless of related blocking model objects. | |
| 2596 | - * If this model object doesn't exist yet in the DB, just removes its related things | |
| 2597 | - * | |
| 2598 | - * @param string $relationName | |
| 2599 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2600 | - * @return int how many deleted | |
| 2601 | - * @throws ReflectionException | |
| 2602 | - * @throws InvalidArgumentException | |
| 2603 | - * @throws InvalidInterfaceException | |
| 2604 | - * @throws InvalidDataTypeException | |
| 2605 | - * @throws EE_Error | |
| 2606 | - */ | |
| 2607 | - public function delete_related($relationName, $query_params = array()) | |
| 2608 | -    { | |
| 2609 | -        if ($this->ID()) { | |
| 2610 | - $count = $this->get_model()->delete_related( | |
| 2611 | - $this, | |
| 2612 | - $relationName, | |
| 2613 | - $query_params | |
| 2614 | - ); | |
| 2615 | -        } else { | |
| 2616 | - $count = count($this->get_all_from_cache($relationName)); | |
| 2617 | - $this->clear_cache($relationName, null, true); | |
| 2618 | - } | |
| 2619 | - return $count; | |
| 2620 | - } | |
| 2621 | - | |
| 2622 | - | |
| 2623 | - /** | |
| 2624 | - * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes | |
| 2625 | - * the current model object's relation to them. If they can't be deleted (because | |
| 2626 | - * of blocking related model objects) just does a soft delete on it instead, if possible. | |
| 2627 | - * If the related thing isn't a soft-deletable model object, this function is identical | |
| 2628 | - * to delete_related(). If this model object doesn't exist in the DB, just remove its related things | |
| 2629 | - * | |
| 2630 | - * @param string $relationName | |
| 2631 | - * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2632 | - * @return int how many deleted (including those soft deleted) | |
| 2633 | - * @throws ReflectionException | |
| 2634 | - * @throws InvalidArgumentException | |
| 2635 | - * @throws InvalidInterfaceException | |
| 2636 | - * @throws InvalidDataTypeException | |
| 2637 | - * @throws EE_Error | |
| 2638 | - */ | |
| 2639 | - public function delete_related_permanently($relationName, $query_params = array()) | |
| 2640 | -    { | |
| 2641 | -        if ($this->ID()) { | |
| 2642 | - $count = $this->get_model()->delete_related_permanently( | |
| 2643 | - $this, | |
| 2644 | - $relationName, | |
| 2645 | - $query_params | |
| 2646 | - ); | |
| 2647 | -        } else { | |
| 2648 | - $count = count($this->get_all_from_cache($relationName)); | |
| 2649 | - } | |
| 2650 | - $this->clear_cache($relationName, null, true); | |
| 2651 | - return $count; | |
| 2652 | - } | |
| 2653 | - | |
| 2654 | - | |
| 2655 | - /** | |
| 2656 | - * is_set | |
| 2657 | - * Just a simple utility function children can use for checking if property exists | |
| 2658 | - * | |
| 2659 | - * @access public | |
| 2660 | - * @param string $field_name property to check | |
| 2661 | - * @return bool TRUE if existing,FALSE if not. | |
| 2662 | - */ | |
| 2663 | - public function is_set($field_name) | |
| 2664 | -    { | |
| 2665 | - return isset($this->_fields[ $field_name ]); | |
| 2666 | - } | |
| 2667 | - | |
| 2668 | - | |
| 2669 | - /** | |
| 2670 | - * Just a simple utility function children can use for checking if property (or properties) exists and throwing an | |
| 2671 | - * EE_Error exception if they don't | |
| 2672 | - * | |
| 2673 | - * @param mixed (string|array) $properties properties to check | |
| 2674 | - * @throws EE_Error | |
| 2675 | - * @return bool TRUE if existing, throw EE_Error if not. | |
| 2676 | - */ | |
| 2677 | - protected function _property_exists($properties) | |
| 2678 | -    { | |
| 2679 | -        foreach ((array) $properties as $property_name) { | |
| 2680 | - // first make sure this property exists | |
| 2681 | -            if (! $this->_fields[ $property_name ]) { | |
| 2682 | - throw new EE_Error( | |
| 2683 | - sprintf( | |
| 2684 | - esc_html__( | |
| 2685 | - 'Trying to retrieve a non-existent property (%s). Double check the spelling please', | |
| 2686 | - 'event_espresso' | |
| 2687 | - ), | |
| 2688 | - $property_name | |
| 2689 | - ) | |
| 2690 | - ); | |
| 2691 | - } | |
| 2692 | - } | |
| 2693 | - return true; | |
| 2694 | - } | |
| 2695 | - | |
| 2696 | - | |
| 2697 | - /** | |
| 2698 | - * This simply returns an array of model fields for this object | |
| 2699 | - * | |
| 2700 | - * @return array | |
| 2701 | - * @throws ReflectionException | |
| 2702 | - * @throws InvalidArgumentException | |
| 2703 | - * @throws InvalidInterfaceException | |
| 2704 | - * @throws InvalidDataTypeException | |
| 2705 | - * @throws EE_Error | |
| 2706 | - */ | |
| 2707 | - public function model_field_array() | |
| 2708 | -    { | |
| 2709 | - $fields = $this->get_model()->field_settings(false); | |
| 2710 | - $properties = array(); | |
| 2711 | - // remove prepended underscore | |
| 2712 | -        foreach ($fields as $field_name => $settings) { | |
| 2713 | - $properties[ $field_name ] = $this->get($field_name); | |
| 2714 | - } | |
| 2715 | - return $properties; | |
| 2716 | - } | |
| 2717 | - | |
| 2718 | - | |
| 2719 | - /** | |
| 2720 | - * Very handy general function to allow for plugins to extend any child of EE_Base_Class. | |
| 2721 | - * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called | |
| 2722 | - * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. | |
| 2723 | - * Instead of requiring a plugin to extend the EE_Base_Class | |
| 2724 | - * (which works fine is there's only 1 plugin, but when will that happen?) | |
| 2725 | -     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' | |
| 2726 | - * (eg, filters_hook_espresso__EE_Answer__my_great_function) | |
| 2727 | - * and accepts 2 arguments: the object on which the function was called, | |
| 2728 | - * and an array of the original arguments passed to the function. | |
| 2729 | - * Whatever their callback function returns will be returned by this function. | |
| 2730 | - * Example: in functions.php (or in a plugin): | |
| 2731 | -     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); | |
| 2732 | -     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){ | |
| 2733 | -     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray); | |
| 2734 | - * return $previousReturnValue.$returnString; | |
| 2735 | - * } | |
| 2736 | -     * require('EE_Answer.class.php'); | |
| 2737 | -     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42')); | |
| 2738 | -     * echo $answer->my_callback('monkeys',100); | |
| 2739 | - * //will output "you called my_callback! and passed args:monkeys,100" | |
| 2740 | - * | |
| 2741 | - * @param string $methodName name of method which was called on a child of EE_Base_Class, but which | |
| 2742 | - * @param array $args array of original arguments passed to the function | |
| 2743 | - * @throws EE_Error | |
| 2744 | - * @return mixed whatever the plugin which calls add_filter decides | |
| 2745 | - */ | |
| 2746 | - public function __call($methodName, $args) | |
| 2747 | -    { | |
| 2748 | - $className = get_class($this); | |
| 2749 | -        $tagName = "FHEE__{$className}__{$methodName}"; | |
| 2750 | -        if (! has_filter($tagName)) { | |
| 2751 | - throw new EE_Error( | |
| 2752 | - sprintf( | |
| 2753 | - esc_html__( | |
| 2754 | -                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}", | |
| 2755 | - 'event_espresso' | |
| 2756 | - ), | |
| 2757 | - $methodName, | |
| 2758 | - $className, | |
| 2759 | - $tagName | |
| 2760 | - ) | |
| 2761 | - ); | |
| 2762 | - } | |
| 2763 | - return apply_filters($tagName, null, $this, $args); | |
| 2764 | - } | |
| 2765 | - | |
| 2766 | - | |
| 2767 | - /** | |
| 2768 | - * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value. | |
| 2769 | - * A $previous_value can be specified in case there are many meta rows with the same key | |
| 2770 | - * | |
| 2771 | - * @param string $meta_key | |
| 2772 | - * @param mixed $meta_value | |
| 2773 | - * @param mixed $previous_value | |
| 2774 | - * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row) | |
| 2775 | - * NOTE: if the values haven't changed, returns 0 | |
| 2776 | - * @throws InvalidArgumentException | |
| 2777 | - * @throws InvalidInterfaceException | |
| 2778 | - * @throws InvalidDataTypeException | |
| 2779 | - * @throws EE_Error | |
| 2780 | - * @throws ReflectionException | |
| 2781 | - */ | |
| 2782 | - public function update_extra_meta($meta_key, $meta_value, $previous_value = null) | |
| 2783 | -    { | |
| 2784 | - $query_params = array( | |
| 2785 | - array( | |
| 2786 | - 'EXM_key' => $meta_key, | |
| 2787 | - 'OBJ_ID' => $this->ID(), | |
| 2788 | - 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2789 | - ), | |
| 2790 | - ); | |
| 2791 | -        if ($previous_value !== null) { | |
| 2792 | - $query_params[0]['EXM_value'] = $meta_value; | |
| 2793 | - } | |
| 2794 | - $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params); | |
| 2795 | -        if (! $existing_rows_like_that) { | |
| 2796 | - return $this->add_extra_meta($meta_key, $meta_value); | |
| 2797 | - } | |
| 2798 | -        foreach ($existing_rows_like_that as $existing_row) { | |
| 2799 | -            $existing_row->save(array('EXM_value' => $meta_value)); | |
| 2800 | - } | |
| 2801 | - return count($existing_rows_like_that); | |
| 2802 | - } | |
| 2803 | - | |
| 2804 | - | |
| 2805 | - /** | |
| 2806 | - * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check | |
| 2807 | - * no other extra meta for this model object have the same key. Returns TRUE if the | |
| 2808 | - * extra meta row was entered, false if not | |
| 2809 | - * | |
| 2810 | - * @param string $meta_key | |
| 2811 | - * @param mixed $meta_value | |
| 2812 | - * @param boolean $unique | |
| 2813 | - * @return boolean | |
| 2814 | - * @throws InvalidArgumentException | |
| 2815 | - * @throws InvalidInterfaceException | |
| 2816 | - * @throws InvalidDataTypeException | |
| 2817 | - * @throws EE_Error | |
| 2818 | - * @throws ReflectionException | |
| 2819 | - * @throws ReflectionException | |
| 2820 | - */ | |
| 2821 | - public function add_extra_meta($meta_key, $meta_value, $unique = false) | |
| 2822 | -    { | |
| 2823 | -        if ($unique) { | |
| 2824 | - $existing_extra_meta = EEM_Extra_Meta::instance()->get_one( | |
| 2825 | - array( | |
| 2826 | - array( | |
| 2827 | - 'EXM_key' => $meta_key, | |
| 2828 | - 'OBJ_ID' => $this->ID(), | |
| 2829 | - 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2830 | - ), | |
| 2831 | - ) | |
| 2832 | - ); | |
| 2833 | -            if ($existing_extra_meta) { | |
| 2834 | - return false; | |
| 2835 | - } | |
| 2836 | - } | |
| 2837 | - $new_extra_meta = EE_Extra_Meta::new_instance( | |
| 2838 | - array( | |
| 2839 | - 'EXM_key' => $meta_key, | |
| 2840 | - 'EXM_value' => $meta_value, | |
| 2841 | - 'OBJ_ID' => $this->ID(), | |
| 2842 | - 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2843 | - ) | |
| 2844 | - ); | |
| 2845 | - $new_extra_meta->save(); | |
| 2846 | - return true; | |
| 2847 | - } | |
| 2848 | - | |
| 2849 | - | |
| 2850 | - /** | |
| 2851 | - * Deletes all the extra meta rows for this record as specified by key. If $meta_value | |
| 2852 | - * is specified, only deletes extra meta records with that value. | |
| 2853 | - * | |
| 2854 | - * @param string $meta_key | |
| 2855 | - * @param mixed $meta_value | |
| 2856 | - * @return int number of extra meta rows deleted | |
| 2857 | - * @throws InvalidArgumentException | |
| 2858 | - * @throws InvalidInterfaceException | |
| 2859 | - * @throws InvalidDataTypeException | |
| 2860 | - * @throws EE_Error | |
| 2861 | - * @throws ReflectionException | |
| 2862 | - */ | |
| 2863 | - public function delete_extra_meta($meta_key, $meta_value = null) | |
| 2864 | -    { | |
| 2865 | - $query_params = array( | |
| 2866 | - array( | |
| 2867 | - 'EXM_key' => $meta_key, | |
| 2868 | - 'OBJ_ID' => $this->ID(), | |
| 2869 | - 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2870 | - ), | |
| 2871 | - ); | |
| 2872 | -        if ($meta_value !== null) { | |
| 2873 | - $query_params[0]['EXM_value'] = $meta_value; | |
| 2874 | - } | |
| 2875 | - return EEM_Extra_Meta::instance()->delete($query_params); | |
| 2876 | - } | |
| 2877 | - | |
| 2878 | - | |
| 2879 | - /** | |
| 2880 | - * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise | |
| 2881 | - * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation. | |
| 2882 | - * You can specify $default is case you haven't found the extra meta | |
| 2883 | - * | |
| 2884 | - * @param string $meta_key | |
| 2885 | - * @param boolean $single | |
| 2886 | - * @param mixed $default if we don't find anything, what should we return? | |
| 2887 | - * @return mixed single value if $single; array if ! $single | |
| 2888 | - * @throws ReflectionException | |
| 2889 | - * @throws InvalidArgumentException | |
| 2890 | - * @throws InvalidInterfaceException | |
| 2891 | - * @throws InvalidDataTypeException | |
| 2892 | - * @throws EE_Error | |
| 2893 | - */ | |
| 2894 | - public function get_extra_meta($meta_key, $single = false, $default = null) | |
| 2895 | -    { | |
| 2896 | -        if ($single) { | |
| 2897 | - $result = $this->get_first_related( | |
| 2898 | - 'Extra_Meta', | |
| 2899 | -                array(array('EXM_key' => $meta_key)) | |
| 2900 | - ); | |
| 2901 | -            if ($result instanceof EE_Extra_Meta) { | |
| 2902 | - return $result->value(); | |
| 2903 | - } | |
| 2904 | -        } else { | |
| 2905 | - $results = $this->get_many_related( | |
| 2906 | - 'Extra_Meta', | |
| 2907 | -                array(array('EXM_key' => $meta_key)) | |
| 2908 | - ); | |
| 2909 | -            if ($results) { | |
| 2910 | - $values = array(); | |
| 2911 | -                foreach ($results as $result) { | |
| 2912 | -                    if ($result instanceof EE_Extra_Meta) { | |
| 2913 | - $values[ $result->ID() ] = $result->value(); | |
| 2914 | - } | |
| 2915 | - } | |
| 2916 | - return $values; | |
| 2917 | - } | |
| 2918 | - } | |
| 2919 | - // if nothing discovered yet return default. | |
| 2920 | - return apply_filters( | |
| 2921 | - 'FHEE__EE_Base_Class__get_extra_meta__default_value', | |
| 2922 | - $default, | |
| 2923 | - $meta_key, | |
| 2924 | - $single, | |
| 2925 | - $this | |
| 2926 | - ); | |
| 2927 | - } | |
| 2928 | - | |
| 2929 | - | |
| 2930 | - /** | |
| 2931 | - * Returns a simple array of all the extra meta associated with this model object. | |
| 2932 | - * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the | |
| 2933 | - * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with | |
| 2934 | -     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123)) | |
| 2935 | - * If $one_of_each_key is false, it will return an array with the top-level keys being | |
| 2936 | - * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and | |
| 2937 | - * finally the extra meta's value as each sub-value. (eg | |
| 2938 | -     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123))) | |
| 2939 | - * | |
| 2940 | - * @param boolean $one_of_each_key | |
| 2941 | - * @return array | |
| 2942 | - * @throws ReflectionException | |
| 2943 | - * @throws InvalidArgumentException | |
| 2944 | - * @throws InvalidInterfaceException | |
| 2945 | - * @throws InvalidDataTypeException | |
| 2946 | - * @throws EE_Error | |
| 2947 | - */ | |
| 2948 | - public function all_extra_meta_array($one_of_each_key = true) | |
| 2949 | -    { | |
| 2950 | - $return_array = array(); | |
| 2951 | -        if ($one_of_each_key) { | |
| 2952 | - $extra_meta_objs = $this->get_many_related( | |
| 2953 | - 'Extra_Meta', | |
| 2954 | -                array('group_by' => 'EXM_key') | |
| 2955 | - ); | |
| 2956 | -            foreach ($extra_meta_objs as $extra_meta_obj) { | |
| 2957 | -                if ($extra_meta_obj instanceof EE_Extra_Meta) { | |
| 2958 | - $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value(); | |
| 2959 | - } | |
| 2960 | - } | |
| 2961 | -        } else { | |
| 2962 | -            $extra_meta_objs = $this->get_many_related('Extra_Meta'); | |
| 2963 | -            foreach ($extra_meta_objs as $extra_meta_obj) { | |
| 2964 | -                if ($extra_meta_obj instanceof EE_Extra_Meta) { | |
| 2965 | -                    if (! isset($return_array[ $extra_meta_obj->key() ])) { | |
| 2966 | - $return_array[ $extra_meta_obj->key() ] = array(); | |
| 2967 | - } | |
| 2968 | - $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value(); | |
| 2969 | - } | |
| 2970 | - } | |
| 2971 | - } | |
| 2972 | - return $return_array; | |
| 2973 | - } | |
| 2974 | - | |
| 2975 | - | |
| 2976 | - /** | |
| 2977 | - * Gets a pretty nice displayable nice for this model object. Often overridden | |
| 2978 | - * | |
| 2979 | - * @return string | |
| 2980 | - * @throws ReflectionException | |
| 2981 | - * @throws InvalidArgumentException | |
| 2982 | - * @throws InvalidInterfaceException | |
| 2983 | - * @throws InvalidDataTypeException | |
| 2984 | - * @throws EE_Error | |
| 2985 | - */ | |
| 2986 | - public function name() | |
| 2987 | -    { | |
| 2988 | - // find a field that's not a text field | |
| 2989 | -        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base'); | |
| 2990 | -        if ($field_we_can_use) { | |
| 2991 | - return $this->get($field_we_can_use->get_name()); | |
| 2992 | - } | |
| 2993 | - $first_few_properties = $this->model_field_array(); | |
| 2994 | - $first_few_properties = array_slice($first_few_properties, 0, 3); | |
| 2995 | - $name_parts = array(); | |
| 2996 | -        foreach ($first_few_properties as $name => $value) { | |
| 2997 | - $name_parts[] = "$name:$value"; | |
| 2998 | - } | |
| 2999 | -        return implode(',', $name_parts); | |
| 3000 | - } | |
| 3001 | - | |
| 3002 | - | |
| 3003 | - /** | |
| 3004 | - * in_entity_map | |
| 3005 | - * Checks if this model object has been proven to already be in the entity map | |
| 3006 | - * | |
| 3007 | - * @return boolean | |
| 3008 | - * @throws ReflectionException | |
| 3009 | - * @throws InvalidArgumentException | |
| 3010 | - * @throws InvalidInterfaceException | |
| 3011 | - * @throws InvalidDataTypeException | |
| 3012 | - * @throws EE_Error | |
| 3013 | - */ | |
| 3014 | - public function in_entity_map() | |
| 3015 | -    { | |
| 3016 | - // well, if we looked, did we find it in the entity map? | |
| 3017 | - return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this; | |
| 3018 | - } | |
| 3019 | - | |
| 3020 | - | |
| 3021 | - /** | |
| 3022 | - * refresh_from_db | |
| 3023 | - * Makes sure the fields and values on this model object are in-sync with what's in the database. | |
| 3024 | - * | |
| 3025 | - * @throws ReflectionException | |
| 3026 | - * @throws InvalidArgumentException | |
| 3027 | - * @throws InvalidInterfaceException | |
| 3028 | - * @throws InvalidDataTypeException | |
| 3029 | - * @throws EE_Error if this model object isn't in the entity mapper (because then you should | |
| 3030 | - * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE | |
| 3031 | - */ | |
| 3032 | - public function refresh_from_db() | |
| 3033 | -    { | |
| 3034 | -        if ($this->ID() && $this->in_entity_map()) { | |
| 3035 | - $this->get_model()->refresh_entity_map_from_db($this->ID()); | |
| 3036 | -        } else { | |
| 3037 | - // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database) | |
| 3038 | - // if it has an ID but it's not in the map, and you're asking me to refresh it | |
| 3039 | - // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's | |
| 3040 | - // absolutely nothing in it for this ID | |
| 3041 | -            if (WP_DEBUG) { | |
| 3042 | - throw new EE_Error( | |
| 3043 | - sprintf( | |
| 3044 | - esc_html__( | |
| 3045 | - 'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.', | |
| 3046 | - 'event_espresso' | |
| 3047 | - ), | |
| 3048 | - $this->ID(), | |
| 3049 | - get_class($this->get_model()) . '::instance()->add_to_entity_map()', | |
| 3050 | - get_class($this->get_model()) . '::instance()->refresh_entity_map()' | |
| 3051 | - ) | |
| 3052 | - ); | |
| 3053 | - } | |
| 3054 | - } | |
| 3055 | - } | |
| 3056 | - | |
| 3057 | - | |
| 3058 | - /** | |
| 3059 | - * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method | |
| 3060 | - * (probably a bad assumption they have made, oh well) | |
| 3061 | - * | |
| 3062 | - * @return string | |
| 3063 | - */ | |
| 3064 | - public function __toString() | |
| 3065 | -    { | |
| 3066 | -        try { | |
| 3067 | -            return sprintf('%s (%s)', $this->name(), $this->ID()); | |
| 3068 | -        } catch (Exception $e) { | |
| 3069 | - EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 3070 | - return ''; | |
| 3071 | - } | |
| 3072 | - } | |
| 3073 | - | |
| 3074 | - | |
| 3075 | - /** | |
| 3076 | - * Clear related model objects if they're already in the DB, because otherwise when we | |
| 3077 | - * UN-serialize this model object we'll need to be careful to add them to the entity map. | |
| 3078 | - * This means if we have made changes to those related model objects, and want to unserialize | |
| 3079 | - * the this model object on a subsequent request, changes to those related model objects will be lost. | |
| 3080 | - * Instead, those related model objects should be directly serialized and stored. | |
| 3081 | - * Eg, the following won't work: | |
| 3082 | - * $reg = EEM_Registration::instance()->get_one_by_ID( 123 ); | |
| 3083 | - * $att = $reg->attendee(); | |
| 3084 | - * $att->set( 'ATT_fname', 'Dirk' ); | |
| 3085 | - * update_option( 'my_option', serialize( $reg ) ); | |
| 3086 | - * //END REQUEST | |
| 3087 | - * //START NEXT REQUEST | |
| 3088 | - * $reg = get_option( 'my_option' ); | |
| 3089 | - * $reg->attendee()->save(); | |
| 3090 | - * And would need to be replace with: | |
| 3091 | - * $reg = EEM_Registration::instance()->get_one_by_ID( 123 ); | |
| 3092 | - * $att = $reg->attendee(); | |
| 3093 | - * $att->set( 'ATT_fname', 'Dirk' ); | |
| 3094 | - * update_option( 'my_option', serialize( $reg ) ); | |
| 3095 | - * //END REQUEST | |
| 3096 | - * //START NEXT REQUEST | |
| 3097 | - * $att = get_option( 'my_option' ); | |
| 3098 | - * $att->save(); | |
| 3099 | - * | |
| 3100 | - * @return array | |
| 3101 | - * @throws ReflectionException | |
| 3102 | - * @throws InvalidArgumentException | |
| 3103 | - * @throws InvalidInterfaceException | |
| 3104 | - * @throws InvalidDataTypeException | |
| 3105 | - * @throws EE_Error | |
| 3106 | - */ | |
| 3107 | - public function __sleep() | |
| 3108 | -    { | |
| 3109 | - $model = $this->get_model(); | |
| 3110 | -        foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 3111 | -            if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 3112 | - $classname = 'EE_' . $model->get_this_model_name(); | |
| 3113 | - if ($this->get_one_from_cache($relation_name) instanceof $classname | |
| 3114 | - && $this->get_one_from_cache($relation_name)->ID() | |
| 3115 | -                ) { | |
| 3116 | - $this->clear_cache( | |
| 3117 | - $relation_name, | |
| 3118 | - $this->get_one_from_cache($relation_name)->ID() | |
| 3119 | - ); | |
| 3120 | - } | |
| 3121 | - } | |
| 3122 | - } | |
| 3123 | - $this->_props_n_values_provided_in_constructor = array(); | |
| 3124 | - $properties_to_serialize = get_object_vars($this); | |
| 3125 | - // don't serialize the model. It's big and that risks recursion | |
| 3126 | - unset($properties_to_serialize['_model']); | |
| 3127 | - return array_keys($properties_to_serialize); | |
| 3128 | - } | |
| 3129 | - | |
| 3130 | - | |
| 3131 | - /** | |
| 3132 | - * restore _props_n_values_provided_in_constructor | |
| 3133 | - * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization, | |
| 3134 | - * and therefore should NOT be used to determine if state change has occurred since initial construction. | |
| 3135 | - * At best, you would only be able to detect if state change has occurred during THIS request. | |
| 3136 | - */ | |
| 3137 | - public function __wakeup() | |
| 3138 | -    { | |
| 3139 | - $this->_props_n_values_provided_in_constructor = $this->_fields; | |
| 3140 | - } | |
| 3141 | - | |
| 3142 | - | |
| 3143 | - /** | |
| 3144 | - * Usage of this magic method is to ensure any internally cached references to object instances that must remain | |
| 3145 | - * distinct with the clone host instance are also cloned. | |
| 3146 | - */ | |
| 3147 | - public function __clone() | |
| 3148 | -    { | |
| 3149 | - // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes). | |
| 3150 | -        foreach ($this->_fields as $field => $value) { | |
| 3151 | -            if ($value instanceof DateTime) { | |
| 3152 | - $this->_fields[ $field ] = clone $value; | |
| 3153 | - } | |
| 3154 | - } | |
| 3155 | - } | |
| 16 | + /** | |
| 17 | + * This is an array of the original properties and values provided during construction | |
| 18 | + * of this model object. (keys are model field names, values are their values). | |
| 19 | + * This list is important to remember so that when we are merging data from the db, we know | |
| 20 | + * which values to override and which to not override. | |
| 21 | + * | |
| 22 | + * @var array | |
| 23 | + */ | |
| 24 | + protected $_props_n_values_provided_in_constructor; | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * Timezone | |
| 28 | + * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in. | |
| 29 | + * This can also be used before a get to set what timezone you want strings coming out of the object to be in. NOT | |
| 30 | + * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have | |
| 31 | + * access to it. | |
| 32 | + * | |
| 33 | + * @var string | |
| 34 | + */ | |
| 35 | + protected $_timezone; | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * date format | |
| 39 | + * pattern or format for displaying dates | |
| 40 | + * | |
| 41 | + * @var string $_dt_frmt | |
| 42 | + */ | |
| 43 | + protected $_dt_frmt; | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * time format | |
| 47 | + * pattern or format for displaying time | |
| 48 | + * | |
| 49 | + * @var string $_tm_frmt | |
| 50 | + */ | |
| 51 | + protected $_tm_frmt; | |
| 52 | + | |
| 53 | + /** | |
| 54 | + * This property is for holding a cached array of object properties indexed by property name as the key. | |
| 55 | + * The purpose of this is for setting a cache on properties that may have calculated values after a | |
| 56 | + * prepare_for_get. That way the cache can be checked first and the calculated property returned instead of having | |
| 57 | + * to recalculate. Used by _set_cached_property() and _get_cached_property() methods. | |
| 58 | + * | |
| 59 | + * @var array | |
| 60 | + */ | |
| 61 | + protected $_cached_properties = array(); | |
| 62 | + | |
| 63 | + /** | |
| 64 | + * An array containing keys of the related model, and values are either an array of related mode objects or a | |
| 65 | + * single | |
| 66 | + * related model object. see the model's _model_relations. The keys should match those specified. And if the | |
| 67 | + * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object, | |
| 68 | + * all others have an array) | |
| 69 | + * | |
| 70 | + * @var array | |
| 71 | + */ | |
| 72 | + protected $_model_relations = array(); | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * Array where keys are field names (see the model's _fields property) and values are their values. To see what | |
| 76 | + * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods) | |
| 77 | + * | |
| 78 | + * @var array | |
| 79 | + */ | |
| 80 | + protected $_fields = array(); | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * @var boolean indicating whether or not this model object is intended to ever be saved | |
| 84 | + * For example, we might create model objects intended to only be used for the duration | |
| 85 | + * of this request and to be thrown away, and if they were accidentally saved | |
| 86 | + * it would be a bug. | |
| 87 | + */ | |
| 88 | + protected $_allow_persist = true; | |
| 89 | + | |
| 90 | + /** | |
| 91 | + * @var boolean indicating whether or not this model object's properties have changed since construction | |
| 92 | + */ | |
| 93 | + protected $_has_changes = false; | |
| 94 | + | |
| 95 | + /** | |
| 96 | + * @var EEM_Base | |
| 97 | + */ | |
| 98 | + protected $_model; | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose | |
| 102 | + * for these values is for retrieval of the results, they are not further queryable and they are not persisted to | |
| 103 | + * the db. They also do not automatically update if there are any changes to the data that produced their results. | |
| 104 | + * The format is a simple array of field_alias => field_value. So for instance if a custom select was something | |
| 105 | + * like, "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this | |
| 106 | + * array as: | |
| 107 | + * array( | |
| 108 | + * 'Registration_Count' => 24 | |
| 109 | + * ); | |
| 110 | + * Note: if the custom select configuration for the query included a data type, the value will be in the data type | |
| 111 | + * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more | |
| 112 | + * info) | |
| 113 | + * | |
| 114 | + * @var array | |
| 115 | + */ | |
| 116 | + protected $custom_selection_results = array(); | |
| 117 | + | |
| 118 | + | |
| 119 | + /** | |
| 120 | + * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children | |
| 121 | + * play nice | |
| 122 | + * | |
| 123 | + * @param array $fieldValues where each key is a field (ie, array key in the 2nd | |
| 124 | + * layer of the model's _fields array, (eg, EVT_ID, | |
| 125 | + * TXN_amount, QST_name, etc) and values are their values | |
| 126 | + * @param boolean $bydb a flag for setting if the class is instantiated by the | |
| 127 | + * corresponding db model or not. | |
| 128 | + * @param string $timezone indicate what timezone you want any datetime fields to | |
| 129 | + * be in when instantiating a EE_Base_Class object. | |
| 130 | + * @param array $date_formats An array of date formats to set on construct where first | |
| 131 | + * value is the date_format and second value is the time | |
| 132 | + * format. | |
| 133 | + * @throws InvalidArgumentException | |
| 134 | + * @throws InvalidInterfaceException | |
| 135 | + * @throws InvalidDataTypeException | |
| 136 | + * @throws EE_Error | |
| 137 | + * @throws ReflectionException | |
| 138 | + */ | |
| 139 | + protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array()) | |
| 140 | +	{ | |
| 141 | + $className = get_class($this); | |
| 142 | +		do_action("AHEE__{$className}__construct", $this, $fieldValues); | |
| 143 | + $model = $this->get_model(); | |
| 144 | + $model_fields = $model->field_settings(false); | |
| 145 | + // ensure $fieldValues is an array | |
| 146 | + $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues); | |
| 147 | + // verify client code has not passed any invalid field names | |
| 148 | +		foreach ($fieldValues as $field_name => $field_value) { | |
| 149 | +			if (! isset($model_fields[ $field_name ])) { | |
| 150 | + throw new EE_Error( | |
| 151 | + sprintf( | |
| 152 | + esc_html__( | |
| 153 | + 'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s', | |
| 154 | + 'event_espresso' | |
| 155 | + ), | |
| 156 | + $field_name, | |
| 157 | + get_class($this), | |
| 158 | +						implode(', ', array_keys($model_fields)) | |
| 159 | + ) | |
| 160 | + ); | |
| 161 | + } | |
| 162 | + } | |
| 163 | + $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone); | |
| 164 | +		if (! empty($date_formats) && is_array($date_formats)) { | |
| 165 | + list($this->_dt_frmt, $this->_tm_frmt) = $date_formats; | |
| 166 | +		} else { | |
| 167 | + // set default formats for date and time | |
| 168 | +			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d'); | |
| 169 | +			$this->_tm_frmt = (string) get_option('time_format', 'g:i a'); | |
| 170 | + } | |
| 171 | + // if db model is instantiating | |
| 172 | +		if ($bydb) { | |
| 173 | + // client code has indicated these field values are from the database | |
| 174 | +			foreach ($model_fields as $fieldName => $field) { | |
| 175 | + $this->set_from_db( | |
| 176 | + $fieldName, | |
| 177 | + isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null | |
| 178 | + ); | |
| 179 | + } | |
| 180 | +		} else { | |
| 181 | + // we're constructing a brand | |
| 182 | + // new instance of the model object. Generally, this means we'll need to do more field validation | |
| 183 | +			foreach ($model_fields as $fieldName => $field) { | |
| 184 | + $this->set( | |
| 185 | + $fieldName, | |
| 186 | + isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null, | |
| 187 | + true | |
| 188 | + ); | |
| 189 | + } | |
| 190 | + } | |
| 191 | + // remember what values were passed to this constructor | |
| 192 | + $this->_props_n_values_provided_in_constructor = $fieldValues; | |
| 193 | + // remember in entity mapper | |
| 194 | +		if (! $bydb && $model->has_primary_key_field() && $this->ID()) { | |
| 195 | + $model->add_to_entity_map($this); | |
| 196 | + } | |
| 197 | + // setup all the relations | |
| 198 | +		foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 199 | +			if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 200 | + $this->_model_relations[ $relation_name ] = null; | |
| 201 | +			} else { | |
| 202 | + $this->_model_relations[ $relation_name ] = array(); | |
| 203 | + } | |
| 204 | + } | |
| 205 | + /** | |
| 206 | + * Action done at the end of each model object construction | |
| 207 | + * | |
| 208 | + * @param EE_Base_Class $this the model object just created | |
| 209 | + */ | |
| 210 | +		do_action('AHEE__EE_Base_Class__construct__finished', $this); | |
| 211 | + } | |
| 212 | + | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * Gets whether or not this model object is allowed to persist/be saved to the database. | |
| 216 | + * | |
| 217 | + * @return boolean | |
| 218 | + */ | |
| 219 | + public function allow_persist() | |
| 220 | +	{ | |
| 221 | + return $this->_allow_persist; | |
| 222 | + } | |
| 223 | + | |
| 224 | + | |
| 225 | + /** | |
| 226 | + * Sets whether or not this model object should be allowed to be saved to the DB. | |
| 227 | + * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless | |
| 228 | + * you got new information that somehow made you change your mind. | |
| 229 | + * | |
| 230 | + * @param boolean $allow_persist | |
| 231 | + * @return boolean | |
| 232 | + */ | |
| 233 | + public function set_allow_persist($allow_persist) | |
| 234 | +	{ | |
| 235 | + return $this->_allow_persist = $allow_persist; | |
| 236 | + } | |
| 237 | + | |
| 238 | + | |
| 239 | + /** | |
| 240 | + * Gets the field's original value when this object was constructed during this request. | |
| 241 | + * This can be helpful when determining if a model object has changed or not | |
| 242 | + * | |
| 243 | + * @param string $field_name | |
| 244 | + * @return mixed|null | |
| 245 | + * @throws ReflectionException | |
| 246 | + * @throws InvalidArgumentException | |
| 247 | + * @throws InvalidInterfaceException | |
| 248 | + * @throws InvalidDataTypeException | |
| 249 | + * @throws EE_Error | |
| 250 | + */ | |
| 251 | + public function get_original($field_name) | |
| 252 | +	{ | |
| 253 | + if (isset($this->_props_n_values_provided_in_constructor[ $field_name ]) | |
| 254 | + && $field_settings = $this->get_model()->field_settings_for($field_name) | |
| 255 | +		) { | |
| 256 | + return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]); | |
| 257 | + } | |
| 258 | + return null; | |
| 259 | + } | |
| 260 | + | |
| 261 | + | |
| 262 | + /** | |
| 263 | + * @param EE_Base_Class $obj | |
| 264 | + * @return string | |
| 265 | + */ | |
| 266 | + public function get_class($obj) | |
| 267 | +	{ | |
| 268 | + return get_class($obj); | |
| 269 | + } | |
| 270 | + | |
| 271 | + | |
| 272 | + /** | |
| 273 | + * Overrides parent because parent expects old models. | |
| 274 | + * This also doesn't do any validation, and won't work for serialized arrays | |
| 275 | + * | |
| 276 | + * @param string $field_name | |
| 277 | + * @param mixed $field_value | |
| 278 | + * @param bool $use_default | |
| 279 | + * @throws InvalidArgumentException | |
| 280 | + * @throws InvalidInterfaceException | |
| 281 | + * @throws InvalidDataTypeException | |
| 282 | + * @throws EE_Error | |
| 283 | + * @throws ReflectionException | |
| 284 | + * @throws ReflectionException | |
| 285 | + * @throws ReflectionException | |
| 286 | + */ | |
| 287 | + public function set($field_name, $field_value, $use_default = false) | |
| 288 | +	{ | |
| 289 | + // if not using default and nothing has changed, and object has already been setup (has ID), | |
| 290 | + // then don't do anything | |
| 291 | + if (! $use_default | |
| 292 | + && $this->_fields[ $field_name ] === $field_value | |
| 293 | + && $this->ID() | |
| 294 | +		) { | |
| 295 | + return; | |
| 296 | + } | |
| 297 | + $model = $this->get_model(); | |
| 298 | + $this->_has_changes = true; | |
| 299 | + $field_obj = $model->field_settings_for($field_name); | |
| 300 | +		if ($field_obj instanceof EE_Model_Field_Base) { | |
| 301 | +			// if ( method_exists( $field_obj, 'set_timezone' )) { | |
| 302 | +			if ($field_obj instanceof EE_Datetime_Field) { | |
| 303 | + $field_obj->set_timezone($this->_timezone); | |
| 304 | + $field_obj->set_date_format($this->_dt_frmt); | |
| 305 | + $field_obj->set_time_format($this->_tm_frmt); | |
| 306 | + } | |
| 307 | + $holder_of_value = $field_obj->prepare_for_set($field_value); | |
| 308 | + // should the value be null? | |
| 309 | +			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) { | |
| 310 | + $this->_fields[ $field_name ] = $field_obj->get_default_value(); | |
| 311 | + /** | |
| 312 | + * To save having to refactor all the models, if a default value is used for a | |
| 313 | + * EE_Datetime_Field, and that value is not null nor is it a DateTime | |
| 314 | + * object. Then let's do a set again to ensure that it becomes a DateTime | |
| 315 | + * object. | |
| 316 | + * | |
| 317 | + * @since 4.6.10+ | |
| 318 | + */ | |
| 319 | + if ($field_obj instanceof EE_Datetime_Field | |
| 320 | + && $this->_fields[ $field_name ] !== null | |
| 321 | + && ! $this->_fields[ $field_name ] instanceof DateTime | |
| 322 | +				) { | |
| 323 | + empty($this->_fields[ $field_name ]) | |
| 324 | + ? $this->set($field_name, time()) | |
| 325 | + : $this->set($field_name, $this->_fields[ $field_name ]); | |
| 326 | + } | |
| 327 | +			} else { | |
| 328 | + $this->_fields[ $field_name ] = $holder_of_value; | |
| 329 | + } | |
| 330 | + // if we're not in the constructor... | |
| 331 | + // now check if what we set was a primary key | |
| 332 | + if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor | |
| 333 | + $this->_props_n_values_provided_in_constructor | |
| 334 | + && $field_value | |
| 335 | + && $field_name === $model->primary_key_name() | |
| 336 | +			) { | |
| 337 | + // if so, we want all this object's fields to be filled either with | |
| 338 | + // what we've explicitly set on this model | |
| 339 | + // or what we have in the db | |
| 340 | + // echo "setting primary key!"; | |
| 341 | + $fields_on_model = self::_get_model(get_class($this))->field_settings(); | |
| 342 | + $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value); | |
| 343 | +				foreach ($fields_on_model as $field_obj) { | |
| 344 | + if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor) | |
| 345 | + && $field_obj->get_name() !== $field_name | |
| 346 | +					) { | |
| 347 | + $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name())); | |
| 348 | + } | |
| 349 | + } | |
| 350 | + // oh this model object has an ID? well make sure its in the entity mapper | |
| 351 | + $model->add_to_entity_map($this); | |
| 352 | + } | |
| 353 | + // let's unset any cache for this field_name from the $_cached_properties property. | |
| 354 | + $this->_clear_cached_property($field_name); | |
| 355 | +		} else { | |
| 356 | + throw new EE_Error( | |
| 357 | + sprintf( | |
| 358 | + esc_html__( | |
| 359 | + 'A valid EE_Model_Field_Base could not be found for the given field name: %s', | |
| 360 | + 'event_espresso' | |
| 361 | + ), | |
| 362 | + $field_name | |
| 363 | + ) | |
| 364 | + ); | |
| 365 | + } | |
| 366 | + } | |
| 367 | + | |
| 368 | + | |
| 369 | + /** | |
| 370 | + * Set custom select values for model. | |
| 371 | + * | |
| 372 | + * @param array $custom_select_values | |
| 373 | + */ | |
| 374 | + public function setCustomSelectsValues(array $custom_select_values) | |
| 375 | +	{ | |
| 376 | + $this->custom_selection_results = $custom_select_values; | |
| 377 | + } | |
| 378 | + | |
| 379 | + | |
| 380 | + /** | |
| 381 | + * Returns the custom select value for the provided alias if its set. | |
| 382 | + * If not set, returns null. | |
| 383 | + * | |
| 384 | + * @param string $alias | |
| 385 | + * @return string|int|float|null | |
| 386 | + */ | |
| 387 | + public function getCustomSelect($alias) | |
| 388 | +	{ | |
| 389 | + return isset($this->custom_selection_results[ $alias ]) | |
| 390 | + ? $this->custom_selection_results[ $alias ] | |
| 391 | + : null; | |
| 392 | + } | |
| 393 | + | |
| 394 | + | |
| 395 | + /** | |
| 396 | + * This sets the field value on the db column if it exists for the given $column_name or | |
| 397 | + * saves it to EE_Extra_Meta if the given $column_name does not match a db column. | |
| 398 | + * | |
| 399 | + * @see EE_message::get_column_value for related documentation on the necessity of this method. | |
| 400 | + * @param string $field_name Must be the exact column name. | |
| 401 | + * @param mixed $field_value The value to set. | |
| 402 | + * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs. | |
| 403 | + * @throws InvalidArgumentException | |
| 404 | + * @throws InvalidInterfaceException | |
| 405 | + * @throws InvalidDataTypeException | |
| 406 | + * @throws EE_Error | |
| 407 | + * @throws ReflectionException | |
| 408 | + */ | |
| 409 | + public function set_field_or_extra_meta($field_name, $field_value) | |
| 410 | +	{ | |
| 411 | +		if ($this->get_model()->has_field($field_name)) { | |
| 412 | + $this->set($field_name, $field_value); | |
| 413 | + return true; | |
| 414 | + } | |
| 415 | + // ensure this object is saved first so that extra meta can be properly related. | |
| 416 | + $this->save(); | |
| 417 | + return $this->update_extra_meta($field_name, $field_value); | |
| 418 | + } | |
| 419 | + | |
| 420 | + | |
| 421 | + /** | |
| 422 | + * This retrieves the value of the db column set on this class or if that's not present | |
| 423 | + * it will attempt to retrieve from extra_meta if found. | |
| 424 | + * Example Usage: | |
| 425 | + * Via EE_Message child class: | |
| 426 | + * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to", | |
| 427 | + * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may | |
| 428 | + * also have additional main fields specific to the messenger. The system accommodates those extra | |
| 429 | + * fields through the EE_Extra_Meta table. This method allows for EE_messengers to retrieve the | |
| 430 | + * value for those extra fields dynamically via the EE_message object. | |
| 431 | + * | |
| 432 | + * @param string $field_name expecting the fully qualified field name. | |
| 433 | + * @return mixed|null value for the field if found. null if not found. | |
| 434 | + * @throws ReflectionException | |
| 435 | + * @throws InvalidArgumentException | |
| 436 | + * @throws InvalidInterfaceException | |
| 437 | + * @throws InvalidDataTypeException | |
| 438 | + * @throws EE_Error | |
| 439 | + */ | |
| 440 | + public function get_field_or_extra_meta($field_name) | |
| 441 | +	{ | |
| 442 | +		if ($this->get_model()->has_field($field_name)) { | |
| 443 | + $column_value = $this->get($field_name); | |
| 444 | +		} else { | |
| 445 | + // This isn't a column in the main table, let's see if it is in the extra meta. | |
| 446 | + $column_value = $this->get_extra_meta($field_name, true, null); | |
| 447 | + } | |
| 448 | + return $column_value; | |
| 449 | + } | |
| 450 | + | |
| 451 | + | |
| 452 | + /** | |
| 453 | + * See $_timezone property for description of what the timezone property is for. This SETS the timezone internally | |
| 454 | + * for being able to reference what timezone we are running conversions on when converting TO the internal timezone | |
| 455 | + * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is | |
| 456 | + * available to all child classes that may be using the EE_Datetime_Field for a field data type. | |
| 457 | + * | |
| 458 | + * @access public | |
| 459 | + * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php | |
| 460 | + * @return void | |
| 461 | + * @throws InvalidArgumentException | |
| 462 | + * @throws InvalidInterfaceException | |
| 463 | + * @throws InvalidDataTypeException | |
| 464 | + * @throws EE_Error | |
| 465 | + * @throws ReflectionException | |
| 466 | + */ | |
| 467 | + public function set_timezone($timezone = '') | |
| 468 | +	{ | |
| 469 | + $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone); | |
| 470 | + // make sure we clear all cached properties because they won't be relevant now | |
| 471 | + $this->_clear_cached_properties(); | |
| 472 | + // make sure we update field settings and the date for all EE_Datetime_Fields | |
| 473 | + $model_fields = $this->get_model()->field_settings(false); | |
| 474 | +		foreach ($model_fields as $field_name => $field_obj) { | |
| 475 | +			if ($field_obj instanceof EE_Datetime_Field) { | |
| 476 | + $field_obj->set_timezone($this->_timezone); | |
| 477 | +				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) { | |
| 478 | + EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone)); | |
| 479 | + } | |
| 480 | + } | |
| 481 | + } | |
| 482 | + } | |
| 483 | + | |
| 484 | + | |
| 485 | + /** | |
| 486 | + * This just returns whatever is set for the current timezone. | |
| 487 | + * | |
| 488 | + * @access public | |
| 489 | + * @return string timezone string | |
| 490 | + */ | |
| 491 | + public function get_timezone() | |
| 492 | +	{ | |
| 493 | + return $this->_timezone; | |
| 494 | + } | |
| 495 | + | |
| 496 | + | |
| 497 | + /** | |
| 498 | + * This sets the internal date format to what is sent in to be used as the new default for the class | |
| 499 | + * internally instead of wp set date format options | |
| 500 | + * | |
| 501 | + * @since 4.6 | |
| 502 | + * @param string $format should be a format recognizable by PHP date() functions. | |
| 503 | + */ | |
| 504 | + public function set_date_format($format) | |
| 505 | +	{ | |
| 506 | + $this->_dt_frmt = $format; | |
| 507 | + // clear cached_properties because they won't be relevant now. | |
| 508 | + $this->_clear_cached_properties(); | |
| 509 | + } | |
| 510 | + | |
| 511 | + | |
| 512 | + /** | |
| 513 | + * This sets the internal time format string to what is sent in to be used as the new default for the | |
| 514 | + * class internally instead of wp set time format options. | |
| 515 | + * | |
| 516 | + * @since 4.6 | |
| 517 | + * @param string $format should be a format recognizable by PHP date() functions. | |
| 518 | + */ | |
| 519 | + public function set_time_format($format) | |
| 520 | +	{ | |
| 521 | + $this->_tm_frmt = $format; | |
| 522 | + // clear cached_properties because they won't be relevant now. | |
| 523 | + $this->_clear_cached_properties(); | |
| 524 | + } | |
| 525 | + | |
| 526 | + | |
| 527 | + /** | |
| 528 | + * This returns the current internal set format for the date and time formats. | |
| 529 | + * | |
| 530 | + * @param bool $full if true (default), then return the full format. Otherwise will return an array | |
| 531 | + * where the first value is the date format and the second value is the time format. | |
| 532 | + * @return mixed string|array | |
| 533 | + */ | |
| 534 | + public function get_format($full = true) | |
| 535 | +	{ | |
| 536 | + return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt); | |
| 537 | + } | |
| 538 | + | |
| 539 | + | |
| 540 | + /** | |
| 541 | + * cache | |
| 542 | + * stores the passed model object on the current model object. | |
| 543 | + * In certain circumstances, we can use this cached model object instead of querying for another one entirely. | |
| 544 | + * | |
| 545 | + * @param string $relationName one of the keys in the _model_relations array on the model. Eg | |
| 546 | + * 'Registration' associated with this model object | |
| 547 | + * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction, | |
| 548 | + * that could be a payment or a registration) | |
| 549 | + * @param null $cache_id a string or number that will be used as the key for any Belongs_To_Many | |
| 550 | + * items which will be stored in an array on this object | |
| 551 | + * @throws ReflectionException | |
| 552 | + * @throws InvalidArgumentException | |
| 553 | + * @throws InvalidInterfaceException | |
| 554 | + * @throws InvalidDataTypeException | |
| 555 | + * @throws EE_Error | |
| 556 | + * @return mixed index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one | |
| 557 | + * related thing, no array) | |
| 558 | + */ | |
| 559 | + public function cache($relationName = '', $object_to_cache = null, $cache_id = null) | |
| 560 | +	{ | |
| 561 | + // its entirely possible that there IS no related object yet in which case there is nothing to cache. | |
| 562 | +		if (! $object_to_cache instanceof EE_Base_Class) { | |
| 563 | + return false; | |
| 564 | + } | |
| 565 | + // also get "how" the object is related, or throw an error | |
| 566 | +		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) { | |
| 567 | + throw new EE_Error( | |
| 568 | + sprintf( | |
| 569 | +					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'), | |
| 570 | + $relationName, | |
| 571 | + get_class($this) | |
| 572 | + ) | |
| 573 | + ); | |
| 574 | + } | |
| 575 | + // how many things are related ? | |
| 576 | +		if ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 577 | + // if it's a "belongs to" relationship, then there's only one related model object | |
| 578 | + // eg, if this is a registration, there's only 1 attendee for it | |
| 579 | + // so for these model objects just set it to be cached | |
| 580 | + $this->_model_relations[ $relationName ] = $object_to_cache; | |
| 581 | + $return = true; | |
| 582 | +		} else { | |
| 583 | + // otherwise, this is the "many" side of a one to many relationship, | |
| 584 | + // so we'll add the object to the array of related objects for that type. | |
| 585 | + // eg: if this is an event, there are many registrations for that event, | |
| 586 | + // so we cache the registrations in an array | |
| 587 | +			if (! is_array($this->_model_relations[ $relationName ])) { | |
| 588 | + // if for some reason, the cached item is a model object, | |
| 589 | + // then stick that in the array, otherwise start with an empty array | |
| 590 | + $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ] | |
| 591 | + instanceof | |
| 592 | + EE_Base_Class | |
| 593 | + ? array($this->_model_relations[ $relationName ]) : array(); | |
| 594 | + } | |
| 595 | + // first check for a cache_id which is normally empty | |
| 596 | +			if (! empty($cache_id)) { | |
| 597 | + // if the cache_id exists, then it means we are purposely trying to cache this | |
| 598 | + // with a known key that can then be used to retrieve the object later on | |
| 599 | + $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache; | |
| 600 | + $return = $cache_id; | |
| 601 | +			} elseif ($object_to_cache->ID()) { | |
| 602 | + // OR the cached object originally came from the db, so let's just use it's PK for an ID | |
| 603 | + $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache; | |
| 604 | + $return = $object_to_cache->ID(); | |
| 605 | +			} else { | |
| 606 | + // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID | |
| 607 | + $this->_model_relations[ $relationName ][] = $object_to_cache; | |
| 608 | + // move the internal pointer to the end of the array | |
| 609 | + end($this->_model_relations[ $relationName ]); | |
| 610 | + // and grab the key so that we can return it | |
| 611 | + $return = key($this->_model_relations[ $relationName ]); | |
| 612 | + } | |
| 613 | + } | |
| 614 | + return $return; | |
| 615 | + } | |
| 616 | + | |
| 617 | + | |
| 618 | + /** | |
| 619 | + * For adding an item to the cached_properties property. | |
| 620 | + * | |
| 621 | + * @access protected | |
| 622 | + * @param string $fieldname the property item the corresponding value is for. | |
| 623 | + * @param mixed $value The value we are caching. | |
| 624 | + * @param string|null $cache_type | |
| 625 | + * @return void | |
| 626 | + * @throws ReflectionException | |
| 627 | + * @throws InvalidArgumentException | |
| 628 | + * @throws InvalidInterfaceException | |
| 629 | + * @throws InvalidDataTypeException | |
| 630 | + * @throws EE_Error | |
| 631 | + */ | |
| 632 | + protected function _set_cached_property($fieldname, $value, $cache_type = null) | |
| 633 | +	{ | |
| 634 | + // first make sure this property exists | |
| 635 | + $this->get_model()->field_settings_for($fieldname); | |
| 636 | + $cache_type = empty($cache_type) ? 'standard' : $cache_type; | |
| 637 | + $this->_cached_properties[ $fieldname ][ $cache_type ] = $value; | |
| 638 | + } | |
| 639 | + | |
| 640 | + | |
| 641 | + /** | |
| 642 | + * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist. | |
| 643 | + * This also SETS the cache if we return the actual property! | |
| 644 | + * | |
| 645 | + * @param string $fieldname the name of the property we're trying to retrieve | |
| 646 | + * @param bool $pretty | |
| 647 | + * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 648 | + * (in cases where the same property may be used for different outputs | |
| 649 | + * - i.e. datetime, money etc.) | |
| 650 | + * It can also accept certain pre-defined "schema" strings | |
| 651 | + * to define how to output the property. | |
| 652 | + * see the field's prepare_for_pretty_echoing for what strings can be used | |
| 653 | + * @return mixed whatever the value for the property is we're retrieving | |
| 654 | + * @throws ReflectionException | |
| 655 | + * @throws InvalidArgumentException | |
| 656 | + * @throws InvalidInterfaceException | |
| 657 | + * @throws InvalidDataTypeException | |
| 658 | + * @throws EE_Error | |
| 659 | + */ | |
| 660 | + protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null) | |
| 661 | +	{ | |
| 662 | + // verify the field exists | |
| 663 | + $model = $this->get_model(); | |
| 664 | + $model->field_settings_for($fieldname); | |
| 665 | + $cache_type = $pretty ? 'pretty' : 'standard'; | |
| 666 | + $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : ''; | |
| 667 | +		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) { | |
| 668 | + return $this->_cached_properties[ $fieldname ][ $cache_type ]; | |
| 669 | + } | |
| 670 | + $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref); | |
| 671 | + $this->_set_cached_property($fieldname, $value, $cache_type); | |
| 672 | + return $value; | |
| 673 | + } | |
| 674 | + | |
| 675 | + | |
| 676 | + /** | |
| 677 | + * If the cache didn't fetch the needed item, this fetches it. | |
| 678 | + * | |
| 679 | + * @param string $fieldname | |
| 680 | + * @param bool $pretty | |
| 681 | + * @param string $extra_cache_ref | |
| 682 | + * @return mixed | |
| 683 | + * @throws InvalidArgumentException | |
| 684 | + * @throws InvalidInterfaceException | |
| 685 | + * @throws InvalidDataTypeException | |
| 686 | + * @throws EE_Error | |
| 687 | + * @throws ReflectionException | |
| 688 | + */ | |
| 689 | + protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null) | |
| 690 | +	{ | |
| 691 | + $field_obj = $this->get_model()->field_settings_for($fieldname); | |
| 692 | + // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct | |
| 693 | +		if ($field_obj instanceof EE_Datetime_Field) { | |
| 694 | + $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref); | |
| 695 | + } | |
| 696 | +		if (! isset($this->_fields[ $fieldname ])) { | |
| 697 | + $this->_fields[ $fieldname ] = null; | |
| 698 | + } | |
| 699 | + $value = $pretty | |
| 700 | + ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref) | |
| 701 | + : $field_obj->prepare_for_get($this->_fields[ $fieldname ]); | |
| 702 | + return $value; | |
| 703 | + } | |
| 704 | + | |
| 705 | + | |
| 706 | + /** | |
| 707 | + * set timezone, formats, and output for EE_Datetime_Field objects | |
| 708 | + * | |
| 709 | + * @param \EE_Datetime_Field $datetime_field | |
| 710 | + * @param bool $pretty | |
| 711 | + * @param null $date_or_time | |
| 712 | + * @return void | |
| 713 | + * @throws InvalidArgumentException | |
| 714 | + * @throws InvalidInterfaceException | |
| 715 | + * @throws InvalidDataTypeException | |
| 716 | + * @throws EE_Error | |
| 717 | + */ | |
| 718 | + protected function _prepare_datetime_field( | |
| 719 | + EE_Datetime_Field $datetime_field, | |
| 720 | + $pretty = false, | |
| 721 | + $date_or_time = null | |
| 722 | +	) { | |
| 723 | + $datetime_field->set_timezone($this->_timezone); | |
| 724 | + $datetime_field->set_date_format($this->_dt_frmt, $pretty); | |
| 725 | + $datetime_field->set_time_format($this->_tm_frmt, $pretty); | |
| 726 | + // set the output returned | |
| 727 | +		switch ($date_or_time) { | |
| 728 | + case 'D': | |
| 729 | +				$datetime_field->set_date_time_output('date'); | |
| 730 | + break; | |
| 731 | + case 'T': | |
| 732 | +				$datetime_field->set_date_time_output('time'); | |
| 733 | + break; | |
| 734 | + default: | |
| 735 | + $datetime_field->set_date_time_output(); | |
| 736 | + } | |
| 737 | + } | |
| 738 | + | |
| 739 | + | |
| 740 | + /** | |
| 741 | + * This just takes care of clearing out the cached_properties | |
| 742 | + * | |
| 743 | + * @return void | |
| 744 | + */ | |
| 745 | + protected function _clear_cached_properties() | |
| 746 | +	{ | |
| 747 | + $this->_cached_properties = array(); | |
| 748 | + } | |
| 749 | + | |
| 750 | + | |
| 751 | + /** | |
| 752 | + * This just clears out ONE property if it exists in the cache | |
| 753 | + * | |
| 754 | + * @param string $property_name the property to remove if it exists (from the _cached_properties array) | |
| 755 | + * @return void | |
| 756 | + */ | |
| 757 | + protected function _clear_cached_property($property_name) | |
| 758 | +	{ | |
| 759 | +		if (isset($this->_cached_properties[ $property_name ])) { | |
| 760 | + unset($this->_cached_properties[ $property_name ]); | |
| 761 | + } | |
| 762 | + } | |
| 763 | + | |
| 764 | + | |
| 765 | + /** | |
| 766 | + * Ensures that this related thing is a model object. | |
| 767 | + * | |
| 768 | + * @param mixed $object_or_id EE_base_Class/int/string either a related model object, or its ID | |
| 769 | + * @param string $model_name name of the related thing, eg 'Attendee', | |
| 770 | + * @return EE_Base_Class | |
| 771 | + * @throws ReflectionException | |
| 772 | + * @throws InvalidArgumentException | |
| 773 | + * @throws InvalidInterfaceException | |
| 774 | + * @throws InvalidDataTypeException | |
| 775 | + * @throws EE_Error | |
| 776 | + */ | |
| 777 | + protected function ensure_related_thing_is_model_obj($object_or_id, $model_name) | |
| 778 | +	{ | |
| 779 | + $other_model_instance = self::_get_model_instance_with_name( | |
| 780 | + self::_get_model_classname($model_name), | |
| 781 | + $this->_timezone | |
| 782 | + ); | |
| 783 | + return $other_model_instance->ensure_is_obj($object_or_id); | |
| 784 | + } | |
| 785 | + | |
| 786 | + | |
| 787 | + /** | |
| 788 | + * Forgets the cached model of the given relation Name. So the next time we request it, | |
| 789 | + * we will fetch it again from the database. (Handy if you know it's changed somehow). | |
| 790 | + * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM, | |
| 791 | + * then only remove that one object from our cached array. Otherwise, clear the entire list | |
| 792 | + * | |
| 793 | + * @param string $relationName one of the keys in the _model_relations array on the model. | |
| 794 | + * Eg 'Registration' | |
| 795 | + * @param mixed $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL | |
| 796 | + * if you intend to use $clear_all = TRUE, or the relation only | |
| 797 | + * has 1 object anyways (ie, it's a BelongsToRelation) | |
| 798 | + * @param bool $clear_all This flags clearing the entire cache relation property if | |
| 799 | + * this is HasMany or HABTM. | |
| 800 | + * @throws ReflectionException | |
| 801 | + * @throws InvalidArgumentException | |
| 802 | + * @throws InvalidInterfaceException | |
| 803 | + * @throws InvalidDataTypeException | |
| 804 | + * @throws EE_Error | |
| 805 | + * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a | |
| 806 | + * relation from all | |
| 807 | + */ | |
| 808 | + public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false) | |
| 809 | +	{ | |
| 810 | + $relationship_to_model = $this->get_model()->related_settings_for($relationName); | |
| 811 | + $index_in_cache = ''; | |
| 812 | +		if (! $relationship_to_model) { | |
| 813 | + throw new EE_Error( | |
| 814 | + sprintf( | |
| 815 | +					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'), | |
| 816 | + $relationName, | |
| 817 | + get_class($this) | |
| 818 | + ) | |
| 819 | + ); | |
| 820 | + } | |
| 821 | +		if ($clear_all) { | |
| 822 | + $obj_removed = true; | |
| 823 | + $this->_model_relations[ $relationName ] = null; | |
| 824 | +		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 825 | + $obj_removed = $this->_model_relations[ $relationName ]; | |
| 826 | + $this->_model_relations[ $relationName ] = null; | |
| 827 | +		} else { | |
| 828 | + if ($object_to_remove_or_index_into_array instanceof EE_Base_Class | |
| 829 | + && $object_to_remove_or_index_into_array->ID() | |
| 830 | +			) { | |
| 831 | + $index_in_cache = $object_to_remove_or_index_into_array->ID(); | |
| 832 | + if (is_array($this->_model_relations[ $relationName ]) | |
| 833 | + && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ]) | |
| 834 | +				) { | |
| 835 | + $index_found_at = null; | |
| 836 | + // find this object in the array even though it has a different key | |
| 837 | +					foreach ($this->_model_relations[ $relationName ] as $index => $obj) { | |
| 838 | + /** @noinspection TypeUnsafeComparisonInspection */ | |
| 839 | + if ($obj instanceof EE_Base_Class | |
| 840 | + && ( | |
| 841 | + $obj == $object_to_remove_or_index_into_array | |
| 842 | + || $obj->ID() === $object_to_remove_or_index_into_array->ID() | |
| 843 | + ) | |
| 844 | +						) { | |
| 845 | + $index_found_at = $index; | |
| 846 | + break; | |
| 847 | + } | |
| 848 | + } | |
| 849 | +					if ($index_found_at) { | |
| 850 | + $index_in_cache = $index_found_at; | |
| 851 | +					} else { | |
| 852 | + // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache | |
| 853 | + // if it wasn't in it to begin with. So we're done | |
| 854 | + return $object_to_remove_or_index_into_array; | |
| 855 | + } | |
| 856 | + } | |
| 857 | +			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) { | |
| 858 | + // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it! | |
| 859 | +				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) { | |
| 860 | + /** @noinspection TypeUnsafeComparisonInspection */ | |
| 861 | +					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) { | |
| 862 | + $index_in_cache = $index; | |
| 863 | + } | |
| 864 | + } | |
| 865 | +			} else { | |
| 866 | + $index_in_cache = $object_to_remove_or_index_into_array; | |
| 867 | + } | |
| 868 | + // supposedly we've found it. But it could just be that the client code | |
| 869 | + // provided a bad index/object | |
| 870 | +			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) { | |
| 871 | + $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ]; | |
| 872 | + unset($this->_model_relations[ $relationName ][ $index_in_cache ]); | |
| 873 | +			} else { | |
| 874 | + // that thing was never cached anyways. | |
| 875 | + $obj_removed = null; | |
| 876 | + } | |
| 877 | + } | |
| 878 | + return $obj_removed; | |
| 879 | + } | |
| 880 | + | |
| 881 | + | |
| 882 | + /** | |
| 883 | + * update_cache_after_object_save | |
| 884 | + * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has | |
| 885 | + * obtained after being saved to the db | |
| 886 | + * | |
| 887 | + * @param string $relationName - the type of object that is cached | |
| 888 | + * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached | |
| 889 | + * @param string $current_cache_id - the ID that was used when originally caching the object | |
| 890 | + * @return boolean TRUE on success, FALSE on fail | |
| 891 | + * @throws ReflectionException | |
| 892 | + * @throws InvalidArgumentException | |
| 893 | + * @throws InvalidInterfaceException | |
| 894 | + * @throws InvalidDataTypeException | |
| 895 | + * @throws EE_Error | |
| 896 | + */ | |
| 897 | + public function update_cache_after_object_save( | |
| 898 | + $relationName, | |
| 899 | + EE_Base_Class $newly_saved_object, | |
| 900 | + $current_cache_id = '' | |
| 901 | +	) { | |
| 902 | + // verify that incoming object is of the correct type | |
| 903 | + $obj_class = 'EE_' . $relationName; | |
| 904 | +		if ($newly_saved_object instanceof $obj_class) { | |
| 905 | + /* @type EE_Base_Class $newly_saved_object */ | |
| 906 | + // now get the type of relation | |
| 907 | + $relationship_to_model = $this->get_model()->related_settings_for($relationName); | |
| 908 | + // if this is a 1:1 relationship | |
| 909 | +			if ($relationship_to_model instanceof EE_Belongs_To_Relation) { | |
| 910 | + // then just replace the cached object with the newly saved object | |
| 911 | + $this->_model_relations[ $relationName ] = $newly_saved_object; | |
| 912 | + return true; | |
| 913 | + // or if it's some kind of sordid feral polyamorous relationship... | |
| 914 | + } | |
| 915 | + if (is_array($this->_model_relations[ $relationName ]) | |
| 916 | + && isset($this->_model_relations[ $relationName ][ $current_cache_id ]) | |
| 917 | +			) { | |
| 918 | + // then remove the current cached item | |
| 919 | + unset($this->_model_relations[ $relationName ][ $current_cache_id ]); | |
| 920 | + // and cache the newly saved object using it's new ID | |
| 921 | + $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object; | |
| 922 | + return true; | |
| 923 | + } | |
| 924 | + } | |
| 925 | + return false; | |
| 926 | + } | |
| 927 | + | |
| 928 | + | |
| 929 | + /** | |
| 930 | + * Fetches a single EE_Base_Class on that relation. (If the relation is of type | |
| 931 | + * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects) | |
| 932 | + * | |
| 933 | + * @param string $relationName | |
| 934 | + * @return EE_Base_Class | |
| 935 | + */ | |
| 936 | + public function get_one_from_cache($relationName) | |
| 937 | +	{ | |
| 938 | + $cached_array_or_object = isset($this->_model_relations[ $relationName ]) | |
| 939 | + ? $this->_model_relations[ $relationName ] | |
| 940 | + : null; | |
| 941 | +		if (is_array($cached_array_or_object)) { | |
| 942 | + return array_shift($cached_array_or_object); | |
| 943 | + } | |
| 944 | + return $cached_array_or_object; | |
| 945 | + } | |
| 946 | + | |
| 947 | + | |
| 948 | + /** | |
| 949 | + * Fetches a single EE_Base_Class on that relation. (If the relation is of type | |
| 950 | + * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects) | |
| 951 | + * | |
| 952 | + * @param string $relationName | |
| 953 | + * @throws ReflectionException | |
| 954 | + * @throws InvalidArgumentException | |
| 955 | + * @throws InvalidInterfaceException | |
| 956 | + * @throws InvalidDataTypeException | |
| 957 | + * @throws EE_Error | |
| 958 | + * @return EE_Base_Class[] NOT necessarily indexed by primary keys | |
| 959 | + */ | |
| 960 | + public function get_all_from_cache($relationName) | |
| 961 | +	{ | |
| 962 | + $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array(); | |
| 963 | + // if the result is not an array, but exists, make it an array | |
| 964 | + $objects = is_array($objects) ? $objects : array($objects); | |
| 965 | + // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143 | |
| 966 | + // basically, if this model object was stored in the session, and these cached model objects | |
| 967 | + // already have IDs, let's make sure they're in their model's entity mapper | |
| 968 | + // otherwise we will have duplicates next time we call | |
| 969 | + // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() ); | |
| 970 | + $model = EE_Registry::instance()->load_model($relationName); | |
| 971 | +		foreach ($objects as $model_object) { | |
| 972 | +			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) { | |
| 973 | + // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved | |
| 974 | +				if ($model_object->ID()) { | |
| 975 | + $model->add_to_entity_map($model_object); | |
| 976 | + } | |
| 977 | +			} else { | |
| 978 | + throw new EE_Error( | |
| 979 | + sprintf( | |
| 980 | + esc_html__( | |
| 981 | + 'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object', | |
| 982 | + 'event_espresso' | |
| 983 | + ), | |
| 984 | + $relationName, | |
| 985 | + gettype($model_object) | |
| 986 | + ) | |
| 987 | + ); | |
| 988 | + } | |
| 989 | + } | |
| 990 | + return $objects; | |
| 991 | + } | |
| 992 | + | |
| 993 | + | |
| 994 | + /** | |
| 995 | + * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database | |
| 996 | + * matching the given query conditions. | |
| 997 | + * | |
| 998 | + * @param null $field_to_order_by What field is being used as the reference point. | |
| 999 | + * @param int $limit How many objects to return. | |
| 1000 | + * @param array $query_params Any additional conditions on the query. | |
| 1001 | + * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1002 | + * you can indicate just the columns you want returned | |
| 1003 | + * @return array|EE_Base_Class[] | |
| 1004 | + * @throws ReflectionException | |
| 1005 | + * @throws InvalidArgumentException | |
| 1006 | + * @throws InvalidInterfaceException | |
| 1007 | + * @throws InvalidDataTypeException | |
| 1008 | + * @throws EE_Error | |
| 1009 | + */ | |
| 1010 | + public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null) | |
| 1011 | +	{ | |
| 1012 | + $model = $this->get_model(); | |
| 1013 | + $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1014 | + ? $model->get_primary_key_field()->get_name() | |
| 1015 | + : $field_to_order_by; | |
| 1016 | + $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1017 | +		if (empty($field) || empty($current_value)) { | |
| 1018 | + return array(); | |
| 1019 | + } | |
| 1020 | + return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select); | |
| 1021 | + } | |
| 1022 | + | |
| 1023 | + | |
| 1024 | + /** | |
| 1025 | + * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database | |
| 1026 | + * matching the given query conditions. | |
| 1027 | + * | |
| 1028 | + * @param null $field_to_order_by What field is being used as the reference point. | |
| 1029 | + * @param int $limit How many objects to return. | |
| 1030 | + * @param array $query_params Any additional conditions on the query. | |
| 1031 | + * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1032 | + * you can indicate just the columns you want returned | |
| 1033 | + * @return array|EE_Base_Class[] | |
| 1034 | + * @throws ReflectionException | |
| 1035 | + * @throws InvalidArgumentException | |
| 1036 | + * @throws InvalidInterfaceException | |
| 1037 | + * @throws InvalidDataTypeException | |
| 1038 | + * @throws EE_Error | |
| 1039 | + */ | |
| 1040 | + public function previous_x( | |
| 1041 | + $field_to_order_by = null, | |
| 1042 | + $limit = 1, | |
| 1043 | + $query_params = array(), | |
| 1044 | + $columns_to_select = null | |
| 1045 | +	) { | |
| 1046 | + $model = $this->get_model(); | |
| 1047 | + $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1048 | + ? $model->get_primary_key_field()->get_name() | |
| 1049 | + : $field_to_order_by; | |
| 1050 | + $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1051 | +		if (empty($field) || empty($current_value)) { | |
| 1052 | + return array(); | |
| 1053 | + } | |
| 1054 | + return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select); | |
| 1055 | + } | |
| 1056 | + | |
| 1057 | + | |
| 1058 | + /** | |
| 1059 | + * Returns the next EE_Base_Class object in sequence from this object as found in the database | |
| 1060 | + * matching the given query conditions. | |
| 1061 | + * | |
| 1062 | + * @param null $field_to_order_by What field is being used as the reference point. | |
| 1063 | + * @param array $query_params Any additional conditions on the query. | |
| 1064 | + * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, otherwise | |
| 1065 | + * you can indicate just the columns you want returned | |
| 1066 | + * @return array|EE_Base_Class | |
| 1067 | + * @throws ReflectionException | |
| 1068 | + * @throws InvalidArgumentException | |
| 1069 | + * @throws InvalidInterfaceException | |
| 1070 | + * @throws InvalidDataTypeException | |
| 1071 | + * @throws EE_Error | |
| 1072 | + */ | |
| 1073 | + public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null) | |
| 1074 | +	{ | |
| 1075 | + $model = $this->get_model(); | |
| 1076 | + $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1077 | + ? $model->get_primary_key_field()->get_name() | |
| 1078 | + : $field_to_order_by; | |
| 1079 | + $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1080 | +		if (empty($field) || empty($current_value)) { | |
| 1081 | + return array(); | |
| 1082 | + } | |
| 1083 | + return $model->next($current_value, $field, $query_params, $columns_to_select); | |
| 1084 | + } | |
| 1085 | + | |
| 1086 | + | |
| 1087 | + /** | |
| 1088 | + * Returns the previous EE_Base_Class object in sequence from this object as found in the database | |
| 1089 | + * matching the given query conditions. | |
| 1090 | + * | |
| 1091 | + * @param null $field_to_order_by What field is being used as the reference point. | |
| 1092 | + * @param array $query_params Any additional conditions on the query. | |
| 1093 | + * @param null $columns_to_select If left null, then an EE_Base_Class object is returned, otherwise | |
| 1094 | + * you can indicate just the column you want returned | |
| 1095 | + * @return array|EE_Base_Class | |
| 1096 | + * @throws ReflectionException | |
| 1097 | + * @throws InvalidArgumentException | |
| 1098 | + * @throws InvalidInterfaceException | |
| 1099 | + * @throws InvalidDataTypeException | |
| 1100 | + * @throws EE_Error | |
| 1101 | + */ | |
| 1102 | + public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null) | |
| 1103 | +	{ | |
| 1104 | + $model = $this->get_model(); | |
| 1105 | + $field = empty($field_to_order_by) && $model->has_primary_key_field() | |
| 1106 | + ? $model->get_primary_key_field()->get_name() | |
| 1107 | + : $field_to_order_by; | |
| 1108 | + $current_value = ! empty($field) ? $this->get($field) : null; | |
| 1109 | +		if (empty($field) || empty($current_value)) { | |
| 1110 | + return array(); | |
| 1111 | + } | |
| 1112 | + return $model->previous($current_value, $field, $query_params, $columns_to_select); | |
| 1113 | + } | |
| 1114 | + | |
| 1115 | + | |
| 1116 | + /** | |
| 1117 | + * Overrides parent because parent expects old models. | |
| 1118 | + * This also doesn't do any validation, and won't work for serialized arrays | |
| 1119 | + * | |
| 1120 | + * @param string $field_name | |
| 1121 | + * @param mixed $field_value_from_db | |
| 1122 | + * @throws ReflectionException | |
| 1123 | + * @throws InvalidArgumentException | |
| 1124 | + * @throws InvalidInterfaceException | |
| 1125 | + * @throws InvalidDataTypeException | |
| 1126 | + * @throws EE_Error | |
| 1127 | + */ | |
| 1128 | + public function set_from_db($field_name, $field_value_from_db) | |
| 1129 | +	{ | |
| 1130 | + $field_obj = $this->get_model()->field_settings_for($field_name); | |
| 1131 | +		if ($field_obj instanceof EE_Model_Field_Base) { | |
| 1132 | + // you would think the DB has no NULLs for non-null label fields right? wrong! | |
| 1133 | + // eg, a CPT model object could have an entry in the posts table, but no | |
| 1134 | + // entry in the meta table. Meaning that all its columns in the meta table | |
| 1135 | + // are null! yikes! so when we find one like that, use defaults for its meta columns | |
| 1136 | +			if ($field_value_from_db === null) { | |
| 1137 | +				if ($field_obj->is_nullable()) { | |
| 1138 | + // if the field allows nulls, then let it be null | |
| 1139 | + $field_value = null; | |
| 1140 | +				} else { | |
| 1141 | + $field_value = $field_obj->get_default_value(); | |
| 1142 | + } | |
| 1143 | +			} else { | |
| 1144 | + $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db); | |
| 1145 | + } | |
| 1146 | + $this->_fields[ $field_name ] = $field_value; | |
| 1147 | + $this->_clear_cached_property($field_name); | |
| 1148 | + } | |
| 1149 | + } | |
| 1150 | + | |
| 1151 | + | |
| 1152 | + /** | |
| 1153 | + * verifies that the specified field is of the correct type | |
| 1154 | + * | |
| 1155 | + * @param string $field_name | |
| 1156 | + * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1157 | + * (in cases where the same property may be used for different outputs | |
| 1158 | + * - i.e. datetime, money etc.) | |
| 1159 | + * @return mixed | |
| 1160 | + * @throws ReflectionException | |
| 1161 | + * @throws InvalidArgumentException | |
| 1162 | + * @throws InvalidInterfaceException | |
| 1163 | + * @throws InvalidDataTypeException | |
| 1164 | + * @throws EE_Error | |
| 1165 | + */ | |
| 1166 | + public function get($field_name, $extra_cache_ref = null) | |
| 1167 | +	{ | |
| 1168 | + return $this->_get_cached_property($field_name, false, $extra_cache_ref); | |
| 1169 | + } | |
| 1170 | + | |
| 1171 | + | |
| 1172 | + /** | |
| 1173 | + * This method simply returns the RAW unprocessed value for the given property in this class | |
| 1174 | + * | |
| 1175 | + * @param string $field_name A valid fieldname | |
| 1176 | + * @return mixed Whatever the raw value stored on the property is. | |
| 1177 | + * @throws ReflectionException | |
| 1178 | + * @throws InvalidArgumentException | |
| 1179 | + * @throws InvalidInterfaceException | |
| 1180 | + * @throws InvalidDataTypeException | |
| 1181 | + * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist. | |
| 1182 | + */ | |
| 1183 | + public function get_raw($field_name) | |
| 1184 | +	{ | |
| 1185 | + $field_settings = $this->get_model()->field_settings_for($field_name); | |
| 1186 | + return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime | |
| 1187 | +			? $this->_fields[ $field_name ]->format('U') | |
| 1188 | + : $this->_fields[ $field_name ]; | |
| 1189 | + } | |
| 1190 | + | |
| 1191 | + | |
| 1192 | + /** | |
| 1193 | + * This is used to return the internal DateTime object used for a field that is a | |
| 1194 | + * EE_Datetime_Field. | |
| 1195 | + * | |
| 1196 | + * @param string $field_name The field name retrieving the DateTime object. | |
| 1197 | + * @return mixed null | false | DateTime If the requested field is NOT a EE_Datetime_Field then | |
| 1198 | + * @throws EE_Error an error is set and false returned. If the field IS an | |
| 1199 | + * EE_Datetime_Field and but the field value is null, then | |
| 1200 | + * just null is returned (because that indicates that likely | |
| 1201 | + * this field is nullable). | |
| 1202 | + * @throws InvalidArgumentException | |
| 1203 | + * @throws InvalidDataTypeException | |
| 1204 | + * @throws InvalidInterfaceException | |
| 1205 | + * @throws ReflectionException | |
| 1206 | + */ | |
| 1207 | + public function get_DateTime_object($field_name) | |
| 1208 | +	{ | |
| 1209 | + $field_settings = $this->get_model()->field_settings_for($field_name); | |
| 1210 | +		if (! $field_settings instanceof EE_Datetime_Field) { | |
| 1211 | + EE_Error::add_error( | |
| 1212 | + sprintf( | |
| 1213 | + esc_html__( | |
| 1214 | + 'The field %s is not an EE_Datetime_Field field. There is no DateTime object stored on this field type.', | |
| 1215 | + 'event_espresso' | |
| 1216 | + ), | |
| 1217 | + $field_name | |
| 1218 | + ), | |
| 1219 | + __FILE__, | |
| 1220 | + __FUNCTION__, | |
| 1221 | + __LINE__ | |
| 1222 | + ); | |
| 1223 | + return false; | |
| 1224 | + } | |
| 1225 | + return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime | |
| 1226 | + ? clone $this->_fields[ $field_name ] | |
| 1227 | + : null; | |
| 1228 | + } | |
| 1229 | + | |
| 1230 | + | |
| 1231 | + /** | |
| 1232 | + * To be used in template to immediately echo out the value, and format it for output. | |
| 1233 | + * Eg, should call stripslashes and whatnot before echoing | |
| 1234 | + * | |
| 1235 | + * @param string $field_name the name of the field as it appears in the DB | |
| 1236 | + * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1237 | + * (in cases where the same property may be used for different outputs | |
| 1238 | + * - i.e. datetime, money etc.) | |
| 1239 | + * @return void | |
| 1240 | + * @throws ReflectionException | |
| 1241 | + * @throws InvalidArgumentException | |
| 1242 | + * @throws InvalidInterfaceException | |
| 1243 | + * @throws InvalidDataTypeException | |
| 1244 | + * @throws EE_Error | |
| 1245 | + */ | |
| 1246 | + public function e($field_name, $extra_cache_ref = null) | |
| 1247 | +	{ | |
| 1248 | + echo $this->get_pretty($field_name, $extra_cache_ref); | |
| 1249 | + } | |
| 1250 | + | |
| 1251 | + | |
| 1252 | + /** | |
| 1253 | + * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it | |
| 1254 | + * can be easily used as the value of form input. | |
| 1255 | + * | |
| 1256 | + * @param string $field_name | |
| 1257 | + * @return void | |
| 1258 | + * @throws ReflectionException | |
| 1259 | + * @throws InvalidArgumentException | |
| 1260 | + * @throws InvalidInterfaceException | |
| 1261 | + * @throws InvalidDataTypeException | |
| 1262 | + * @throws EE_Error | |
| 1263 | + */ | |
| 1264 | + public function f($field_name) | |
| 1265 | +	{ | |
| 1266 | + $this->e($field_name, 'form_input'); | |
| 1267 | + } | |
| 1268 | + | |
| 1269 | + | |
| 1270 | + /** | |
| 1271 | + * Same as `f()` but just returns the value instead of echoing it | |
| 1272 | + * | |
| 1273 | + * @param string $field_name | |
| 1274 | + * @return string | |
| 1275 | + * @throws ReflectionException | |
| 1276 | + * @throws InvalidArgumentException | |
| 1277 | + * @throws InvalidInterfaceException | |
| 1278 | + * @throws InvalidDataTypeException | |
| 1279 | + * @throws EE_Error | |
| 1280 | + */ | |
| 1281 | + public function get_f($field_name) | |
| 1282 | +	{ | |
| 1283 | + return (string) $this->get_pretty($field_name, 'form_input'); | |
| 1284 | + } | |
| 1285 | + | |
| 1286 | + | |
| 1287 | + /** | |
| 1288 | + * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this. | |
| 1289 | + * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class | |
| 1290 | + * to see what options are available. | |
| 1291 | + * | |
| 1292 | + * @param string $field_name | |
| 1293 | + * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property | |
| 1294 | + * (in cases where the same property may be used for different outputs | |
| 1295 | + * - i.e. datetime, money etc.) | |
| 1296 | + * @return mixed | |
| 1297 | + * @throws ReflectionException | |
| 1298 | + * @throws InvalidArgumentException | |
| 1299 | + * @throws InvalidInterfaceException | |
| 1300 | + * @throws InvalidDataTypeException | |
| 1301 | + * @throws EE_Error | |
| 1302 | + */ | |
| 1303 | + public function get_pretty($field_name, $extra_cache_ref = null) | |
| 1304 | +	{ | |
| 1305 | + return $this->_get_cached_property($field_name, true, $extra_cache_ref); | |
| 1306 | + } | |
| 1307 | + | |
| 1308 | + | |
| 1309 | + /** | |
| 1310 | + * This simply returns the datetime for the given field name | |
| 1311 | + * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions | |
| 1312 | + * (and the equivalent e_date, e_time, e_datetime). | |
| 1313 | + * | |
| 1314 | + * @access protected | |
| 1315 | + * @param string $field_name Field on the instantiated EE_Base_Class child object | |
| 1316 | + * @param string $dt_frmt valid datetime format used for date | |
| 1317 | + * (if '' then we just use the default on the field, | |
| 1318 | + * if NULL we use the last-used format) | |
| 1319 | + * @param string $tm_frmt Same as above except this is for time format | |
| 1320 | + * @param string $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time. | |
| 1321 | + * @param boolean $echo Whether the dtt is echoing using pretty echoing or just returned using vanilla get | |
| 1322 | + * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown | |
| 1323 | + * if field is not a valid dtt field, or void if echoing | |
| 1324 | + * @throws ReflectionException | |
| 1325 | + * @throws InvalidArgumentException | |
| 1326 | + * @throws InvalidInterfaceException | |
| 1327 | + * @throws InvalidDataTypeException | |
| 1328 | + * @throws EE_Error | |
| 1329 | + */ | |
| 1330 | + protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false) | |
| 1331 | +	{ | |
| 1332 | + // clear cached property | |
| 1333 | + $this->_clear_cached_property($field_name); | |
| 1334 | + // reset format properties because they are used in get() | |
| 1335 | + $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt; | |
| 1336 | + $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt; | |
| 1337 | +		if ($echo) { | |
| 1338 | + $this->e($field_name, $date_or_time); | |
| 1339 | + return ''; | |
| 1340 | + } | |
| 1341 | + return $this->get($field_name, $date_or_time); | |
| 1342 | + } | |
| 1343 | + | |
| 1344 | + | |
| 1345 | + /** | |
| 1346 | + * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date | |
| 1347 | + * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1348 | + * other echoes the pretty value for dtt) | |
| 1349 | + * | |
| 1350 | + * @param string $field_name name of model object datetime field holding the value | |
| 1351 | + * @param string $format format for the date returned (if NULL we use default in dt_frmt property) | |
| 1352 | + * @return string datetime value formatted | |
| 1353 | + * @throws ReflectionException | |
| 1354 | + * @throws InvalidArgumentException | |
| 1355 | + * @throws InvalidInterfaceException | |
| 1356 | + * @throws InvalidDataTypeException | |
| 1357 | + * @throws EE_Error | |
| 1358 | + */ | |
| 1359 | + public function get_date($field_name, $format = '') | |
| 1360 | +	{ | |
| 1361 | + return $this->_get_datetime($field_name, $format, null, 'D'); | |
| 1362 | + } | |
| 1363 | + | |
| 1364 | + | |
| 1365 | + /** | |
| 1366 | + * @param $field_name | |
| 1367 | + * @param string $format | |
| 1368 | + * @throws ReflectionException | |
| 1369 | + * @throws InvalidArgumentException | |
| 1370 | + * @throws InvalidInterfaceException | |
| 1371 | + * @throws InvalidDataTypeException | |
| 1372 | + * @throws EE_Error | |
| 1373 | + */ | |
| 1374 | + public function e_date($field_name, $format = '') | |
| 1375 | +	{ | |
| 1376 | + $this->_get_datetime($field_name, $format, null, 'D', true); | |
| 1377 | + } | |
| 1378 | + | |
| 1379 | + | |
| 1380 | + /** | |
| 1381 | + * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time | |
| 1382 | + * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1383 | + * other echoes the pretty value for dtt) | |
| 1384 | + * | |
| 1385 | + * @param string $field_name name of model object datetime field holding the value | |
| 1386 | + * @param string $format format for the time returned ( if NULL we use default in tm_frmt property) | |
| 1387 | + * @return string datetime value formatted | |
| 1388 | + * @throws ReflectionException | |
| 1389 | + * @throws InvalidArgumentException | |
| 1390 | + * @throws InvalidInterfaceException | |
| 1391 | + * @throws InvalidDataTypeException | |
| 1392 | + * @throws EE_Error | |
| 1393 | + */ | |
| 1394 | + public function get_time($field_name, $format = '') | |
| 1395 | +	{ | |
| 1396 | + return $this->_get_datetime($field_name, null, $format, 'T'); | |
| 1397 | + } | |
| 1398 | + | |
| 1399 | + | |
| 1400 | + /** | |
| 1401 | + * @param $field_name | |
| 1402 | + * @param string $format | |
| 1403 | + * @throws ReflectionException | |
| 1404 | + * @throws InvalidArgumentException | |
| 1405 | + * @throws InvalidInterfaceException | |
| 1406 | + * @throws InvalidDataTypeException | |
| 1407 | + * @throws EE_Error | |
| 1408 | + */ | |
| 1409 | + public function e_time($field_name, $format = '') | |
| 1410 | +	{ | |
| 1411 | + $this->_get_datetime($field_name, null, $format, 'T', true); | |
| 1412 | + } | |
| 1413 | + | |
| 1414 | + | |
| 1415 | + /** | |
| 1416 | + * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND | |
| 1417 | + * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the | |
| 1418 | + * other echoes the pretty value for dtt) | |
| 1419 | + * | |
| 1420 | + * @param string $field_name name of model object datetime field holding the value | |
| 1421 | + * @param string $dt_frmt format for the date returned (if NULL we use default in dt_frmt property) | |
| 1422 | + * @param string $tm_frmt format for the time returned (if NULL we use default in tm_frmt property) | |
| 1423 | + * @return string datetime value formatted | |
| 1424 | + * @throws ReflectionException | |
| 1425 | + * @throws InvalidArgumentException | |
| 1426 | + * @throws InvalidInterfaceException | |
| 1427 | + * @throws InvalidDataTypeException | |
| 1428 | + * @throws EE_Error | |
| 1429 | + */ | |
| 1430 | + public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '') | |
| 1431 | +	{ | |
| 1432 | + return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt); | |
| 1433 | + } | |
| 1434 | + | |
| 1435 | + | |
| 1436 | + /** | |
| 1437 | + * @param string $field_name | |
| 1438 | + * @param string $dt_frmt | |
| 1439 | + * @param string $tm_frmt | |
| 1440 | + * @throws ReflectionException | |
| 1441 | + * @throws InvalidArgumentException | |
| 1442 | + * @throws InvalidInterfaceException | |
| 1443 | + * @throws InvalidDataTypeException | |
| 1444 | + * @throws EE_Error | |
| 1445 | + */ | |
| 1446 | + public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '') | |
| 1447 | +	{ | |
| 1448 | + $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true); | |
| 1449 | + } | |
| 1450 | + | |
| 1451 | + | |
| 1452 | + /** | |
| 1453 | + * Get the i8ln value for a date using the WordPress @see date_i18n function. | |
| 1454 | + * | |
| 1455 | + * @param string $field_name The EE_Datetime_Field reference for the date being retrieved. | |
| 1456 | + * @param string $format PHP valid date/time string format. If none is provided then the internal set format | |
| 1457 | + * on the object will be used. | |
| 1458 | + * @return string Date and time string in set locale or false if no field exists for the given | |
| 1459 | + * @throws ReflectionException | |
| 1460 | + * @throws InvalidArgumentException | |
| 1461 | + * @throws InvalidInterfaceException | |
| 1462 | + * @throws InvalidDataTypeException | |
| 1463 | + * @throws EE_Error | |
| 1464 | + * field name. | |
| 1465 | + */ | |
| 1466 | + public function get_i18n_datetime($field_name, $format = '') | |
| 1467 | +	{ | |
| 1468 | + $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format; | |
| 1469 | + return date_i18n( | |
| 1470 | + $format, | |
| 1471 | + EEH_DTT_Helper::get_timestamp_with_offset( | |
| 1472 | + $this->get_raw($field_name), | |
| 1473 | + $this->_timezone | |
| 1474 | + ) | |
| 1475 | + ); | |
| 1476 | + } | |
| 1477 | + | |
| 1478 | + | |
| 1479 | + /** | |
| 1480 | + * This method validates whether the given field name is a valid field on the model object as well as it is of a | |
| 1481 | + * type EE_Datetime_Field. On success there will be returned the field settings. On fail an EE_Error exception is | |
| 1482 | + * thrown. | |
| 1483 | + * | |
| 1484 | + * @param string $field_name The field name being checked | |
| 1485 | + * @throws ReflectionException | |
| 1486 | + * @throws InvalidArgumentException | |
| 1487 | + * @throws InvalidInterfaceException | |
| 1488 | + * @throws InvalidDataTypeException | |
| 1489 | + * @throws EE_Error | |
| 1490 | + * @return EE_Datetime_Field | |
| 1491 | + */ | |
| 1492 | + protected function _get_dtt_field_settings($field_name) | |
| 1493 | +	{ | |
| 1494 | + $field = $this->get_model()->field_settings_for($field_name); | |
| 1495 | + // check if field is dtt | |
| 1496 | +		if ($field instanceof EE_Datetime_Field) { | |
| 1497 | + return $field; | |
| 1498 | + } | |
| 1499 | + throw new EE_Error( | |
| 1500 | + sprintf( | |
| 1501 | + esc_html__( | |
| 1502 | + 'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field. Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor', | |
| 1503 | + 'event_espresso' | |
| 1504 | + ), | |
| 1505 | + $field_name, | |
| 1506 | + self::_get_model_classname(get_class($this)) | |
| 1507 | + ) | |
| 1508 | + ); | |
| 1509 | + } | |
| 1510 | + | |
| 1511 | + | |
| 1512 | + | |
| 1513 | + | |
| 1514 | + /** | |
| 1515 | + * NOTE ABOUT BELOW: | |
| 1516 | + * These convenience date and time setters are for setting date and time independently. In other words you might | |
| 1517 | + * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand | |
| 1518 | + * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value) | |
| 1519 | + * method and make sure you send the entire datetime value for setting. | |
| 1520 | + */ | |
| 1521 | + /** | |
| 1522 | + * sets the time on a datetime property | |
| 1523 | + * | |
| 1524 | + * @access protected | |
| 1525 | + * @param string|Datetime $time a valid time string for php datetime functions (or DateTime object) | |
| 1526 | + * @param string $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field) | |
| 1527 | + * @throws ReflectionException | |
| 1528 | + * @throws InvalidArgumentException | |
| 1529 | + * @throws InvalidInterfaceException | |
| 1530 | + * @throws InvalidDataTypeException | |
| 1531 | + * @throws EE_Error | |
| 1532 | + */ | |
| 1533 | + protected function _set_time_for($time, $fieldname) | |
| 1534 | +	{ | |
| 1535 | +		$this->_set_date_time('T', $time, $fieldname); | |
| 1536 | + } | |
| 1537 | + | |
| 1538 | + | |
| 1539 | + /** | |
| 1540 | + * sets the date on a datetime property | |
| 1541 | + * | |
| 1542 | + * @access protected | |
| 1543 | + * @param string|DateTime $date a valid date string for php datetime functions ( or DateTime object) | |
| 1544 | + * @param string $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field) | |
| 1545 | + * @throws ReflectionException | |
| 1546 | + * @throws InvalidArgumentException | |
| 1547 | + * @throws InvalidInterfaceException | |
| 1548 | + * @throws InvalidDataTypeException | |
| 1549 | + * @throws EE_Error | |
| 1550 | + */ | |
| 1551 | + protected function _set_date_for($date, $fieldname) | |
| 1552 | +	{ | |
| 1553 | +		$this->_set_date_time('D', $date, $fieldname); | |
| 1554 | + } | |
| 1555 | + | |
| 1556 | + | |
| 1557 | + /** | |
| 1558 | + * This takes care of setting a date or time independently on a given model object property. This method also | |
| 1559 | + * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field | |
| 1560 | + * | |
| 1561 | + * @access protected | |
| 1562 | + * @param string $what "T" for time, 'B' for both, 'D' for Date. | |
| 1563 | + * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object) | |
| 1564 | + * @param string $fieldname the name of the field the date OR time is being set on (must match a | |
| 1565 | + * EE_Datetime_Field property) | |
| 1566 | + * @throws ReflectionException | |
| 1567 | + * @throws InvalidArgumentException | |
| 1568 | + * @throws InvalidInterfaceException | |
| 1569 | + * @throws InvalidDataTypeException | |
| 1570 | + * @throws EE_Error | |
| 1571 | + */ | |
| 1572 | + protected function _set_date_time($what = 'T', $datetime_value, $fieldname) | |
| 1573 | +	{ | |
| 1574 | + $field = $this->_get_dtt_field_settings($fieldname); | |
| 1575 | + $field->set_timezone($this->_timezone); | |
| 1576 | + $field->set_date_format($this->_dt_frmt); | |
| 1577 | + $field->set_time_format($this->_tm_frmt); | |
| 1578 | +		switch ($what) { | |
| 1579 | + case 'T': | |
| 1580 | + $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time( | |
| 1581 | + $datetime_value, | |
| 1582 | + $this->_fields[ $fieldname ] | |
| 1583 | + ); | |
| 1584 | + break; | |
| 1585 | + case 'D': | |
| 1586 | + $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date( | |
| 1587 | + $datetime_value, | |
| 1588 | + $this->_fields[ $fieldname ] | |
| 1589 | + ); | |
| 1590 | + break; | |
| 1591 | + case 'B': | |
| 1592 | + $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value); | |
| 1593 | + break; | |
| 1594 | + } | |
| 1595 | + $this->_clear_cached_property($fieldname); | |
| 1596 | + } | |
| 1597 | + | |
| 1598 | + | |
| 1599 | + /** | |
| 1600 | + * This will return a timestamp for the website timezone but ONLY when the current website timezone is different | |
| 1601 | + * than the timezone set for the website. NOTE, this currently only works well with methods that return values. If | |
| 1602 | + * you use it with methods that echo values the $_timestamp property may not get reset to its original value and | |
| 1603 | + * that could lead to some unexpected results! | |
| 1604 | + * | |
| 1605 | + * @access public | |
| 1606 | + * @param string $field_name This is the name of the field on the object that contains the date/time | |
| 1607 | + * value being returned. | |
| 1608 | + * @param string $callback must match a valid method in this class (defaults to get_datetime) | |
| 1609 | + * @param mixed (array|string) $args This is the arguments that will be passed to the callback. | |
| 1610 | + * @param string $prepend You can include something to prepend on the timestamp | |
| 1611 | + * @param string $append You can include something to append on the timestamp | |
| 1612 | + * @throws ReflectionException | |
| 1613 | + * @throws InvalidArgumentException | |
| 1614 | + * @throws InvalidInterfaceException | |
| 1615 | + * @throws InvalidDataTypeException | |
| 1616 | + * @throws EE_Error | |
| 1617 | + * @return string timestamp | |
| 1618 | + */ | |
| 1619 | + public function display_in_my_timezone( | |
| 1620 | + $field_name, | |
| 1621 | + $callback = 'get_datetime', | |
| 1622 | + $args = null, | |
| 1623 | + $prepend = '', | |
| 1624 | + $append = '' | |
| 1625 | +	) { | |
| 1626 | + $timezone = EEH_DTT_Helper::get_timezone(); | |
| 1627 | +		if ($timezone === $this->_timezone) { | |
| 1628 | + return ''; | |
| 1629 | + } | |
| 1630 | + $original_timezone = $this->_timezone; | |
| 1631 | + $this->set_timezone($timezone); | |
| 1632 | + $fn = (array) $field_name; | |
| 1633 | + $args = array_merge($fn, (array) $args); | |
| 1634 | +		if (! method_exists($this, $callback)) { | |
| 1635 | + throw new EE_Error( | |
| 1636 | + sprintf( | |
| 1637 | + esc_html__( | |
| 1638 | + 'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist. Please check your spelling', | |
| 1639 | + 'event_espresso' | |
| 1640 | + ), | |
| 1641 | + $callback | |
| 1642 | + ) | |
| 1643 | + ); | |
| 1644 | + } | |
| 1645 | + $args = (array) $args; | |
| 1646 | + $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append; | |
| 1647 | + $this->set_timezone($original_timezone); | |
| 1648 | + return $return; | |
| 1649 | + } | |
| 1650 | + | |
| 1651 | + | |
| 1652 | + /** | |
| 1653 | + * Deletes this model object. | |
| 1654 | + * This calls the `EE_Base_Class::_delete` method. Child classes wishing to change default behaviour should | |
| 1655 | + * override | |
| 1656 | + * `EE_Base_Class::_delete` NOT this class. | |
| 1657 | + * | |
| 1658 | + * @return boolean | int | |
| 1659 | + * @throws ReflectionException | |
| 1660 | + * @throws InvalidArgumentException | |
| 1661 | + * @throws InvalidInterfaceException | |
| 1662 | + * @throws InvalidDataTypeException | |
| 1663 | + * @throws EE_Error | |
| 1664 | + */ | |
| 1665 | + public function delete() | |
| 1666 | +	{ | |
| 1667 | + /** | |
| 1668 | + * Called just before the `EE_Base_Class::_delete` method call. | |
| 1669 | + * Note: | |
| 1670 | + * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions | |
| 1671 | + * should be aware that `_delete` may not always result in a permanent delete. | |
| 1672 | + * For example, `EE_Soft_Delete_Base_Class::_delete` | |
| 1673 | + * soft deletes (trash) the object and does not permanently delete it. | |
| 1674 | + * | |
| 1675 | + * @param EE_Base_Class $model_object about to be 'deleted' | |
| 1676 | + */ | |
| 1677 | +		do_action('AHEE__EE_Base_Class__delete__before', $this); | |
| 1678 | + $result = $this->_delete(); | |
| 1679 | + /** | |
| 1680 | + * Called just after the `EE_Base_Class::_delete` method call. | |
| 1681 | + * Note: | |
| 1682 | + * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions | |
| 1683 | + * should be aware that `_delete` may not always result in a permanent delete. | |
| 1684 | + * For example `EE_Soft_Base_Class::_delete` | |
| 1685 | + * soft deletes (trash) the object and does not permanently delete it. | |
| 1686 | + * | |
| 1687 | + * @param EE_Base_Class $model_object that was just 'deleted' | |
| 1688 | + * @param boolean $result | |
| 1689 | + */ | |
| 1690 | +		do_action('AHEE__EE_Base_Class__delete__end', $this, $result); | |
| 1691 | + return $result; | |
| 1692 | + } | |
| 1693 | + | |
| 1694 | + | |
| 1695 | + /** | |
| 1696 | + * Calls the specific delete method for the instantiated class. | |
| 1697 | + * This method is called by the public `EE_Base_Class::delete` method. Any child classes desiring to override | |
| 1698 | + * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT | |
| 1699 | + * `EE_Base_Class::delete` | |
| 1700 | + * | |
| 1701 | + * @return bool|int | |
| 1702 | + * @throws ReflectionException | |
| 1703 | + * @throws InvalidArgumentException | |
| 1704 | + * @throws InvalidInterfaceException | |
| 1705 | + * @throws InvalidDataTypeException | |
| 1706 | + * @throws EE_Error | |
| 1707 | + */ | |
| 1708 | + protected function _delete() | |
| 1709 | +	{ | |
| 1710 | + return $this->delete_permanently(); | |
| 1711 | + } | |
| 1712 | + | |
| 1713 | + | |
| 1714 | + /** | |
| 1715 | + * Deletes this model object permanently from db | |
| 1716 | + * (but keep in mind related models may block the delete and return an error) | |
| 1717 | + * | |
| 1718 | + * @return bool | int | |
| 1719 | + * @throws ReflectionException | |
| 1720 | + * @throws InvalidArgumentException | |
| 1721 | + * @throws InvalidInterfaceException | |
| 1722 | + * @throws InvalidDataTypeException | |
| 1723 | + * @throws EE_Error | |
| 1724 | + */ | |
| 1725 | + public function delete_permanently() | |
| 1726 | +	{ | |
| 1727 | + /** | |
| 1728 | + * Called just before HARD deleting a model object | |
| 1729 | + * | |
| 1730 | + * @param EE_Base_Class $model_object about to be 'deleted' | |
| 1731 | + */ | |
| 1732 | +		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this); | |
| 1733 | + $model = $this->get_model(); | |
| 1734 | + $result = $model->delete_permanently_by_ID($this->ID()); | |
| 1735 | + $this->refresh_cache_of_related_objects(); | |
| 1736 | + /** | |
| 1737 | + * Called just after HARD deleting a model object | |
| 1738 | + * | |
| 1739 | + * @param EE_Base_Class $model_object that was just 'deleted' | |
| 1740 | + * @param boolean $result | |
| 1741 | + */ | |
| 1742 | +		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result); | |
| 1743 | + return $result; | |
| 1744 | + } | |
| 1745 | + | |
| 1746 | + | |
| 1747 | + /** | |
| 1748 | + * When this model object is deleted, it may still be cached on related model objects. This clears the cache of | |
| 1749 | + * related model objects | |
| 1750 | + * | |
| 1751 | + * @throws ReflectionException | |
| 1752 | + * @throws InvalidArgumentException | |
| 1753 | + * @throws InvalidInterfaceException | |
| 1754 | + * @throws InvalidDataTypeException | |
| 1755 | + * @throws EE_Error | |
| 1756 | + */ | |
| 1757 | + public function refresh_cache_of_related_objects() | |
| 1758 | +	{ | |
| 1759 | + $model = $this->get_model(); | |
| 1760 | +		foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 1761 | +			if (! empty($this->_model_relations[ $relation_name ])) { | |
| 1762 | + $related_objects = $this->_model_relations[ $relation_name ]; | |
| 1763 | +				if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 1764 | + // this relation only stores a single model object, not an array | |
| 1765 | + // but let's make it consistent | |
| 1766 | + $related_objects = array($related_objects); | |
| 1767 | + } | |
| 1768 | +				foreach ($related_objects as $related_object) { | |
| 1769 | + // only refresh their cache if they're in memory | |
| 1770 | +					if ($related_object instanceof EE_Base_Class) { | |
| 1771 | + $related_object->clear_cache( | |
| 1772 | + $model->get_this_model_name(), | |
| 1773 | + $this | |
| 1774 | + ); | |
| 1775 | + } | |
| 1776 | + } | |
| 1777 | + } | |
| 1778 | + } | |
| 1779 | + } | |
| 1780 | + | |
| 1781 | + | |
| 1782 | + /** | |
| 1783 | + * Saves this object to the database. An array may be supplied to set some values on this | |
| 1784 | + * object just before saving. | |
| 1785 | + * | |
| 1786 | + * @access public | |
| 1787 | + * @param array $set_cols_n_values keys are field names, values are their new values, | |
| 1788 | + * if provided during the save() method (often client code will change the fields' | |
| 1789 | + * values before calling save) | |
| 1790 | + * @throws InvalidArgumentException | |
| 1791 | + * @throws InvalidInterfaceException | |
| 1792 | + * @throws InvalidDataTypeException | |
| 1793 | + * @throws EE_Error | |
| 1794 | + * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object | |
| 1795 | + * isn't allowed to persist (as determined by EE_Base_Class::allow_persist()) | |
| 1796 | + * @throws ReflectionException | |
| 1797 | + * @throws ReflectionException | |
| 1798 | + * @throws ReflectionException | |
| 1799 | + */ | |
| 1800 | + public function save($set_cols_n_values = array()) | |
| 1801 | +	{ | |
| 1802 | + $model = $this->get_model(); | |
| 1803 | + /** | |
| 1804 | + * Filters the fields we're about to save on the model object | |
| 1805 | + * | |
| 1806 | + * @param array $set_cols_n_values | |
| 1807 | + * @param EE_Base_Class $model_object | |
| 1808 | + */ | |
| 1809 | + $set_cols_n_values = (array) apply_filters( | |
| 1810 | + 'FHEE__EE_Base_Class__save__set_cols_n_values', | |
| 1811 | + $set_cols_n_values, | |
| 1812 | + $this | |
| 1813 | + ); | |
| 1814 | + // set attributes as provided in $set_cols_n_values | |
| 1815 | +		foreach ($set_cols_n_values as $column => $value) { | |
| 1816 | + $this->set($column, $value); | |
| 1817 | + } | |
| 1818 | + // no changes ? then don't do anything | |
| 1819 | +		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) { | |
| 1820 | + return 0; | |
| 1821 | + } | |
| 1822 | + /** | |
| 1823 | + * Saving a model object. | |
| 1824 | + * Before we perform a save, this action is fired. | |
| 1825 | + * | |
| 1826 | + * @param EE_Base_Class $model_object the model object about to be saved. | |
| 1827 | + */ | |
| 1828 | +		do_action('AHEE__EE_Base_Class__save__begin', $this); | |
| 1829 | +		if (! $this->allow_persist()) { | |
| 1830 | + return 0; | |
| 1831 | + } | |
| 1832 | + // now get current attribute values | |
| 1833 | + $save_cols_n_values = $this->_fields; | |
| 1834 | + // if the object already has an ID, update it. Otherwise, insert it | |
| 1835 | + // also: change the assumption about values passed to the model NOT being prepare dby the model object. | |
| 1836 | + // They have been | |
| 1837 | + $old_assumption_concerning_value_preparation = $model | |
| 1838 | + ->get_assumption_concerning_values_already_prepared_by_model_object(); | |
| 1839 | + $model->assume_values_already_prepared_by_model_object(true); | |
| 1840 | + // does this model have an autoincrement PK? | |
| 1841 | +		if ($model->has_primary_key_field()) { | |
| 1842 | +			if ($model->get_primary_key_field()->is_auto_increment()) { | |
| 1843 | + // ok check if it's set, if so: update; if not, insert | |
| 1844 | +				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) { | |
| 1845 | + $results = $model->update_by_ID($save_cols_n_values, $this->ID()); | |
| 1846 | +				} else { | |
| 1847 | + unset($save_cols_n_values[ $model->primary_key_name() ]); | |
| 1848 | + $results = $model->insert($save_cols_n_values); | |
| 1849 | +					if ($results) { | |
| 1850 | + // if successful, set the primary key | |
| 1851 | + // but don't use the normal SET method, because it will check if | |
| 1852 | + // an item with the same ID exists in the mapper & db, then | |
| 1853 | + // will find it in the db (because we just added it) and THAT object | |
| 1854 | + // will get added to the mapper before we can add this one! | |
| 1855 | + // but if we just avoid using the SET method, all that headache can be avoided | |
| 1856 | + $pk_field_name = $model->primary_key_name(); | |
| 1857 | + $this->_fields[ $pk_field_name ] = $results; | |
| 1858 | + $this->_clear_cached_property($pk_field_name); | |
| 1859 | + $model->add_to_entity_map($this); | |
| 1860 | + $this->_update_cached_related_model_objs_fks(); | |
| 1861 | + } | |
| 1862 | + } | |
| 1863 | +			} else {// PK is NOT auto-increment | |
| 1864 | + // so check if one like it already exists in the db | |
| 1865 | +				if ($model->exists_by_ID($this->ID())) { | |
| 1866 | +					if (WP_DEBUG && ! $this->in_entity_map()) { | |
| 1867 | + throw new EE_Error( | |
| 1868 | + sprintf( | |
| 1869 | + esc_html__( | |
| 1870 | + 'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s', | |
| 1871 | + 'event_espresso' | |
| 1872 | + ), | |
| 1873 | + get_class($this), | |
| 1874 | + get_class($model) . '::instance()->add_to_entity_map()', | |
| 1875 | + get_class($model) . '::instance()->get_one_by_ID()', | |
| 1876 | + '<br />' | |
| 1877 | + ) | |
| 1878 | + ); | |
| 1879 | + } | |
| 1880 | + $results = $model->update_by_ID($save_cols_n_values, $this->ID()); | |
| 1881 | +				} else { | |
| 1882 | + $results = $model->insert($save_cols_n_values); | |
| 1883 | + $this->_update_cached_related_model_objs_fks(); | |
| 1884 | + } | |
| 1885 | + } | |
| 1886 | +		} else {// there is NO primary key | |
| 1887 | + $already_in_db = false; | |
| 1888 | +			foreach ($model->unique_indexes() as $index) { | |
| 1889 | + $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields()); | |
| 1890 | +				if ($model->exists(array($uniqueness_where_params))) { | |
| 1891 | + $already_in_db = true; | |
| 1892 | + } | |
| 1893 | + } | |
| 1894 | +			if ($already_in_db) { | |
| 1895 | + $combined_pk_fields_n_values = array_intersect_key( | |
| 1896 | + $save_cols_n_values, | |
| 1897 | + $model->get_combined_primary_key_fields() | |
| 1898 | + ); | |
| 1899 | + $results = $model->update( | |
| 1900 | + $save_cols_n_values, | |
| 1901 | + $combined_pk_fields_n_values | |
| 1902 | + ); | |
| 1903 | +			} else { | |
| 1904 | + $results = $model->insert($save_cols_n_values); | |
| 1905 | + } | |
| 1906 | + } | |
| 1907 | + // restore the old assumption about values being prepared by the model object | |
| 1908 | + $model->assume_values_already_prepared_by_model_object( | |
| 1909 | + $old_assumption_concerning_value_preparation | |
| 1910 | + ); | |
| 1911 | + /** | |
| 1912 | + * After saving the model object this action is called | |
| 1913 | + * | |
| 1914 | + * @param EE_Base_Class $model_object which was just saved | |
| 1915 | + * @param boolean|int $results if it were updated, TRUE or FALSE; if it were newly inserted | |
| 1916 | + * the new ID (or 0 if an error occurred and it wasn't updated) | |
| 1917 | + */ | |
| 1918 | +		do_action('AHEE__EE_Base_Class__save__end', $this, $results); | |
| 1919 | + $this->_has_changes = false; | |
| 1920 | + return $results; | |
| 1921 | + } | |
| 1922 | + | |
| 1923 | + | |
| 1924 | + /** | |
| 1925 | + * Updates the foreign key on related models objects pointing to this to have this model object's ID | |
| 1926 | + * as their foreign key. If the cached related model objects already exist in the db, saves them (so that the DB | |
| 1927 | + * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its | |
| 1928 | + * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't | |
| 1929 | + * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the | |
| 1930 | + * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether | |
| 1931 | + * or not they exist in the DB (if they do, their DB records will be automatically updated) | |
| 1932 | + * | |
| 1933 | + * @return void | |
| 1934 | + * @throws ReflectionException | |
| 1935 | + * @throws InvalidArgumentException | |
| 1936 | + * @throws InvalidInterfaceException | |
| 1937 | + * @throws InvalidDataTypeException | |
| 1938 | + * @throws EE_Error | |
| 1939 | + */ | |
| 1940 | + protected function _update_cached_related_model_objs_fks() | |
| 1941 | +	{ | |
| 1942 | + $model = $this->get_model(); | |
| 1943 | +		foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 1944 | +			if ($relation_obj instanceof EE_Has_Many_Relation) { | |
| 1945 | +				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) { | |
| 1946 | + $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to( | |
| 1947 | + $model->get_this_model_name() | |
| 1948 | + ); | |
| 1949 | + $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID()); | |
| 1950 | +					if ($related_model_obj_in_cache->ID()) { | |
| 1951 | + $related_model_obj_in_cache->save(); | |
| 1952 | + } | |
| 1953 | + } | |
| 1954 | + } | |
| 1955 | + } | |
| 1956 | + } | |
| 1957 | + | |
| 1958 | + | |
| 1959 | + /** | |
| 1960 | + * Saves this model object and its NEW cached relations to the database. | |
| 1961 | + * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB. | |
| 1962 | + * In order for that to work, we would need to mark model objects as dirty/clean... | |
| 1963 | + * because otherwise, there's a potential for infinite looping of saving | |
| 1964 | + * Saves the cached related model objects, and ensures the relation between them | |
| 1965 | + * and this object and properly setup | |
| 1966 | + * | |
| 1967 | + * @return int ID of new model object on save; 0 on failure+ | |
| 1968 | + * @throws ReflectionException | |
| 1969 | + * @throws InvalidArgumentException | |
| 1970 | + * @throws InvalidInterfaceException | |
| 1971 | + * @throws InvalidDataTypeException | |
| 1972 | + * @throws EE_Error | |
| 1973 | + */ | |
| 1974 | + public function save_new_cached_related_model_objs() | |
| 1975 | +	{ | |
| 1976 | + // make sure this has been saved | |
| 1977 | +		if (! $this->ID()) { | |
| 1978 | + $id = $this->save(); | |
| 1979 | +		} else { | |
| 1980 | + $id = $this->ID(); | |
| 1981 | + } | |
| 1982 | + // now save all the NEW cached model objects (ie they don't exist in the DB) | |
| 1983 | +		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) { | |
| 1984 | +			if ($this->_model_relations[ $relationName ]) { | |
| 1985 | + // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation) | |
| 1986 | + // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)? | |
| 1987 | + /* @var $related_model_obj EE_Base_Class */ | |
| 1988 | +				if ($relationObj instanceof EE_Belongs_To_Relation) { | |
| 1989 | + // add a relation to that relation type (which saves the appropriate thing in the process) | |
| 1990 | + // but ONLY if it DOES NOT exist in the DB | |
| 1991 | + $related_model_obj = $this->_model_relations[ $relationName ]; | |
| 1992 | +					// if( ! $related_model_obj->ID()){ | |
| 1993 | + $this->_add_relation_to($related_model_obj, $relationName); | |
| 1994 | + $related_model_obj->save_new_cached_related_model_objs(); | |
| 1995 | + // } | |
| 1996 | +				} else { | |
| 1997 | +					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) { | |
| 1998 | + // add a relation to that relation type (which saves the appropriate thing in the process) | |
| 1999 | + // but ONLY if it DOES NOT exist in the DB | |
| 2000 | +						// if( ! $related_model_obj->ID()){ | |
| 2001 | + $this->_add_relation_to($related_model_obj, $relationName); | |
| 2002 | + $related_model_obj->save_new_cached_related_model_objs(); | |
| 2003 | + // } | |
| 2004 | + } | |
| 2005 | + } | |
| 2006 | + } | |
| 2007 | + } | |
| 2008 | + return $id; | |
| 2009 | + } | |
| 2010 | + | |
| 2011 | + | |
| 2012 | + /** | |
| 2013 | + * for getting a model while instantiated. | |
| 2014 | + * | |
| 2015 | + * @return EEM_Base | EEM_CPT_Base | |
| 2016 | + * @throws ReflectionException | |
| 2017 | + * @throws InvalidArgumentException | |
| 2018 | + * @throws InvalidInterfaceException | |
| 2019 | + * @throws InvalidDataTypeException | |
| 2020 | + * @throws EE_Error | |
| 2021 | + */ | |
| 2022 | + public function get_model() | |
| 2023 | +	{ | |
| 2024 | +		if (! $this->_model) { | |
| 2025 | + $modelName = self::_get_model_classname(get_class($this)); | |
| 2026 | + $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone); | |
| 2027 | +		} else { | |
| 2028 | + $this->_model->set_timezone($this->_timezone); | |
| 2029 | + } | |
| 2030 | + return $this->_model; | |
| 2031 | + } | |
| 2032 | + | |
| 2033 | + | |
| 2034 | + /** | |
| 2035 | + * @param $props_n_values | |
| 2036 | + * @param $classname | |
| 2037 | + * @return mixed bool|EE_Base_Class|EEM_CPT_Base | |
| 2038 | + * @throws ReflectionException | |
| 2039 | + * @throws InvalidArgumentException | |
| 2040 | + * @throws InvalidInterfaceException | |
| 2041 | + * @throws InvalidDataTypeException | |
| 2042 | + * @throws EE_Error | |
| 2043 | + */ | |
| 2044 | + protected static function _get_object_from_entity_mapper($props_n_values, $classname) | |
| 2045 | +	{ | |
| 2046 | + // TODO: will not work for Term_Relationships because they have no PK! | |
| 2047 | + $primary_id_ref = self::_get_primary_key_name($classname); | |
| 2048 | + if (array_key_exists($primary_id_ref, $props_n_values) | |
| 2049 | + && ! empty($props_n_values[ $primary_id_ref ]) | |
| 2050 | +		) { | |
| 2051 | + $id = $props_n_values[ $primary_id_ref ]; | |
| 2052 | + return self::_get_model($classname)->get_from_entity_map($id); | |
| 2053 | + } | |
| 2054 | + return false; | |
| 2055 | + } | |
| 2056 | + | |
| 2057 | + | |
| 2058 | + /** | |
| 2059 | + * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for | |
| 2060 | + * the primary key (if present in incoming values). If there is a key in the incoming array that matches the | |
| 2061 | + * primary key for the model AND it is not null, then we check the db. If there's a an object we return it. If not | |
| 2062 | + * we return false. | |
| 2063 | + * | |
| 2064 | + * @param array $props_n_values incoming array of properties and their values | |
| 2065 | + * @param string $classname the classname of the child class | |
| 2066 | + * @param null $timezone | |
| 2067 | + * @param array $date_formats incoming date_formats in an array where the first value is the | |
| 2068 | + * date_format and the second value is the time format | |
| 2069 | + * @return mixed (EE_Base_Class|bool) | |
| 2070 | + * @throws InvalidArgumentException | |
| 2071 | + * @throws InvalidInterfaceException | |
| 2072 | + * @throws InvalidDataTypeException | |
| 2073 | + * @throws EE_Error | |
| 2074 | + * @throws ReflectionException | |
| 2075 | + * @throws ReflectionException | |
| 2076 | + * @throws ReflectionException | |
| 2077 | + */ | |
| 2078 | + protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array()) | |
| 2079 | +	{ | |
| 2080 | + $existing = null; | |
| 2081 | + $model = self::_get_model($classname, $timezone); | |
| 2082 | +		if ($model->has_primary_key_field()) { | |
| 2083 | + $primary_id_ref = self::_get_primary_key_name($classname); | |
| 2084 | + if (array_key_exists($primary_id_ref, $props_n_values) | |
| 2085 | + && ! empty($props_n_values[ $primary_id_ref ]) | |
| 2086 | +			) { | |
| 2087 | + $existing = $model->get_one_by_ID( | |
| 2088 | + $props_n_values[ $primary_id_ref ] | |
| 2089 | + ); | |
| 2090 | + } | |
| 2091 | +		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) { | |
| 2092 | + // no primary key on this model, but there's still a matching item in the DB | |
| 2093 | + $existing = self::_get_model($classname, $timezone)->get_one_by_ID( | |
| 2094 | + self::_get_model($classname, $timezone) | |
| 2095 | + ->get_index_primary_key_string($props_n_values) | |
| 2096 | + ); | |
| 2097 | + } | |
| 2098 | +		if ($existing) { | |
| 2099 | + // set date formats if present before setting values | |
| 2100 | +			if (! empty($date_formats) && is_array($date_formats)) { | |
| 2101 | + $existing->set_date_format($date_formats[0]); | |
| 2102 | + $existing->set_time_format($date_formats[1]); | |
| 2103 | +			} else { | |
| 2104 | + // set default formats for date and time | |
| 2105 | +				$existing->set_date_format(get_option('date_format')); | |
| 2106 | +				$existing->set_time_format(get_option('time_format')); | |
| 2107 | + } | |
| 2108 | +			foreach ($props_n_values as $property => $field_value) { | |
| 2109 | + $existing->set($property, $field_value); | |
| 2110 | + } | |
| 2111 | + return $existing; | |
| 2112 | + } | |
| 2113 | + return false; | |
| 2114 | + } | |
| 2115 | + | |
| 2116 | + | |
| 2117 | + /** | |
| 2118 | + * Gets the EEM_*_Model for this class | |
| 2119 | + * | |
| 2120 | + * @access public now, as this is more convenient | |
| 2121 | + * @param $classname | |
| 2122 | + * @param null $timezone | |
| 2123 | + * @throws ReflectionException | |
| 2124 | + * @throws InvalidArgumentException | |
| 2125 | + * @throws InvalidInterfaceException | |
| 2126 | + * @throws InvalidDataTypeException | |
| 2127 | + * @throws EE_Error | |
| 2128 | + * @return EEM_Base | |
| 2129 | + */ | |
| 2130 | + protected static function _get_model($classname, $timezone = null) | |
| 2131 | +	{ | |
| 2132 | + // find model for this class | |
| 2133 | +		if (! $classname) { | |
| 2134 | + throw new EE_Error( | |
| 2135 | + sprintf( | |
| 2136 | + esc_html__( | |
| 2137 | + 'What were you thinking calling _get_model(%s)?? You need to specify the class name', | |
| 2138 | + 'event_espresso' | |
| 2139 | + ), | |
| 2140 | + $classname | |
| 2141 | + ) | |
| 2142 | + ); | |
| 2143 | + } | |
| 2144 | + $modelName = self::_get_model_classname($classname); | |
| 2145 | + return self::_get_model_instance_with_name($modelName, $timezone); | |
| 2146 | + } | |
| 2147 | + | |
| 2148 | + | |
| 2149 | + /** | |
| 2150 | + * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee) | |
| 2151 | + * | |
| 2152 | + * @param string $model_classname | |
| 2153 | + * @param null $timezone | |
| 2154 | + * @return EEM_Base | |
| 2155 | + * @throws ReflectionException | |
| 2156 | + * @throws InvalidArgumentException | |
| 2157 | + * @throws InvalidInterfaceException | |
| 2158 | + * @throws InvalidDataTypeException | |
| 2159 | + * @throws EE_Error | |
| 2160 | + */ | |
| 2161 | + protected static function _get_model_instance_with_name($model_classname, $timezone = null) | |
| 2162 | +	{ | |
| 2163 | +		$model_classname = str_replace('EEM_', '', $model_classname); | |
| 2164 | + $model = EE_Registry::instance()->load_model($model_classname); | |
| 2165 | + $model->set_timezone($timezone); | |
| 2166 | + return $model; | |
| 2167 | + } | |
| 2168 | + | |
| 2169 | + | |
| 2170 | + /** | |
| 2171 | + * If a model name is provided (eg Registration), gets the model classname for that model. | |
| 2172 | + * Also works if a model class's classname is provided (eg EE_Registration). | |
| 2173 | + * | |
| 2174 | + * @param null $model_name | |
| 2175 | + * @return string like EEM_Attendee | |
| 2176 | + */ | |
| 2177 | + private static function _get_model_classname($model_name = null) | |
| 2178 | +	{ | |
| 2179 | +		if (strpos($model_name, 'EE_') === 0) { | |
| 2180 | +			$model_classname = str_replace('EE_', 'EEM_', $model_name); | |
| 2181 | +		} else { | |
| 2182 | + $model_classname = 'EEM_' . $model_name; | |
| 2183 | + } | |
| 2184 | + return $model_classname; | |
| 2185 | + } | |
| 2186 | + | |
| 2187 | + | |
| 2188 | + /** | |
| 2189 | + * returns the name of the primary key attribute | |
| 2190 | + * | |
| 2191 | + * @param null $classname | |
| 2192 | + * @throws ReflectionException | |
| 2193 | + * @throws InvalidArgumentException | |
| 2194 | + * @throws InvalidInterfaceException | |
| 2195 | + * @throws InvalidDataTypeException | |
| 2196 | + * @throws EE_Error | |
| 2197 | + * @return string | |
| 2198 | + */ | |
| 2199 | + protected static function _get_primary_key_name($classname = null) | |
| 2200 | +	{ | |
| 2201 | +		if (! $classname) { | |
| 2202 | + throw new EE_Error( | |
| 2203 | + sprintf( | |
| 2204 | +					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'), | |
| 2205 | + $classname | |
| 2206 | + ) | |
| 2207 | + ); | |
| 2208 | + } | |
| 2209 | + return self::_get_model($classname)->get_primary_key_field()->get_name(); | |
| 2210 | + } | |
| 2211 | + | |
| 2212 | + | |
| 2213 | + /** | |
| 2214 | + * Gets the value of the primary key. | |
| 2215 | + * If the object hasn't yet been saved, it should be whatever the model field's default was | |
| 2216 | + * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value | |
| 2217 | + * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL). | |
| 2218 | + * | |
| 2219 | + * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string | |
| 2220 | + * @throws ReflectionException | |
| 2221 | + * @throws InvalidArgumentException | |
| 2222 | + * @throws InvalidInterfaceException | |
| 2223 | + * @throws InvalidDataTypeException | |
| 2224 | + * @throws EE_Error | |
| 2225 | + */ | |
| 2226 | + public function ID() | |
| 2227 | +	{ | |
| 2228 | + $model = $this->get_model(); | |
| 2229 | + // now that we know the name of the variable, use a variable variable to get its value and return its | |
| 2230 | +		if ($model->has_primary_key_field()) { | |
| 2231 | + return $this->_fields[ $model->primary_key_name() ]; | |
| 2232 | + } | |
| 2233 | + return $model->get_index_primary_key_string($this->_fields); | |
| 2234 | + } | |
| 2235 | + | |
| 2236 | + | |
| 2237 | + /** | |
| 2238 | + * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current | |
| 2239 | + * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE | |
| 2240 | + * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing | |
| 2241 | + * | |
| 2242 | + * @param mixed $otherObjectModelObjectOrID EE_Base_Class or the ID of the other object | |
| 2243 | + * @param string $relationName eg 'Events','Question',etc. | |
| 2244 | + * an attendee to a group, you also want to specify which role they | |
| 2245 | + * will have in that group. So you would use this parameter to | |
| 2246 | +	 *                                                 specify array('role-column-name'=>'role-id') | |
| 2247 | + * @param array $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that | |
| 2248 | + * allow you to further constrict the relation to being added. | |
| 2249 | + * However, keep in mind that the columns (keys) given must match a | |
| 2250 | + * column on the JOIN table and currently only the HABTM models | |
| 2251 | + * accept these additional conditions. Also remember that if an | |
| 2252 | + * exact match isn't found for these extra cols/val pairs, then a | |
| 2253 | + * NEW row is created in the join table. | |
| 2254 | + * @param null $cache_id | |
| 2255 | + * @throws ReflectionException | |
| 2256 | + * @throws InvalidArgumentException | |
| 2257 | + * @throws InvalidInterfaceException | |
| 2258 | + * @throws InvalidDataTypeException | |
| 2259 | + * @throws EE_Error | |
| 2260 | + * @return EE_Base_Class the object the relation was added to | |
| 2261 | + */ | |
| 2262 | + public function _add_relation_to( | |
| 2263 | + $otherObjectModelObjectOrID, | |
| 2264 | + $relationName, | |
| 2265 | + $extra_join_model_fields_n_values = array(), | |
| 2266 | + $cache_id = null | |
| 2267 | +	) { | |
| 2268 | + $model = $this->get_model(); | |
| 2269 | + // if this thing exists in the DB, save the relation to the DB | |
| 2270 | +		if ($this->ID()) { | |
| 2271 | + $otherObject = $model->add_relationship_to( | |
| 2272 | + $this, | |
| 2273 | + $otherObjectModelObjectOrID, | |
| 2274 | + $relationName, | |
| 2275 | + $extra_join_model_fields_n_values | |
| 2276 | + ); | |
| 2277 | + // clear cache so future get_many_related and get_first_related() return new results. | |
| 2278 | + $this->clear_cache($relationName, $otherObject, true); | |
| 2279 | +			if ($otherObject instanceof EE_Base_Class) { | |
| 2280 | + $otherObject->clear_cache($model->get_this_model_name(), $this); | |
| 2281 | + } | |
| 2282 | +		} else { | |
| 2283 | + // this thing doesn't exist in the DB, so just cache it | |
| 2284 | +			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) { | |
| 2285 | + throw new EE_Error( | |
| 2286 | + sprintf( | |
| 2287 | + esc_html__( | |
| 2288 | + 'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s', | |
| 2289 | + 'event_espresso' | |
| 2290 | + ), | |
| 2291 | + $otherObjectModelObjectOrID, | |
| 2292 | + get_class($this) | |
| 2293 | + ) | |
| 2294 | + ); | |
| 2295 | + } | |
| 2296 | + $otherObject = $otherObjectModelObjectOrID; | |
| 2297 | + $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id); | |
| 2298 | + } | |
| 2299 | +		if ($otherObject instanceof EE_Base_Class) { | |
| 2300 | + // fix the reciprocal relation too | |
| 2301 | +			if ($otherObject->ID()) { | |
| 2302 | + // its saved so assumed relations exist in the DB, so we can just | |
| 2303 | + // clear the cache so future queries use the updated info in the DB | |
| 2304 | + $otherObject->clear_cache( | |
| 2305 | + $model->get_this_model_name(), | |
| 2306 | + null, | |
| 2307 | + true | |
| 2308 | + ); | |
| 2309 | +			} else { | |
| 2310 | + // it's not saved, so it caches relations like this | |
| 2311 | + $otherObject->cache($model->get_this_model_name(), $this); | |
| 2312 | + } | |
| 2313 | + } | |
| 2314 | + return $otherObject; | |
| 2315 | + } | |
| 2316 | + | |
| 2317 | + | |
| 2318 | + /** | |
| 2319 | + * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current | |
| 2320 | + * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE | |
| 2321 | + * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing | |
| 2322 | + * from the cache | |
| 2323 | + * | |
| 2324 | + * @param mixed $otherObjectModelObjectOrID | |
| 2325 | + * EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved | |
| 2326 | + * to the DB yet | |
| 2327 | + * @param string $relationName | |
| 2328 | + * @param array $where_query | |
| 2329 | + * You can optionally include an array of key=>value pairs that allow you to further constrict the | |
| 2330 | + * relation to being added. However, keep in mind that the columns (keys) given must match a column | |
| 2331 | + * on the JOIN table and currently only the HABTM models accept these additional conditions. Also | |
| 2332 | + * remember that if an exact match isn't found for these extra cols/val pairs, then no row is | |
| 2333 | + * deleted. | |
| 2334 | + * @return EE_Base_Class the relation was removed from | |
| 2335 | + * @throws ReflectionException | |
| 2336 | + * @throws InvalidArgumentException | |
| 2337 | + * @throws InvalidInterfaceException | |
| 2338 | + * @throws InvalidDataTypeException | |
| 2339 | + * @throws EE_Error | |
| 2340 | + */ | |
| 2341 | + public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array()) | |
| 2342 | +	{ | |
| 2343 | +		if ($this->ID()) { | |
| 2344 | + // if this exists in the DB, save the relation change to the DB too | |
| 2345 | + $otherObject = $this->get_model()->remove_relationship_to( | |
| 2346 | + $this, | |
| 2347 | + $otherObjectModelObjectOrID, | |
| 2348 | + $relationName, | |
| 2349 | + $where_query | |
| 2350 | + ); | |
| 2351 | + $this->clear_cache( | |
| 2352 | + $relationName, | |
| 2353 | + $otherObject | |
| 2354 | + ); | |
| 2355 | +		} else { | |
| 2356 | + // this doesn't exist in the DB, just remove it from the cache | |
| 2357 | + $otherObject = $this->clear_cache( | |
| 2358 | + $relationName, | |
| 2359 | + $otherObjectModelObjectOrID | |
| 2360 | + ); | |
| 2361 | + } | |
| 2362 | +		if ($otherObject instanceof EE_Base_Class) { | |
| 2363 | + $otherObject->clear_cache( | |
| 2364 | + $this->get_model()->get_this_model_name(), | |
| 2365 | + $this | |
| 2366 | + ); | |
| 2367 | + } | |
| 2368 | + return $otherObject; | |
| 2369 | + } | |
| 2370 | + | |
| 2371 | + | |
| 2372 | + /** | |
| 2373 | + * Removes ALL the related things for the $relationName. | |
| 2374 | + * | |
| 2375 | + * @param string $relationName | |
| 2376 | + * @param array $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions | |
| 2377 | + * @return EE_Base_Class | |
| 2378 | + * @throws ReflectionException | |
| 2379 | + * @throws InvalidArgumentException | |
| 2380 | + * @throws InvalidInterfaceException | |
| 2381 | + * @throws InvalidDataTypeException | |
| 2382 | + * @throws EE_Error | |
| 2383 | + */ | |
| 2384 | + public function _remove_relations($relationName, $where_query_params = array()) | |
| 2385 | +	{ | |
| 2386 | +		if ($this->ID()) { | |
| 2387 | + // if this exists in the DB, save the relation change to the DB too | |
| 2388 | + $otherObjects = $this->get_model()->remove_relations( | |
| 2389 | + $this, | |
| 2390 | + $relationName, | |
| 2391 | + $where_query_params | |
| 2392 | + ); | |
| 2393 | + $this->clear_cache( | |
| 2394 | + $relationName, | |
| 2395 | + null, | |
| 2396 | + true | |
| 2397 | + ); | |
| 2398 | +		} else { | |
| 2399 | + // this doesn't exist in the DB, just remove it from the cache | |
| 2400 | + $otherObjects = $this->clear_cache( | |
| 2401 | + $relationName, | |
| 2402 | + null, | |
| 2403 | + true | |
| 2404 | + ); | |
| 2405 | + } | |
| 2406 | +		if (is_array($otherObjects)) { | |
| 2407 | +			foreach ($otherObjects as $otherObject) { | |
| 2408 | + $otherObject->clear_cache( | |
| 2409 | + $this->get_model()->get_this_model_name(), | |
| 2410 | + $this | |
| 2411 | + ); | |
| 2412 | + } | |
| 2413 | + } | |
| 2414 | + return $otherObjects; | |
| 2415 | + } | |
| 2416 | + | |
| 2417 | + | |
| 2418 | + /** | |
| 2419 | + * Gets all the related model objects of the specified type. Eg, if the current class if | |
| 2420 | +	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the | |
| 2421 | + * EE_Registration objects which related to this event. Note: by default, we remove the "default query params" | |
| 2422 | + * because we want to get even deleted items etc. | |
| 2423 | + * | |
| 2424 | + * @param string $relationName key in the model's _model_relations array | |
| 2425 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions | |
| 2426 | + * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary | |
| 2427 | + * keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these | |
| 2428 | + * results if you want IDs | |
| 2429 | + * @throws ReflectionException | |
| 2430 | + * @throws InvalidArgumentException | |
| 2431 | + * @throws InvalidInterfaceException | |
| 2432 | + * @throws InvalidDataTypeException | |
| 2433 | + * @throws EE_Error | |
| 2434 | + */ | |
| 2435 | + public function get_many_related($relationName, $query_params = array()) | |
| 2436 | +	{ | |
| 2437 | +		if ($this->ID()) { | |
| 2438 | + // this exists in the DB, so get the related things from either the cache or the DB | |
| 2439 | + // if there are query parameters, forget about caching the related model objects. | |
| 2440 | +			if ($query_params) { | |
| 2441 | + $related_model_objects = $this->get_model()->get_all_related( | |
| 2442 | + $this, | |
| 2443 | + $relationName, | |
| 2444 | + $query_params | |
| 2445 | + ); | |
| 2446 | +			} else { | |
| 2447 | + // did we already cache the result of this query? | |
| 2448 | + $cached_results = $this->get_all_from_cache($relationName); | |
| 2449 | +				if (! $cached_results) { | |
| 2450 | + $related_model_objects = $this->get_model()->get_all_related( | |
| 2451 | + $this, | |
| 2452 | + $relationName, | |
| 2453 | + $query_params | |
| 2454 | + ); | |
| 2455 | + // if no query parameters were passed, then we got all the related model objects | |
| 2456 | + // for that relation. We can cache them then. | |
| 2457 | +					foreach ($related_model_objects as $related_model_object) { | |
| 2458 | + $this->cache($relationName, $related_model_object); | |
| 2459 | + } | |
| 2460 | +				} else { | |
| 2461 | + $related_model_objects = $cached_results; | |
| 2462 | + } | |
| 2463 | + } | |
| 2464 | +		} else { | |
| 2465 | + // this doesn't exist in the DB, so just get the related things from the cache | |
| 2466 | + $related_model_objects = $this->get_all_from_cache($relationName); | |
| 2467 | + } | |
| 2468 | + return $related_model_objects; | |
| 2469 | + } | |
| 2470 | + | |
| 2471 | + | |
| 2472 | + /** | |
| 2473 | + * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default, | |
| 2474 | + * unless otherwise specified in the $query_params | |
| 2475 | + * | |
| 2476 | + * @param string $relation_name model_name like 'Event', or 'Registration' | |
| 2477 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2478 | + * @param string $field_to_count name of field to count by. By default, uses primary key | |
| 2479 | + * @param bool $distinct if we want to only count the distinct values for the column then you can trigger | |
| 2480 | + * that by the setting $distinct to TRUE; | |
| 2481 | + * @return int | |
| 2482 | + * @throws ReflectionException | |
| 2483 | + * @throws InvalidArgumentException | |
| 2484 | + * @throws InvalidInterfaceException | |
| 2485 | + * @throws InvalidDataTypeException | |
| 2486 | + * @throws EE_Error | |
| 2487 | + */ | |
| 2488 | + public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false) | |
| 2489 | +	{ | |
| 2490 | + return $this->get_model()->count_related( | |
| 2491 | + $this, | |
| 2492 | + $relation_name, | |
| 2493 | + $query_params, | |
| 2494 | + $field_to_count, | |
| 2495 | + $distinct | |
| 2496 | + ); | |
| 2497 | + } | |
| 2498 | + | |
| 2499 | + | |
| 2500 | + /** | |
| 2501 | + * Instead of getting the related model objects, simply sums up the values of the specified field. | |
| 2502 | + * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params | |
| 2503 | + * | |
| 2504 | + * @param string $relation_name model_name like 'Event', or 'Registration' | |
| 2505 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2506 | + * @param string $field_to_sum name of field to count by. | |
| 2507 | + * By default, uses primary key | |
| 2508 | + * (which doesn't make much sense, so you should probably change it) | |
| 2509 | + * @return int | |
| 2510 | + * @throws ReflectionException | |
| 2511 | + * @throws InvalidArgumentException | |
| 2512 | + * @throws InvalidInterfaceException | |
| 2513 | + * @throws InvalidDataTypeException | |
| 2514 | + * @throws EE_Error | |
| 2515 | + */ | |
| 2516 | + public function sum_related($relation_name, $query_params = array(), $field_to_sum = null) | |
| 2517 | +	{ | |
| 2518 | + return $this->get_model()->sum_related( | |
| 2519 | + $this, | |
| 2520 | + $relation_name, | |
| 2521 | + $query_params, | |
| 2522 | + $field_to_sum | |
| 2523 | + ); | |
| 2524 | + } | |
| 2525 | + | |
| 2526 | + | |
| 2527 | + /** | |
| 2528 | + * Gets the first (ie, one) related model object of the specified type. | |
| 2529 | + * | |
| 2530 | + * @param string $relationName key in the model's _model_relations array | |
| 2531 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2532 | + * @return EE_Base_Class (not an array, a single object) | |
| 2533 | + * @throws ReflectionException | |
| 2534 | + * @throws InvalidArgumentException | |
| 2535 | + * @throws InvalidInterfaceException | |
| 2536 | + * @throws InvalidDataTypeException | |
| 2537 | + * @throws EE_Error | |
| 2538 | + */ | |
| 2539 | + public function get_first_related($relationName, $query_params = array()) | |
| 2540 | +	{ | |
| 2541 | + $model = $this->get_model(); | |
| 2542 | +		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB | |
| 2543 | + // if they've provided some query parameters, don't bother trying to cache the result | |
| 2544 | + // also make sure we're not caching the result of get_first_related | |
| 2545 | + // on a relation which should have an array of objects (because the cache might have an array of objects) | |
| 2546 | + if ($query_params | |
| 2547 | + || ! $model->related_settings_for($relationName) | |
| 2548 | + instanceof | |
| 2549 | + EE_Belongs_To_Relation | |
| 2550 | +			) { | |
| 2551 | + $related_model_object = $model->get_first_related( | |
| 2552 | + $this, | |
| 2553 | + $relationName, | |
| 2554 | + $query_params | |
| 2555 | + ); | |
| 2556 | +			} else { | |
| 2557 | + // first, check if we've already cached the result of this query | |
| 2558 | + $cached_result = $this->get_one_from_cache($relationName); | |
| 2559 | +				if (! $cached_result) { | |
| 2560 | + $related_model_object = $model->get_first_related( | |
| 2561 | + $this, | |
| 2562 | + $relationName, | |
| 2563 | + $query_params | |
| 2564 | + ); | |
| 2565 | + $this->cache($relationName, $related_model_object); | |
| 2566 | +				} else { | |
| 2567 | + $related_model_object = $cached_result; | |
| 2568 | + } | |
| 2569 | + } | |
| 2570 | +		} else { | |
| 2571 | + $related_model_object = null; | |
| 2572 | + // this doesn't exist in the Db, | |
| 2573 | + // but maybe the relation is of type belongs to, and so the related thing might | |
| 2574 | +			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) { | |
| 2575 | + $related_model_object = $model->get_first_related( | |
| 2576 | + $this, | |
| 2577 | + $relationName, | |
| 2578 | + $query_params | |
| 2579 | + ); | |
| 2580 | + } | |
| 2581 | + // this doesn't exist in the DB and apparently the thing it belongs to doesn't either, | |
| 2582 | + // just get what's cached on this object | |
| 2583 | +			if (! $related_model_object) { | |
| 2584 | + $related_model_object = $this->get_one_from_cache($relationName); | |
| 2585 | + } | |
| 2586 | + } | |
| 2587 | + return $related_model_object; | |
| 2588 | + } | |
| 2589 | + | |
| 2590 | + | |
| 2591 | + /** | |
| 2592 | + * Does a delete on all related objects of type $relationName and removes | |
| 2593 | + * the current model object's relation to them. If they can't be deleted (because | |
| 2594 | + * of blocking related model objects) does nothing. If the related model objects are | |
| 2595 | + * soft-deletable, they will be soft-deleted regardless of related blocking model objects. | |
| 2596 | + * If this model object doesn't exist yet in the DB, just removes its related things | |
| 2597 | + * | |
| 2598 | + * @param string $relationName | |
| 2599 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2600 | + * @return int how many deleted | |
| 2601 | + * @throws ReflectionException | |
| 2602 | + * @throws InvalidArgumentException | |
| 2603 | + * @throws InvalidInterfaceException | |
| 2604 | + * @throws InvalidDataTypeException | |
| 2605 | + * @throws EE_Error | |
| 2606 | + */ | |
| 2607 | + public function delete_related($relationName, $query_params = array()) | |
| 2608 | +	{ | |
| 2609 | +		if ($this->ID()) { | |
| 2610 | + $count = $this->get_model()->delete_related( | |
| 2611 | + $this, | |
| 2612 | + $relationName, | |
| 2613 | + $query_params | |
| 2614 | + ); | |
| 2615 | +		} else { | |
| 2616 | + $count = count($this->get_all_from_cache($relationName)); | |
| 2617 | + $this->clear_cache($relationName, null, true); | |
| 2618 | + } | |
| 2619 | + return $count; | |
| 2620 | + } | |
| 2621 | + | |
| 2622 | + | |
| 2623 | + /** | |
| 2624 | + * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes | |
| 2625 | + * the current model object's relation to them. If they can't be deleted (because | |
| 2626 | + * of blocking related model objects) just does a soft delete on it instead, if possible. | |
| 2627 | + * If the related thing isn't a soft-deletable model object, this function is identical | |
| 2628 | + * to delete_related(). If this model object doesn't exist in the DB, just remove its related things | |
| 2629 | + * | |
| 2630 | + * @param string $relationName | |
| 2631 | + * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md | |
| 2632 | + * @return int how many deleted (including those soft deleted) | |
| 2633 | + * @throws ReflectionException | |
| 2634 | + * @throws InvalidArgumentException | |
| 2635 | + * @throws InvalidInterfaceException | |
| 2636 | + * @throws InvalidDataTypeException | |
| 2637 | + * @throws EE_Error | |
| 2638 | + */ | |
| 2639 | + public function delete_related_permanently($relationName, $query_params = array()) | |
| 2640 | +	{ | |
| 2641 | +		if ($this->ID()) { | |
| 2642 | + $count = $this->get_model()->delete_related_permanently( | |
| 2643 | + $this, | |
| 2644 | + $relationName, | |
| 2645 | + $query_params | |
| 2646 | + ); | |
| 2647 | +		} else { | |
| 2648 | + $count = count($this->get_all_from_cache($relationName)); | |
| 2649 | + } | |
| 2650 | + $this->clear_cache($relationName, null, true); | |
| 2651 | + return $count; | |
| 2652 | + } | |
| 2653 | + | |
| 2654 | + | |
| 2655 | + /** | |
| 2656 | + * is_set | |
| 2657 | + * Just a simple utility function children can use for checking if property exists | |
| 2658 | + * | |
| 2659 | + * @access public | |
| 2660 | + * @param string $field_name property to check | |
| 2661 | + * @return bool TRUE if existing,FALSE if not. | |
| 2662 | + */ | |
| 2663 | + public function is_set($field_name) | |
| 2664 | +	{ | |
| 2665 | + return isset($this->_fields[ $field_name ]); | |
| 2666 | + } | |
| 2667 | + | |
| 2668 | + | |
| 2669 | + /** | |
| 2670 | + * Just a simple utility function children can use for checking if property (or properties) exists and throwing an | |
| 2671 | + * EE_Error exception if they don't | |
| 2672 | + * | |
| 2673 | + * @param mixed (string|array) $properties properties to check | |
| 2674 | + * @throws EE_Error | |
| 2675 | + * @return bool TRUE if existing, throw EE_Error if not. | |
| 2676 | + */ | |
| 2677 | + protected function _property_exists($properties) | |
| 2678 | +	{ | |
| 2679 | +		foreach ((array) $properties as $property_name) { | |
| 2680 | + // first make sure this property exists | |
| 2681 | +			if (! $this->_fields[ $property_name ]) { | |
| 2682 | + throw new EE_Error( | |
| 2683 | + sprintf( | |
| 2684 | + esc_html__( | |
| 2685 | + 'Trying to retrieve a non-existent property (%s). Double check the spelling please', | |
| 2686 | + 'event_espresso' | |
| 2687 | + ), | |
| 2688 | + $property_name | |
| 2689 | + ) | |
| 2690 | + ); | |
| 2691 | + } | |
| 2692 | + } | |
| 2693 | + return true; | |
| 2694 | + } | |
| 2695 | + | |
| 2696 | + | |
| 2697 | + /** | |
| 2698 | + * This simply returns an array of model fields for this object | |
| 2699 | + * | |
| 2700 | + * @return array | |
| 2701 | + * @throws ReflectionException | |
| 2702 | + * @throws InvalidArgumentException | |
| 2703 | + * @throws InvalidInterfaceException | |
| 2704 | + * @throws InvalidDataTypeException | |
| 2705 | + * @throws EE_Error | |
| 2706 | + */ | |
| 2707 | + public function model_field_array() | |
| 2708 | +	{ | |
| 2709 | + $fields = $this->get_model()->field_settings(false); | |
| 2710 | + $properties = array(); | |
| 2711 | + // remove prepended underscore | |
| 2712 | +		foreach ($fields as $field_name => $settings) { | |
| 2713 | + $properties[ $field_name ] = $this->get($field_name); | |
| 2714 | + } | |
| 2715 | + return $properties; | |
| 2716 | + } | |
| 2717 | + | |
| 2718 | + | |
| 2719 | + /** | |
| 2720 | + * Very handy general function to allow for plugins to extend any child of EE_Base_Class. | |
| 2721 | + * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called | |
| 2722 | + * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. | |
| 2723 | + * Instead of requiring a plugin to extend the EE_Base_Class | |
| 2724 | + * (which works fine is there's only 1 plugin, but when will that happen?) | |
| 2725 | +	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' | |
| 2726 | + * (eg, filters_hook_espresso__EE_Answer__my_great_function) | |
| 2727 | + * and accepts 2 arguments: the object on which the function was called, | |
| 2728 | + * and an array of the original arguments passed to the function. | |
| 2729 | + * Whatever their callback function returns will be returned by this function. | |
| 2730 | + * Example: in functions.php (or in a plugin): | |
| 2731 | +	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); | |
| 2732 | +	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){ | |
| 2733 | +	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray); | |
| 2734 | + * return $previousReturnValue.$returnString; | |
| 2735 | + * } | |
| 2736 | +	 * require('EE_Answer.class.php'); | |
| 2737 | +	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42')); | |
| 2738 | +	 * echo $answer->my_callback('monkeys',100); | |
| 2739 | + * //will output "you called my_callback! and passed args:monkeys,100" | |
| 2740 | + * | |
| 2741 | + * @param string $methodName name of method which was called on a child of EE_Base_Class, but which | |
| 2742 | + * @param array $args array of original arguments passed to the function | |
| 2743 | + * @throws EE_Error | |
| 2744 | + * @return mixed whatever the plugin which calls add_filter decides | |
| 2745 | + */ | |
| 2746 | + public function __call($methodName, $args) | |
| 2747 | +	{ | |
| 2748 | + $className = get_class($this); | |
| 2749 | +		$tagName = "FHEE__{$className}__{$methodName}"; | |
| 2750 | +		if (! has_filter($tagName)) { | |
| 2751 | + throw new EE_Error( | |
| 2752 | + sprintf( | |
| 2753 | + esc_html__( | |
| 2754 | +						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}", | |
| 2755 | + 'event_espresso' | |
| 2756 | + ), | |
| 2757 | + $methodName, | |
| 2758 | + $className, | |
| 2759 | + $tagName | |
| 2760 | + ) | |
| 2761 | + ); | |
| 2762 | + } | |
| 2763 | + return apply_filters($tagName, null, $this, $args); | |
| 2764 | + } | |
| 2765 | + | |
| 2766 | + | |
| 2767 | + /** | |
| 2768 | + * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value. | |
| 2769 | + * A $previous_value can be specified in case there are many meta rows with the same key | |
| 2770 | + * | |
| 2771 | + * @param string $meta_key | |
| 2772 | + * @param mixed $meta_value | |
| 2773 | + * @param mixed $previous_value | |
| 2774 | + * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row) | |
| 2775 | + * NOTE: if the values haven't changed, returns 0 | |
| 2776 | + * @throws InvalidArgumentException | |
| 2777 | + * @throws InvalidInterfaceException | |
| 2778 | + * @throws InvalidDataTypeException | |
| 2779 | + * @throws EE_Error | |
| 2780 | + * @throws ReflectionException | |
| 2781 | + */ | |
| 2782 | + public function update_extra_meta($meta_key, $meta_value, $previous_value = null) | |
| 2783 | +	{ | |
| 2784 | + $query_params = array( | |
| 2785 | + array( | |
| 2786 | + 'EXM_key' => $meta_key, | |
| 2787 | + 'OBJ_ID' => $this->ID(), | |
| 2788 | + 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2789 | + ), | |
| 2790 | + ); | |
| 2791 | +		if ($previous_value !== null) { | |
| 2792 | + $query_params[0]['EXM_value'] = $meta_value; | |
| 2793 | + } | |
| 2794 | + $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params); | |
| 2795 | +		if (! $existing_rows_like_that) { | |
| 2796 | + return $this->add_extra_meta($meta_key, $meta_value); | |
| 2797 | + } | |
| 2798 | +		foreach ($existing_rows_like_that as $existing_row) { | |
| 2799 | +			$existing_row->save(array('EXM_value' => $meta_value)); | |
| 2800 | + } | |
| 2801 | + return count($existing_rows_like_that); | |
| 2802 | + } | |
| 2803 | + | |
| 2804 | + | |
| 2805 | + /** | |
| 2806 | + * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check | |
| 2807 | + * no other extra meta for this model object have the same key. Returns TRUE if the | |
| 2808 | + * extra meta row was entered, false if not | |
| 2809 | + * | |
| 2810 | + * @param string $meta_key | |
| 2811 | + * @param mixed $meta_value | |
| 2812 | + * @param boolean $unique | |
| 2813 | + * @return boolean | |
| 2814 | + * @throws InvalidArgumentException | |
| 2815 | + * @throws InvalidInterfaceException | |
| 2816 | + * @throws InvalidDataTypeException | |
| 2817 | + * @throws EE_Error | |
| 2818 | + * @throws ReflectionException | |
| 2819 | + * @throws ReflectionException | |
| 2820 | + */ | |
| 2821 | + public function add_extra_meta($meta_key, $meta_value, $unique = false) | |
| 2822 | +	{ | |
| 2823 | +		if ($unique) { | |
| 2824 | + $existing_extra_meta = EEM_Extra_Meta::instance()->get_one( | |
| 2825 | + array( | |
| 2826 | + array( | |
| 2827 | + 'EXM_key' => $meta_key, | |
| 2828 | + 'OBJ_ID' => $this->ID(), | |
| 2829 | + 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2830 | + ), | |
| 2831 | + ) | |
| 2832 | + ); | |
| 2833 | +			if ($existing_extra_meta) { | |
| 2834 | + return false; | |
| 2835 | + } | |
| 2836 | + } | |
| 2837 | + $new_extra_meta = EE_Extra_Meta::new_instance( | |
| 2838 | + array( | |
| 2839 | + 'EXM_key' => $meta_key, | |
| 2840 | + 'EXM_value' => $meta_value, | |
| 2841 | + 'OBJ_ID' => $this->ID(), | |
| 2842 | + 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2843 | + ) | |
| 2844 | + ); | |
| 2845 | + $new_extra_meta->save(); | |
| 2846 | + return true; | |
| 2847 | + } | |
| 2848 | + | |
| 2849 | + | |
| 2850 | + /** | |
| 2851 | + * Deletes all the extra meta rows for this record as specified by key. If $meta_value | |
| 2852 | + * is specified, only deletes extra meta records with that value. | |
| 2853 | + * | |
| 2854 | + * @param string $meta_key | |
| 2855 | + * @param mixed $meta_value | |
| 2856 | + * @return int number of extra meta rows deleted | |
| 2857 | + * @throws InvalidArgumentException | |
| 2858 | + * @throws InvalidInterfaceException | |
| 2859 | + * @throws InvalidDataTypeException | |
| 2860 | + * @throws EE_Error | |
| 2861 | + * @throws ReflectionException | |
| 2862 | + */ | |
| 2863 | + public function delete_extra_meta($meta_key, $meta_value = null) | |
| 2864 | +	{ | |
| 2865 | + $query_params = array( | |
| 2866 | + array( | |
| 2867 | + 'EXM_key' => $meta_key, | |
| 2868 | + 'OBJ_ID' => $this->ID(), | |
| 2869 | + 'EXM_type' => $this->get_model()->get_this_model_name(), | |
| 2870 | + ), | |
| 2871 | + ); | |
| 2872 | +		if ($meta_value !== null) { | |
| 2873 | + $query_params[0]['EXM_value'] = $meta_value; | |
| 2874 | + } | |
| 2875 | + return EEM_Extra_Meta::instance()->delete($query_params); | |
| 2876 | + } | |
| 2877 | + | |
| 2878 | + | |
| 2879 | + /** | |
| 2880 | + * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise | |
| 2881 | + * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation. | |
| 2882 | + * You can specify $default is case you haven't found the extra meta | |
| 2883 | + * | |
| 2884 | + * @param string $meta_key | |
| 2885 | + * @param boolean $single | |
| 2886 | + * @param mixed $default if we don't find anything, what should we return? | |
| 2887 | + * @return mixed single value if $single; array if ! $single | |
| 2888 | + * @throws ReflectionException | |
| 2889 | + * @throws InvalidArgumentException | |
| 2890 | + * @throws InvalidInterfaceException | |
| 2891 | + * @throws InvalidDataTypeException | |
| 2892 | + * @throws EE_Error | |
| 2893 | + */ | |
| 2894 | + public function get_extra_meta($meta_key, $single = false, $default = null) | |
| 2895 | +	{ | |
| 2896 | +		if ($single) { | |
| 2897 | + $result = $this->get_first_related( | |
| 2898 | + 'Extra_Meta', | |
| 2899 | +				array(array('EXM_key' => $meta_key)) | |
| 2900 | + ); | |
| 2901 | +			if ($result instanceof EE_Extra_Meta) { | |
| 2902 | + return $result->value(); | |
| 2903 | + } | |
| 2904 | +		} else { | |
| 2905 | + $results = $this->get_many_related( | |
| 2906 | + 'Extra_Meta', | |
| 2907 | +				array(array('EXM_key' => $meta_key)) | |
| 2908 | + ); | |
| 2909 | +			if ($results) { | |
| 2910 | + $values = array(); | |
| 2911 | +				foreach ($results as $result) { | |
| 2912 | +					if ($result instanceof EE_Extra_Meta) { | |
| 2913 | + $values[ $result->ID() ] = $result->value(); | |
| 2914 | + } | |
| 2915 | + } | |
| 2916 | + return $values; | |
| 2917 | + } | |
| 2918 | + } | |
| 2919 | + // if nothing discovered yet return default. | |
| 2920 | + return apply_filters( | |
| 2921 | + 'FHEE__EE_Base_Class__get_extra_meta__default_value', | |
| 2922 | + $default, | |
| 2923 | + $meta_key, | |
| 2924 | + $single, | |
| 2925 | + $this | |
| 2926 | + ); | |
| 2927 | + } | |
| 2928 | + | |
| 2929 | + | |
| 2930 | + /** | |
| 2931 | + * Returns a simple array of all the extra meta associated with this model object. | |
| 2932 | + * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the | |
| 2933 | + * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with | |
| 2934 | +	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123)) | |
| 2935 | + * If $one_of_each_key is false, it will return an array with the top-level keys being | |
| 2936 | + * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and | |
| 2937 | + * finally the extra meta's value as each sub-value. (eg | |
| 2938 | +	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123))) | |
| 2939 | + * | |
| 2940 | + * @param boolean $one_of_each_key | |
| 2941 | + * @return array | |
| 2942 | + * @throws ReflectionException | |
| 2943 | + * @throws InvalidArgumentException | |
| 2944 | + * @throws InvalidInterfaceException | |
| 2945 | + * @throws InvalidDataTypeException | |
| 2946 | + * @throws EE_Error | |
| 2947 | + */ | |
| 2948 | + public function all_extra_meta_array($one_of_each_key = true) | |
| 2949 | +	{ | |
| 2950 | + $return_array = array(); | |
| 2951 | +		if ($one_of_each_key) { | |
| 2952 | + $extra_meta_objs = $this->get_many_related( | |
| 2953 | + 'Extra_Meta', | |
| 2954 | +				array('group_by' => 'EXM_key') | |
| 2955 | + ); | |
| 2956 | +			foreach ($extra_meta_objs as $extra_meta_obj) { | |
| 2957 | +				if ($extra_meta_obj instanceof EE_Extra_Meta) { | |
| 2958 | + $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value(); | |
| 2959 | + } | |
| 2960 | + } | |
| 2961 | +		} else { | |
| 2962 | +			$extra_meta_objs = $this->get_many_related('Extra_Meta'); | |
| 2963 | +			foreach ($extra_meta_objs as $extra_meta_obj) { | |
| 2964 | +				if ($extra_meta_obj instanceof EE_Extra_Meta) { | |
| 2965 | +					if (! isset($return_array[ $extra_meta_obj->key() ])) { | |
| 2966 | + $return_array[ $extra_meta_obj->key() ] = array(); | |
| 2967 | + } | |
| 2968 | + $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value(); | |
| 2969 | + } | |
| 2970 | + } | |
| 2971 | + } | |
| 2972 | + return $return_array; | |
| 2973 | + } | |
| 2974 | + | |
| 2975 | + | |
| 2976 | + /** | |
| 2977 | + * Gets a pretty nice displayable nice for this model object. Often overridden | |
| 2978 | + * | |
| 2979 | + * @return string | |
| 2980 | + * @throws ReflectionException | |
| 2981 | + * @throws InvalidArgumentException | |
| 2982 | + * @throws InvalidInterfaceException | |
| 2983 | + * @throws InvalidDataTypeException | |
| 2984 | + * @throws EE_Error | |
| 2985 | + */ | |
| 2986 | + public function name() | |
| 2987 | +	{ | |
| 2988 | + // find a field that's not a text field | |
| 2989 | +		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base'); | |
| 2990 | +		if ($field_we_can_use) { | |
| 2991 | + return $this->get($field_we_can_use->get_name()); | |
| 2992 | + } | |
| 2993 | + $first_few_properties = $this->model_field_array(); | |
| 2994 | + $first_few_properties = array_slice($first_few_properties, 0, 3); | |
| 2995 | + $name_parts = array(); | |
| 2996 | +		foreach ($first_few_properties as $name => $value) { | |
| 2997 | + $name_parts[] = "$name:$value"; | |
| 2998 | + } | |
| 2999 | +		return implode(',', $name_parts); | |
| 3000 | + } | |
| 3001 | + | |
| 3002 | + | |
| 3003 | + /** | |
| 3004 | + * in_entity_map | |
| 3005 | + * Checks if this model object has been proven to already be in the entity map | |
| 3006 | + * | |
| 3007 | + * @return boolean | |
| 3008 | + * @throws ReflectionException | |
| 3009 | + * @throws InvalidArgumentException | |
| 3010 | + * @throws InvalidInterfaceException | |
| 3011 | + * @throws InvalidDataTypeException | |
| 3012 | + * @throws EE_Error | |
| 3013 | + */ | |
| 3014 | + public function in_entity_map() | |
| 3015 | +	{ | |
| 3016 | + // well, if we looked, did we find it in the entity map? | |
| 3017 | + return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this; | |
| 3018 | + } | |
| 3019 | + | |
| 3020 | + | |
| 3021 | + /** | |
| 3022 | + * refresh_from_db | |
| 3023 | + * Makes sure the fields and values on this model object are in-sync with what's in the database. | |
| 3024 | + * | |
| 3025 | + * @throws ReflectionException | |
| 3026 | + * @throws InvalidArgumentException | |
| 3027 | + * @throws InvalidInterfaceException | |
| 3028 | + * @throws InvalidDataTypeException | |
| 3029 | + * @throws EE_Error if this model object isn't in the entity mapper (because then you should | |
| 3030 | + * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE | |
| 3031 | + */ | |
| 3032 | + public function refresh_from_db() | |
| 3033 | +	{ | |
| 3034 | +		if ($this->ID() && $this->in_entity_map()) { | |
| 3035 | + $this->get_model()->refresh_entity_map_from_db($this->ID()); | |
| 3036 | +		} else { | |
| 3037 | + // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database) | |
| 3038 | + // if it has an ID but it's not in the map, and you're asking me to refresh it | |
| 3039 | + // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's | |
| 3040 | + // absolutely nothing in it for this ID | |
| 3041 | +			if (WP_DEBUG) { | |
| 3042 | + throw new EE_Error( | |
| 3043 | + sprintf( | |
| 3044 | + esc_html__( | |
| 3045 | + 'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.', | |
| 3046 | + 'event_espresso' | |
| 3047 | + ), | |
| 3048 | + $this->ID(), | |
| 3049 | + get_class($this->get_model()) . '::instance()->add_to_entity_map()', | |
| 3050 | + get_class($this->get_model()) . '::instance()->refresh_entity_map()' | |
| 3051 | + ) | |
| 3052 | + ); | |
| 3053 | + } | |
| 3054 | + } | |
| 3055 | + } | |
| 3056 | + | |
| 3057 | + | |
| 3058 | + /** | |
| 3059 | + * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method | |
| 3060 | + * (probably a bad assumption they have made, oh well) | |
| 3061 | + * | |
| 3062 | + * @return string | |
| 3063 | + */ | |
| 3064 | + public function __toString() | |
| 3065 | +	{ | |
| 3066 | +		try { | |
| 3067 | +			return sprintf('%s (%s)', $this->name(), $this->ID()); | |
| 3068 | +		} catch (Exception $e) { | |
| 3069 | + EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 3070 | + return ''; | |
| 3071 | + } | |
| 3072 | + } | |
| 3073 | + | |
| 3074 | + | |
| 3075 | + /** | |
| 3076 | + * Clear related model objects if they're already in the DB, because otherwise when we | |
| 3077 | + * UN-serialize this model object we'll need to be careful to add them to the entity map. | |
| 3078 | + * This means if we have made changes to those related model objects, and want to unserialize | |
| 3079 | + * the this model object on a subsequent request, changes to those related model objects will be lost. | |
| 3080 | + * Instead, those related model objects should be directly serialized and stored. | |
| 3081 | + * Eg, the following won't work: | |
| 3082 | + * $reg = EEM_Registration::instance()->get_one_by_ID( 123 ); | |
| 3083 | + * $att = $reg->attendee(); | |
| 3084 | + * $att->set( 'ATT_fname', 'Dirk' ); | |
| 3085 | + * update_option( 'my_option', serialize( $reg ) ); | |
| 3086 | + * //END REQUEST | |
| 3087 | + * //START NEXT REQUEST | |
| 3088 | + * $reg = get_option( 'my_option' ); | |
| 3089 | + * $reg->attendee()->save(); | |
| 3090 | + * And would need to be replace with: | |
| 3091 | + * $reg = EEM_Registration::instance()->get_one_by_ID( 123 ); | |
| 3092 | + * $att = $reg->attendee(); | |
| 3093 | + * $att->set( 'ATT_fname', 'Dirk' ); | |
| 3094 | + * update_option( 'my_option', serialize( $reg ) ); | |
| 3095 | + * //END REQUEST | |
| 3096 | + * //START NEXT REQUEST | |
| 3097 | + * $att = get_option( 'my_option' ); | |
| 3098 | + * $att->save(); | |
| 3099 | + * | |
| 3100 | + * @return array | |
| 3101 | + * @throws ReflectionException | |
| 3102 | + * @throws InvalidArgumentException | |
| 3103 | + * @throws InvalidInterfaceException | |
| 3104 | + * @throws InvalidDataTypeException | |
| 3105 | + * @throws EE_Error | |
| 3106 | + */ | |
| 3107 | + public function __sleep() | |
| 3108 | +	{ | |
| 3109 | + $model = $this->get_model(); | |
| 3110 | +		foreach ($model->relation_settings() as $relation_name => $relation_obj) { | |
| 3111 | +			if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 3112 | + $classname = 'EE_' . $model->get_this_model_name(); | |
| 3113 | + if ($this->get_one_from_cache($relation_name) instanceof $classname | |
| 3114 | + && $this->get_one_from_cache($relation_name)->ID() | |
| 3115 | +				) { | |
| 3116 | + $this->clear_cache( | |
| 3117 | + $relation_name, | |
| 3118 | + $this->get_one_from_cache($relation_name)->ID() | |
| 3119 | + ); | |
| 3120 | + } | |
| 3121 | + } | |
| 3122 | + } | |
| 3123 | + $this->_props_n_values_provided_in_constructor = array(); | |
| 3124 | + $properties_to_serialize = get_object_vars($this); | |
| 3125 | + // don't serialize the model. It's big and that risks recursion | |
| 3126 | + unset($properties_to_serialize['_model']); | |
| 3127 | + return array_keys($properties_to_serialize); | |
| 3128 | + } | |
| 3129 | + | |
| 3130 | + | |
| 3131 | + /** | |
| 3132 | + * restore _props_n_values_provided_in_constructor | |
| 3133 | + * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization, | |
| 3134 | + * and therefore should NOT be used to determine if state change has occurred since initial construction. | |
| 3135 | + * At best, you would only be able to detect if state change has occurred during THIS request. | |
| 3136 | + */ | |
| 3137 | + public function __wakeup() | |
| 3138 | +	{ | |
| 3139 | + $this->_props_n_values_provided_in_constructor = $this->_fields; | |
| 3140 | + } | |
| 3141 | + | |
| 3142 | + | |
| 3143 | + /** | |
| 3144 | + * Usage of this magic method is to ensure any internally cached references to object instances that must remain | |
| 3145 | + * distinct with the clone host instance are also cloned. | |
| 3146 | + */ | |
| 3147 | + public function __clone() | |
| 3148 | +	{ | |
| 3149 | + // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes). | |
| 3150 | +		foreach ($this->_fields as $field => $value) { | |
| 3151 | +			if ($value instanceof DateTime) { | |
| 3152 | + $this->_fields[ $field ] = clone $value; | |
| 3153 | + } | |
| 3154 | + } | |
| 3155 | + } | |
| 3156 | 3156 | } | 
| @@ -78,7 +78,7 @@ discard block | ||
| 78 | 78 |          $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | 
| 79 | 79 |          try { | 
| 80 | 80 | $controller->setRequestedVersion($version); | 
| 81 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 81 | +            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 82 | 82 | return $controller->sendResponse( | 
| 83 | 83 | new WP_Error( | 
| 84 | 84 | 'endpoint_parsing_error', | 
| @@ -119,7 +119,7 @@ discard block | ||
| 119 | 119 |          $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | 
| 120 | 120 |          try { | 
| 121 | 121 | $controller->setRequestedVersion($version); | 
| 122 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 122 | +            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 123 | 123 | return array(); | 
| 124 | 124 | } | 
| 125 | 125 | // get the model for this version | 
| @@ -176,11 +176,11 @@ discard block | ||
| 176 | 176 | */ | 
| 177 | 177 | protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema) | 
| 178 | 178 |      { | 
| 179 | -        if (isset($schema['properties'][ $field_name ]['default'])) { | |
| 180 | -            if (is_array($schema['properties'][ $field_name ]['default'])) { | |
| 181 | -                foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) { | |
| 179 | +        if (isset($schema['properties'][$field_name]['default'])) { | |
| 180 | +            if (is_array($schema['properties'][$field_name]['default'])) { | |
| 181 | +                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) { | |
| 182 | 182 |                      if ($default_key === 'raw') { | 
| 183 | - $schema['properties'][ $field_name ]['default'][ $default_key ] = | |
| 183 | + $schema['properties'][$field_name]['default'][$default_key] = | |
| 184 | 184 | ModelDataTranslator::prepareFieldValueForJson( | 
| 185 | 185 | $field, | 
| 186 | 186 | $default_value, | 
| @@ -189,9 +189,9 @@ discard block | ||
| 189 | 189 | } | 
| 190 | 190 | } | 
| 191 | 191 |              } else { | 
| 192 | - $schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 192 | + $schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 193 | 193 | $field, | 
| 194 | - $schema['properties'][ $field_name ]['default'], | |
| 194 | + $schema['properties'][$field_name]['default'], | |
| 195 | 195 | $this->getModelVersionInfo()->requestedVersion() | 
| 196 | 196 | ); | 
| 197 | 197 | } | 
| @@ -213,9 +213,9 @@ discard block | ||
| 213 | 213 | protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema) | 
| 214 | 214 |      { | 
| 215 | 215 |          if ($field instanceof EE_Datetime_Field) { | 
| 216 | - $schema['properties'][ $field_name . '_gmt' ] = $field->getSchema(); | |
| 216 | + $schema['properties'][$field_name.'_gmt'] = $field->getSchema(); | |
| 217 | 217 | // modify the description | 
| 218 | - $schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf( | |
| 218 | + $schema['properties'][$field_name.'_gmt']['description'] = sprintf( | |
| 219 | 219 |                  esc_html__('%s - the value for this field is in GMT.', 'event_espresso'), | 
| 220 | 220 | wp_specialchars_decode($field->get_nicename(), ENT_QUOTES) | 
| 221 | 221 | ); | 
| @@ -258,7 +258,7 @@ discard block | ||
| 258 | 258 |          $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | 
| 259 | 259 |          try { | 
| 260 | 260 | $controller->setRequestedVersion($version); | 
| 261 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 261 | +            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 262 | 262 | return $controller->sendResponse( | 
| 263 | 263 | new WP_Error( | 
| 264 | 264 | 'endpoint_parsing_error', | 
| @@ -337,7 +337,7 @@ discard block | ||
| 337 | 337 | public function getEntitiesFromModel($model, $request) | 
| 338 | 338 |      { | 
| 339 | 339 | $query_params = $this->createModelQueryParams($model, $request->get_params()); | 
| 340 | -        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) { | |
| 340 | +        if ( ! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) { | |
| 341 | 341 | $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name()); | 
| 342 | 342 | throw new RestException( | 
| 343 | 343 |                  sprintf('rest_%s_cannot_list', $model_name_plural), | 
| @@ -349,14 +349,14 @@ discard block | ||
| 349 | 349 |                  array('status' => 403) | 
| 350 | 350 | ); | 
| 351 | 351 | } | 
| 352 | -        if (! $request->get_header('no_rest_headers')) { | |
| 352 | +        if ( ! $request->get_header('no_rest_headers')) { | |
| 353 | 353 | $this->setHeadersFromQueryParams($model, $query_params); | 
| 354 | 354 | } | 
| 355 | 355 | /** @type array $results */ | 
| 356 | 356 | $results = $model->get_all_wpdb_results($query_params); | 
| 357 | 357 | $nice_results = array(); | 
| 358 | 358 |          foreach ($results as $result) { | 
| 359 | - $nice_results[] = $this->createEntityFromWpdbResult( | |
| 359 | + $nice_results[] = $this->createEntityFromWpdbResult( | |
| 360 | 360 | $model, | 
| 361 | 361 | $result, | 
| 362 | 362 | $request | 
| @@ -390,7 +390,7 @@ discard block | ||
| 390 | 390 |          $context = $this->validateContext($request->get_param('caps')); | 
| 391 | 391 | $model = $relation->get_this_model(); | 
| 392 | 392 | $related_model = $relation->get_other_model(); | 
| 393 | -        if (! isset($primary_model_query_params[0])) { | |
| 393 | +        if ( ! isset($primary_model_query_params[0])) { | |
| 394 | 394 | $primary_model_query_params[0] = array(); | 
| 395 | 395 | } | 
| 396 | 396 | // check if they can access the 1st model object | 
| @@ -413,7 +413,7 @@ discard block | ||
| 413 | 413 |          if (is_array($primary_model_rows)) { | 
| 414 | 414 | $primary_model_row = reset($primary_model_rows); | 
| 415 | 415 | } | 
| 416 | - if (! ( | |
| 416 | + if ( ! ( | |
| 417 | 417 | Capabilities::currentUserHasPartialAccessTo($related_model, $context) | 
| 418 | 418 | && $primary_model_row | 
| 419 | 419 | ) | 
| @@ -453,13 +453,13 @@ discard block | ||
| 453 | 453 | ); | 
| 454 | 454 | $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params()); | 
| 455 | 455 |          foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) { | 
| 456 | - $query_params[0][ $relation->get_this_model()->get_this_model_name() | |
| 456 | + $query_params[0][$relation->get_this_model()->get_this_model_name() | |
| 457 | 457 | . '.' | 
| 458 | - . $where_condition_key ] = $where_condition_value; | |
| 458 | + . $where_condition_key] = $where_condition_value; | |
| 459 | 459 | } | 
| 460 | 460 | $query_params['default_where_conditions'] = 'none'; | 
| 461 | 461 | $query_params['caps'] = $context; | 
| 462 | -        if (! $request->get_header('no_rest_headers')) { | |
| 462 | +        if ( ! $request->get_header('no_rest_headers')) { | |
| 463 | 463 | $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params); | 
| 464 | 464 | } | 
| 465 | 465 | /** @type array $results */ | 
| @@ -510,7 +510,7 @@ discard block | ||
| 510 | 510 | */ | 
| 511 | 511 | public function getEntitiesFromRelation($id, $relation, $request) | 
| 512 | 512 |      { | 
| 513 | -        if (! $relation->get_this_model()->has_primary_key_field()) { | |
| 513 | +        if ( ! $relation->get_this_model()->has_primary_key_field()) { | |
| 514 | 514 | throw new EE_Error( | 
| 515 | 515 | sprintf( | 
| 516 | 516 | __( | 
| @@ -555,7 +555,7 @@ discard block | ||
| 555 | 555 | Capabilities::getMissingPermissionsString($model, $query_params['caps']) | 
| 556 | 556 | ); | 
| 557 | 557 | // normally the limit to a 2-part array, where the 2nd item is the limit | 
| 558 | -        if (! isset($query_params['limit'])) { | |
| 558 | +        if ( ! isset($query_params['limit'])) { | |
| 559 | 559 | $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit(); | 
| 560 | 560 | } | 
| 561 | 561 |          if (is_array($query_params['limit'])) { | 
| @@ -594,7 +594,7 @@ discard block | ||
| 594 | 594 | */ | 
| 595 | 595 | public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null) | 
| 596 | 596 |      { | 
| 597 | -        if (! $rest_request instanceof WP_REST_Request) { | |
| 597 | +        if ( ! $rest_request instanceof WP_REST_Request) { | |
| 598 | 598 | // ok so this was called in the old style, where the 3rd arg was | 
| 599 | 599 | // $include, and the 4th arg was $context | 
| 600 | 600 | // now setup the request just to avoid fatal errors, although we won't be able | 
| @@ -622,7 +622,7 @@ discard block | ||
| 622 | 622 | $db_row, | 
| 623 | 623 | array( | 
| 624 | 624 | 0 => array( | 
| 625 | - $model->primary_key_name() => $db_row[ $model->get_primary_key_field()->get_qualified_column() ] | |
| 625 | + $model->primary_key_name() => $db_row[$model->get_primary_key_field()->get_qualified_column()] | |
| 626 | 626 | ) | 
| 627 | 627 | ), | 
| 628 | 628 | $rest_request | 
| @@ -669,7 +669,7 @@ discard block | ||
| 669 | 669 | $rest_request, | 
| 670 | 670 | $this | 
| 671 | 671 | ); | 
| 672 | -        if (! $current_user_full_access_to_entity) { | |
| 672 | +        if ( ! $current_user_full_access_to_entity) { | |
| 673 | 673 | $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields( | 
| 674 | 674 | $entity_array, | 
| 675 | 675 | $model, | 
| @@ -701,7 +701,7 @@ discard block | ||
| 701 | 701 | */ | 
| 702 | 702 | protected function addProtectedProperty(EEM_Base $model, $results_so_far, $protected) | 
| 703 | 703 |      { | 
| 704 | -        if (! $model->hasPassword() || ! $protected) { | |
| 704 | +        if ( ! $model->hasPassword() || ! $protected) { | |
| 705 | 705 | return $results_so_far; | 
| 706 | 706 | } | 
| 707 | 707 | $password_field = $model->getPasswordField(); | 
| @@ -715,7 +715,7 @@ discard block | ||
| 715 | 715 | $fields_included | 
| 716 | 716 | ); | 
| 717 | 717 |          foreach ($fields_included as $field_name) { | 
| 718 | - $results_so_far['_protected'][] = $field_name ; | |
| 718 | + $results_so_far['_protected'][] = $field_name; | |
| 719 | 719 | } | 
| 720 | 720 | return $results_so_far; | 
| 721 | 721 | } | 
| @@ -746,8 +746,8 @@ discard block | ||
| 746 | 746 |          if ($do_chevy_shuffle) { | 
| 747 | 747 | global $post; | 
| 748 | 748 | $old_post = $post; | 
| 749 | - $post = get_post($result[ $model->primary_key_name() ]); | |
| 750 | -            if (! $post instanceof \WP_Post) { | |
| 749 | + $post = get_post($result[$model->primary_key_name()]); | |
| 750 | +            if ( ! $post instanceof \WP_Post) { | |
| 751 | 751 | // well that's weird, because $result is what we JUST fetched from the database | 
| 752 | 752 | throw new RestException( | 
| 753 | 753 | 'error_fetching_post_from_database_results', | 
| @@ -757,7 +757,7 @@ discard block | ||
| 757 | 757 | ) | 
| 758 | 758 | ); | 
| 759 | 759 | } | 
| 760 | - $model_object_classname = 'EE_' . $model->get_this_model_name(); | |
| 760 | + $model_object_classname = 'EE_'.$model->get_this_model_name(); | |
| 761 | 761 |              $post->{$model_object_classname} = \EE_Registry::instance()->load_class( | 
| 762 | 762 | $model_object_classname, | 
| 763 | 763 | $result, | 
| @@ -768,13 +768,13 @@ discard block | ||
| 768 | 768 |          foreach ($result as $field_name => $field_value) { | 
| 769 | 769 | $field_obj = $model->field_settings_for($field_name); | 
| 770 | 770 |              if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) { | 
| 771 | - unset($result[ $field_name ]); | |
| 771 | + unset($result[$field_name]); | |
| 772 | 772 | } elseif ($this->isSubclassOfOne( | 
| 773 | 773 | $field_obj, | 
| 774 | 774 | $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat() | 
| 775 | 775 | ) | 
| 776 | 776 |              ) { | 
| 777 | - $result[ $field_name ] = array( | |
| 777 | + $result[$field_name] = array( | |
| 778 | 778 | 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | 
| 779 | 779 | 'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | 
| 780 | 780 | ); | 
| @@ -783,7 +783,7 @@ discard block | ||
| 783 | 783 | $this->getModelVersionInfo()->fieldsThatHavePrettyFormat() | 
| 784 | 784 | ) | 
| 785 | 785 |              ) { | 
| 786 | - $result[ $field_name ] = array( | |
| 786 | + $result[$field_name] = array( | |
| 787 | 787 | 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | 
| 788 | 788 | 'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | 
| 789 | 789 | ); | 
| @@ -814,10 +814,10 @@ discard block | ||
| 814 | 814 | $this->getModelVersionInfo()->requestedVersion() | 
| 815 | 815 | ); | 
| 816 | 816 | } | 
| 817 | - $result[ $field_name . '_gmt' ] = $gmt_date; | |
| 818 | - $result[ $field_name ] = $local_date; | |
| 817 | + $result[$field_name.'_gmt'] = $gmt_date; | |
| 818 | + $result[$field_name] = $local_date; | |
| 819 | 819 |              } else { | 
| 820 | - $result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value); | |
| 820 | + $result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value); | |
| 821 | 821 | } | 
| 822 | 822 | } | 
| 823 | 823 |          if ($do_chevy_shuffle) { | 
| @@ -869,7 +869,7 @@ discard block | ||
| 869 | 869 | protected function addExtraFields(EEM_Base $model, $db_row, $entity_array) | 
| 870 | 870 |      { | 
| 871 | 871 |          if ($model instanceof EEM_CPT_Base) { | 
| 872 | - $entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]); | |
| 872 | + $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]); | |
| 873 | 873 | } | 
| 874 | 874 | return $entity_array; | 
| 875 | 875 | } | 
| @@ -894,7 +894,7 @@ discard block | ||
| 894 | 894 | 'href' => $this->getVersionedLinkTo( | 
| 895 | 895 | EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | 
| 896 | 896 | . '/' | 
| 897 | - . $entity_array[ $model->primary_key_name() ] | |
| 897 | + . $entity_array[$model->primary_key_name()] | |
| 898 | 898 | ), | 
| 899 | 899 | ), | 
| 900 | 900 | ); | 
| @@ -910,12 +910,12 @@ discard block | ||
| 910 | 910 |          if ($model->has_primary_key_field()) { | 
| 911 | 911 |              foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) { | 
| 912 | 912 | $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj); | 
| 913 | - $links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array( | |
| 913 | + $links[EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array( | |
| 914 | 914 | array( | 
| 915 | 915 | 'href' => $this->getVersionedLinkTo( | 
| 916 | 916 | EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | 
| 917 | 917 | . '/' | 
| 918 | - . $entity_array[ $model->primary_key_name() ] | |
| 918 | + . $entity_array[$model->primary_key_name()] | |
| 919 | 919 | . '/' | 
| 920 | 920 | . $related_model_part | 
| 921 | 921 | ), | 
| @@ -947,7 +947,7 @@ discard block | ||
| 947 | 947 | $included_items_protected = false | 
| 948 | 948 |      ) { | 
| 949 | 949 | // if $db_row not included, hope the entity array has what we need | 
| 950 | -        if (! $db_row) { | |
| 950 | +        if ( ! $db_row) { | |
| 951 | 951 | $db_row = $entity_array; | 
| 952 | 952 | } | 
| 953 | 953 | $relation_settings = $this->getModelVersionInfo()->relationSettings($model); | 
| @@ -980,7 +980,7 @@ discard block | ||
| 980 | 980 | $model->deduce_fields_n_values_from_cols_n_values($db_row) | 
| 981 | 981 | ) | 
| 982 | 982 | ); | 
| 983 | -                if (! $included_items_protected) { | |
| 983 | +                if ( ! $included_items_protected) { | |
| 984 | 984 | $related_results = $this->getEntitiesFromRelationUsingModelQueryParams( | 
| 985 | 985 | $primary_model_query_params, | 
| 986 | 986 | $relation_obj, | 
| @@ -994,7 +994,7 @@ discard block | ||
| 994 | 994 |                  if ($related_results instanceof WP_Error) { | 
| 995 | 995 | $related_results = null; | 
| 996 | 996 | } | 
| 997 | - $entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results; | |
| 997 | + $entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results; | |
| 998 | 998 | } | 
| 999 | 999 | } | 
| 1000 | 1000 | return $entity_array; | 
| @@ -1019,7 +1019,7 @@ discard block | ||
| 1019 | 1019 |          $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), ''); | 
| 1020 | 1020 | $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model); | 
| 1021 | 1021 | // if they passed in * or didn't specify any includes, return everything | 
| 1022 | -        if (! in_array('*', $includes_for_this_model) | |
| 1022 | +        if ( ! in_array('*', $includes_for_this_model) | |
| 1023 | 1023 | && ! empty($includes_for_this_model) | 
| 1024 | 1024 |          ) { | 
| 1025 | 1025 |              if ($model->has_primary_key_field()) { | 
| @@ -1073,12 +1073,12 @@ discard block | ||
| 1073 | 1073 | // it's password protected, so they shouldn't be able to read this. Remove the value | 
| 1074 | 1074 | $schema = $this->fields_calculator->getJsonSchemaForModel($model); | 
| 1075 | 1075 | if ($row_is_protected | 
| 1076 | - && isset($schema['properties'][ $field_to_calculate ]['protected']) | |
| 1077 | -                    && $schema['properties'][ $field_to_calculate ]['protected']) { | |
| 1076 | + && isset($schema['properties'][$field_to_calculate]['protected']) | |
| 1077 | +                    && $schema['properties'][$field_to_calculate]['protected']) { | |
| 1078 | 1078 | $calculated_value = null; | 
| 1079 | 1079 | $protected_fields[] = $field_to_calculate; | 
| 1080 | -                    if ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1081 | -                        switch ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1080 | +                    if ($schema['properties'][$field_to_calculate]['type']) { | |
| 1081 | +                        switch ($schema['properties'][$field_to_calculate]['type']) { | |
| 1082 | 1082 | case 'boolean': | 
| 1083 | 1083 | $calculated_value = false; | 
| 1084 | 1084 | break; | 
| @@ -1188,7 +1188,7 @@ discard block | ||
| 1188 | 1188 | */ | 
| 1189 | 1189 | public function validateContext($context) | 
| 1190 | 1190 |      { | 
| 1191 | -        if (! $context) { | |
| 1191 | +        if ( ! $context) { | |
| 1192 | 1192 | $context = EEM_Base::caps_read; | 
| 1193 | 1193 | } | 
| 1194 | 1194 | $valid_contexts = EEM_Base::valid_cap_contexts(); | 
| @@ -1213,7 +1213,7 @@ discard block | ||
| 1213 | 1213 | EEM_Base::default_where_conditions_minimum_all, | 
| 1214 | 1214 | EEM_Base::default_where_conditions_minimum_others, | 
| 1215 | 1215 | ); | 
| 1216 | -        if (! $default_query_params) { | |
| 1216 | +        if ( ! $default_query_params) { | |
| 1217 | 1217 | $default_query_params = EEM_Base::default_where_conditions_all; | 
| 1218 | 1218 | } | 
| 1219 | 1219 | if (in_array( | 
| @@ -1296,14 +1296,14 @@ discard block | ||
| 1296 | 1296 | } | 
| 1297 | 1297 |          if (isset($query_params['limit'])) { | 
| 1298 | 1298 | // limit should be either a string like '23' or '23,43', or an array with two items in it | 
| 1299 | -            if (! is_array($query_params['limit'])) { | |
| 1299 | +            if ( ! is_array($query_params['limit'])) { | |
| 1300 | 1300 |                  $limit_array = explode(',', (string) $query_params['limit']); | 
| 1301 | 1301 |              } else { | 
| 1302 | 1302 | $limit_array = $query_params['limit']; | 
| 1303 | 1303 | } | 
| 1304 | 1304 | $sanitized_limit = array(); | 
| 1305 | 1305 |              foreach ($limit_array as $key => $limit_part) { | 
| 1306 | -                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) { | |
| 1306 | +                if ($this->debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) { | |
| 1307 | 1307 | throw new EE_Error( | 
| 1308 | 1308 | sprintf( | 
| 1309 | 1309 | __( | 
| @@ -1335,7 +1335,7 @@ discard block | ||
| 1335 | 1335 | // if this is a model protected by a password on another model, exclude the password protected | 
| 1336 | 1336 | // entities by default. But if they passed in a password, try to show them all. If the password is wrong, | 
| 1337 | 1337 | // though, they'll get an error (see Read::createEntityFromWpdbResult() which calls Read::checkPassword) | 
| 1338 | - if (! $model->hasPassword() | |
| 1338 | + if ( ! $model->hasPassword() | |
| 1339 | 1339 | && $model->restrictedByRelatedModelPassword() | 
| 1340 | 1340 |              && $model_query_params['caps'] === EEM_Base::caps_read) { | 
| 1341 | 1341 |              if (empty($query_params['password'])) { | 
| @@ -1360,9 +1360,9 @@ discard block | ||
| 1360 | 1360 | $model_ready_query_params = array(); | 
| 1361 | 1361 |          foreach ($query_params as $key => $value) { | 
| 1362 | 1362 |              if (is_array($value)) { | 
| 1363 | - $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value); | |
| 1363 | + $model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value); | |
| 1364 | 1364 |              } else { | 
| 1365 | - $model_ready_query_params[ $key ] = $value; | |
| 1365 | + $model_ready_query_params[$key] = $value; | |
| 1366 | 1366 | } | 
| 1367 | 1367 | } | 
| 1368 | 1368 | return $model_ready_query_params; | 
| @@ -1380,9 +1380,9 @@ discard block | ||
| 1380 | 1380 | $model_ready_query_params = array(); | 
| 1381 | 1381 |          foreach ($query_params as $key => $value) { | 
| 1382 | 1382 |              if (is_array($value)) { | 
| 1383 | - $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value); | |
| 1383 | + $model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value); | |
| 1384 | 1384 |              } else { | 
| 1385 | - $model_ready_query_params[ $key ] = $value; | |
| 1385 | + $model_ready_query_params[$key] = $value; | |
| 1386 | 1386 | } | 
| 1387 | 1387 | } | 
| 1388 | 1388 | return $model_ready_query_params; | 
| @@ -1414,17 +1414,17 @@ discard block | ||
| 1414 | 1414 |          foreach ($exploded_contents as $item) { | 
| 1415 | 1415 | $item = trim($item); | 
| 1416 | 1416 | // if no prefix was provided, so we look for items with no "." in them | 
| 1417 | -            if (! $prefix) { | |
| 1417 | +            if ( ! $prefix) { | |
| 1418 | 1418 | // does this item have a period? | 
| 1419 | 1419 |                  if (strpos($item, '.') === false) { | 
| 1420 | 1420 | // if not, then its what we're looking for | 
| 1421 | 1421 | $contents_with_prefix[] = $item; | 
| 1422 | 1422 | } | 
| 1423 | -            } elseif (strpos($item, $prefix . '.') === 0) { | |
| 1423 | +            } elseif (strpos($item, $prefix.'.') === 0) { | |
| 1424 | 1424 | // this item has the prefix and a period, grab it | 
| 1425 | 1425 | $contents_with_prefix[] = substr( | 
| 1426 | 1426 | $item, | 
| 1427 | - strpos($item, $prefix . '.') + strlen($prefix . '.') | |
| 1427 | + strpos($item, $prefix.'.') + strlen($prefix.'.') | |
| 1428 | 1428 | ); | 
| 1429 | 1429 |              } elseif ($item === $prefix) { | 
| 1430 | 1430 | // this item is JUST the prefix | 
| @@ -1463,9 +1463,9 @@ discard block | ||
| 1463 | 1463 |          if ($model_name) { | 
| 1464 | 1464 |              foreach ($includes as $field_to_include) { | 
| 1465 | 1465 | $field_to_include = trim($field_to_include); | 
| 1466 | -                if (strpos($field_to_include, $model_name . '.') === 0) { | |
| 1466 | +                if (strpos($field_to_include, $model_name.'.') === 0) { | |
| 1467 | 1467 | // found the model name at the exact start | 
| 1468 | - $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include); | |
| 1468 | + $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include); | |
| 1469 | 1469 | $extracted_fields_to_include[] = $field_sans_model_name; | 
| 1470 | 1470 |                  } elseif ($field_to_include == $model_name) { | 
| 1471 | 1471 | $extracted_fields_to_include[] = '*'; | 
| @@ -1506,7 +1506,7 @@ discard block | ||
| 1506 | 1506 | $restricted_query_params['caps'] = $context; | 
| 1507 | 1507 |          $this->setDebugInfo('model query params', $restricted_query_params); | 
| 1508 | 1508 | $model_rows = $model->get_all_wpdb_results($restricted_query_params); | 
| 1509 | -        if (! empty($model_rows)) { | |
| 1509 | +        if ( ! empty($model_rows)) { | |
| 1510 | 1510 | return $this->createEntityFromWpdbResult( | 
| 1511 | 1511 | $model, | 
| 1512 | 1512 | reset($model_rows), | 
| @@ -1518,7 +1518,7 @@ discard block | ||
| 1518 | 1518 |              if ($model->exists($query_params)) { | 
| 1519 | 1519 | // you got shafted- it existed but we didn't want to tell you! | 
| 1520 | 1520 | throw new RestException( | 
| 1521 | - 'rest_user_cannot_' . $context, | |
| 1521 | + 'rest_user_cannot_'.$context, | |
| 1522 | 1522 | sprintf( | 
| 1523 | 1523 |                          __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'), | 
| 1524 | 1524 | $context, | 
| @@ -1567,11 +1567,11 @@ discard block | ||
| 1567 | 1567 | } | 
| 1568 | 1568 | // if this entity requires a password, they better give it and it better be right! | 
| 1569 | 1569 | if ($model->hasPassword() | 
| 1570 | -            && $model_row[ $model->getPasswordField()->get_qualified_column() ] !== '') { | |
| 1570 | +            && $model_row[$model->getPasswordField()->get_qualified_column()] !== '') { | |
| 1571 | 1571 |              if (empty($request['password'])) { | 
| 1572 | 1572 | throw new RestPasswordRequiredException(); | 
| 1573 | - } elseif (!hash_equals( | |
| 1574 | - $model_row[ $model->getPasswordField()->get_qualified_column() ], | |
| 1573 | + } elseif ( ! hash_equals( | |
| 1574 | + $model_row[$model->getPasswordField()->get_qualified_column()], | |
| 1575 | 1575 | $request['password'] | 
| 1576 | 1576 |              )) { | 
| 1577 | 1577 | throw new RestPasswordIncorrectException(); | 
| @@ -1582,12 +1582,12 @@ discard block | ||
| 1582 | 1582 |              $password_supplied = $request->get_param('password'); | 
| 1583 | 1583 |              if (empty($password_supplied)) { | 
| 1584 | 1584 | $query_params['exclude_protected'] = true; | 
| 1585 | -                if (!$model->exists($query_params)) { | |
| 1585 | +                if ( ! $model->exists($query_params)) { | |
| 1586 | 1586 | throw new RestPasswordRequiredException(); | 
| 1587 | 1587 | } | 
| 1588 | 1588 |              } else { | 
| 1589 | - $query_params[0][ $model->modelChainAndPassword() ] = $password_supplied; | |
| 1590 | -                if (!$model->exists($query_params)) { | |
| 1589 | + $query_params[0][$model->modelChainAndPassword()] = $password_supplied; | |
| 1590 | +                if ( ! $model->exists($query_params)) { | |
| 1591 | 1591 | throw new RestPasswordIncorrectException(); | 
| 1592 | 1592 | } | 
| 1593 | 1593 | } | 
| @@ -45,1554 +45,1554 @@ | ||
| 45 | 45 |  { | 
| 46 | 46 | |
| 47 | 47 | |
| 48 | - /** | |
| 49 | - * @var CalculatedModelFields | |
| 50 | - */ | |
| 51 | - protected $fields_calculator; | |
| 52 | - | |
| 53 | - | |
| 54 | - /** | |
| 55 | - * Read constructor. | |
| 56 | - * @param CalculatedModelFields $fields_calculator | |
| 57 | - */ | |
| 58 | - public function __construct(CalculatedModelFields $fields_calculator) | |
| 59 | -    { | |
| 60 | - parent::__construct(); | |
| 61 | - $this->fields_calculator = $fields_calculator; | |
| 62 | - } | |
| 63 | - | |
| 64 | - | |
| 65 | - /** | |
| 66 | - * Handles requests to get all (or a filtered subset) of entities for a particular model | |
| 67 | - * | |
| 68 | - * @param WP_REST_Request $request | |
| 69 | - * @param string $version | |
| 70 | - * @param string $model_name | |
| 71 | - * @return WP_REST_Response|WP_Error | |
| 72 | - * @throws InvalidArgumentException | |
| 73 | - * @throws InvalidDataTypeException | |
| 74 | - * @throws InvalidInterfaceException | |
| 75 | - */ | |
| 76 | - public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name) | |
| 77 | -    { | |
| 78 | -        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 79 | -        try { | |
| 80 | - $controller->setRequestedVersion($version); | |
| 81 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 82 | - return $controller->sendResponse( | |
| 83 | - new WP_Error( | |
| 84 | - 'endpoint_parsing_error', | |
| 85 | - sprintf( | |
| 86 | - __( | |
| 87 | - 'There is no model for endpoint %s. Please contact event espresso support', | |
| 88 | - 'event_espresso' | |
| 89 | - ), | |
| 90 | - $model_name | |
| 91 | - ) | |
| 92 | - ) | |
| 93 | - ); | |
| 94 | - } | |
| 95 | - return $controller->sendResponse( | |
| 96 | - $controller->getEntitiesFromModel( | |
| 97 | - $controller->getModelVersionInfo()->loadModel($model_name), | |
| 98 | - $request | |
| 99 | - ) | |
| 100 | - ); | |
| 101 | -        } catch (Exception $e) { | |
| 102 | - return $controller->sendResponse($e); | |
| 103 | - } | |
| 104 | - } | |
| 105 | - | |
| 106 | - | |
| 107 | - /** | |
| 108 | - * Prepares and returns schema for any OPTIONS request. | |
| 109 | - * | |
| 110 | - * @param string $version The API endpoint version being used. | |
| 111 | - * @param string $model_name Something like `Event` or `Registration` | |
| 112 | - * @return array | |
| 113 | - * @throws InvalidArgumentException | |
| 114 | - * @throws InvalidDataTypeException | |
| 115 | - * @throws InvalidInterfaceException | |
| 116 | - */ | |
| 117 | - public static function handleSchemaRequest($version, $model_name) | |
| 118 | -    { | |
| 119 | -        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 120 | -        try { | |
| 121 | - $controller->setRequestedVersion($version); | |
| 122 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 123 | - return array(); | |
| 124 | - } | |
| 125 | - // get the model for this version | |
| 126 | - $model = $controller->getModelVersionInfo()->loadModel($model_name); | |
| 127 | -            $model_schema = new JsonModelSchema($model, LoaderFactory::getLoader()->getShared('EventEspresso\core\libraries\rest_api\CalculatedModelFields')); | |
| 128 | - return $model_schema->getModelSchemaForRelations( | |
| 129 | - $controller->getModelVersionInfo()->relationSettings($model), | |
| 130 | - $controller->customizeSchemaForRestResponse( | |
| 131 | - $model, | |
| 132 | - $model_schema->getModelSchemaForFields( | |
| 133 | - $controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model), | |
| 134 | - $model_schema->getInitialSchemaStructure() | |
| 135 | - ) | |
| 136 | - ) | |
| 137 | - ); | |
| 138 | -        } catch (Exception $e) { | |
| 139 | - return array(); | |
| 140 | - } | |
| 141 | - } | |
| 142 | - | |
| 143 | - | |
| 144 | - /** | |
| 145 | - * This loops through each field in the given schema for the model and does the following: | |
| 146 | - * - add any extra fields that are REST API specific and related to existing fields. | |
| 147 | - * - transform default values into the correct format for a REST API response. | |
| 148 | - * | |
| 149 | - * @param EEM_Base $model | |
| 150 | - * @param array $schema | |
| 151 | - * @return array The final schema. | |
| 152 | - */ | |
| 153 | - protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema) | |
| 154 | -    { | |
| 155 | -        foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) { | |
| 156 | - $schema = $this->translateDefaultsForRestResponse( | |
| 157 | - $field_name, | |
| 158 | - $field, | |
| 159 | - $this->maybeAddExtraFieldsToSchema($field_name, $field, $schema) | |
| 160 | - ); | |
| 161 | - } | |
| 162 | - return $schema; | |
| 163 | - } | |
| 164 | - | |
| 165 | - | |
| 166 | - /** | |
| 167 | - * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST | |
| 168 | - * response. | |
| 169 | - * | |
| 170 | - * @param $field_name | |
| 171 | - * @param EE_Model_Field_Base $field | |
| 172 | - * @param array $schema | |
| 173 | - * @return array | |
| 174 | - * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we | |
| 175 | - * did, let's know about it ASAP, so let the exception bubble up) | |
| 176 | - */ | |
| 177 | - protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema) | |
| 178 | -    { | |
| 179 | -        if (isset($schema['properties'][ $field_name ]['default'])) { | |
| 180 | -            if (is_array($schema['properties'][ $field_name ]['default'])) { | |
| 181 | -                foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) { | |
| 182 | -                    if ($default_key === 'raw') { | |
| 183 | - $schema['properties'][ $field_name ]['default'][ $default_key ] = | |
| 184 | - ModelDataTranslator::prepareFieldValueForJson( | |
| 185 | - $field, | |
| 186 | - $default_value, | |
| 187 | - $this->getModelVersionInfo()->requestedVersion() | |
| 188 | - ); | |
| 189 | - } | |
| 190 | - } | |
| 191 | -            } else { | |
| 192 | - $schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 193 | - $field, | |
| 194 | - $schema['properties'][ $field_name ]['default'], | |
| 195 | - $this->getModelVersionInfo()->requestedVersion() | |
| 196 | - ); | |
| 197 | - } | |
| 198 | - } | |
| 199 | - return $schema; | |
| 200 | - } | |
| 201 | - | |
| 202 | - | |
| 203 | - /** | |
| 204 | - * Adds additional fields to the schema | |
| 205 | - * The REST API returns a GMT value field for each datetime field in the resource. Thus the description about this | |
| 206 | - * needs to be added to the schema. | |
| 207 | - * | |
| 208 | - * @param $field_name | |
| 209 | - * @param EE_Model_Field_Base $field | |
| 210 | - * @param array $schema | |
| 211 | - * @return array | |
| 212 | - */ | |
| 213 | - protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema) | |
| 214 | -    { | |
| 215 | -        if ($field instanceof EE_Datetime_Field) { | |
| 216 | - $schema['properties'][ $field_name . '_gmt' ] = $field->getSchema(); | |
| 217 | - // modify the description | |
| 218 | - $schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf( | |
| 219 | -                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'), | |
| 220 | - wp_specialchars_decode($field->get_nicename(), ENT_QUOTES) | |
| 221 | - ); | |
| 222 | - } | |
| 223 | - return $schema; | |
| 224 | - } | |
| 225 | - | |
| 226 | - | |
| 227 | - /** | |
| 228 | - * Used to figure out the route from the request when a `WP_REST_Request` object is not available | |
| 229 | - * | |
| 230 | - * @return string | |
| 231 | - */ | |
| 232 | - protected function getRouteFromRequest() | |
| 233 | -    { | |
| 234 | - if (isset($GLOBALS['wp']) | |
| 235 | - && $GLOBALS['wp'] instanceof \WP | |
| 236 | - && isset($GLOBALS['wp']->query_vars['rest_route']) | |
| 237 | -        ) { | |
| 238 | - return $GLOBALS['wp']->query_vars['rest_route']; | |
| 239 | -        } else { | |
| 240 | - return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/'; | |
| 241 | - } | |
| 242 | - } | |
| 243 | - | |
| 244 | - | |
| 245 | - /** | |
| 246 | - * Gets a single entity related to the model indicated in the path and its id | |
| 247 | - * | |
| 248 | - * @param WP_REST_Request $request | |
| 249 | - * @param string $version | |
| 250 | - * @param string $model_name | |
| 251 | - * @return WP_REST_Response|WP_Error | |
| 252 | - * @throws InvalidDataTypeException | |
| 253 | - * @throws InvalidInterfaceException | |
| 254 | - * @throws InvalidArgumentException | |
| 255 | - */ | |
| 256 | - public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name) | |
| 257 | -    { | |
| 258 | -        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 259 | -        try { | |
| 260 | - $controller->setRequestedVersion($version); | |
| 261 | -            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 262 | - return $controller->sendResponse( | |
| 263 | - new WP_Error( | |
| 264 | - 'endpoint_parsing_error', | |
| 265 | - sprintf( | |
| 266 | - __( | |
| 267 | - 'There is no model for endpoint %s. Please contact event espresso support', | |
| 268 | - 'event_espresso' | |
| 269 | - ), | |
| 270 | - $model_name | |
| 271 | - ) | |
| 272 | - ) | |
| 273 | - ); | |
| 274 | - } | |
| 275 | - return $controller->sendResponse( | |
| 276 | - $controller->getEntityFromModel( | |
| 277 | - $controller->getModelVersionInfo()->loadModel($model_name), | |
| 278 | - $request | |
| 279 | - ) | |
| 280 | - ); | |
| 281 | -        } catch (Exception $e) { | |
| 282 | - return $controller->sendResponse($e); | |
| 283 | - } | |
| 284 | - } | |
| 285 | - | |
| 286 | - | |
| 287 | - /** | |
| 288 | - * Gets all the related entities (or if its a belongs-to relation just the one) | |
| 289 | - * to the item with the given id | |
| 290 | - * | |
| 291 | - * @param WP_REST_Request $request | |
| 292 | - * @param string $version | |
| 293 | - * @param string $model_name | |
| 294 | - * @param string $related_model_name | |
| 295 | - * @return WP_REST_Response|WP_Error | |
| 296 | - * @throws InvalidDataTypeException | |
| 297 | - * @throws InvalidInterfaceException | |
| 298 | - * @throws InvalidArgumentException | |
| 299 | - */ | |
| 300 | - public static function handleRequestGetRelated( | |
| 301 | - WP_REST_Request $request, | |
| 302 | - $version, | |
| 303 | - $model_name, | |
| 304 | - $related_model_name | |
| 305 | -    ) { | |
| 306 | -        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 307 | -        try { | |
| 308 | - $controller->setRequestedVersion($version); | |
| 309 | - $main_model = $controller->validateModel($model_name); | |
| 310 | - $controller->validateModel($related_model_name); | |
| 311 | - return $controller->sendResponse( | |
| 312 | - $controller->getEntitiesFromRelation( | |
| 313 | -                    $request->get_param('id'), | |
| 314 | - $main_model->related_settings_for($related_model_name), | |
| 315 | - $request | |
| 316 | - ) | |
| 317 | - ); | |
| 318 | -        } catch (Exception $e) { | |
| 319 | - return $controller->sendResponse($e); | |
| 320 | - } | |
| 321 | - } | |
| 322 | - | |
| 323 | - | |
| 324 | - /** | |
| 325 | - * Gets a collection for the given model and filters | |
| 326 | - * | |
| 327 | - * @param EEM_Base $model | |
| 328 | - * @param WP_REST_Request $request | |
| 329 | - * @return array | |
| 330 | - * @throws EE_Error | |
| 331 | - * @throws InvalidArgumentException | |
| 332 | - * @throws InvalidDataTypeException | |
| 333 | - * @throws InvalidInterfaceException | |
| 334 | - * @throws ReflectionException | |
| 335 | - * @throws RestException | |
| 336 | - */ | |
| 337 | - public function getEntitiesFromModel($model, $request) | |
| 338 | -    { | |
| 339 | - $query_params = $this->createModelQueryParams($model, $request->get_params()); | |
| 340 | -        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) { | |
| 341 | - $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name()); | |
| 342 | - throw new RestException( | |
| 343 | -                sprintf('rest_%s_cannot_list', $model_name_plural), | |
| 344 | - sprintf( | |
| 345 | -                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'), | |
| 346 | - $model_name_plural, | |
| 347 | - Capabilities::getMissingPermissionsString($model, $query_params['caps']) | |
| 348 | - ), | |
| 349 | -                array('status' => 403) | |
| 350 | - ); | |
| 351 | - } | |
| 352 | -        if (! $request->get_header('no_rest_headers')) { | |
| 353 | - $this->setHeadersFromQueryParams($model, $query_params); | |
| 354 | - } | |
| 355 | - /** @type array $results */ | |
| 356 | - $results = $model->get_all_wpdb_results($query_params); | |
| 357 | - $nice_results = array(); | |
| 358 | -        foreach ($results as $result) { | |
| 359 | - $nice_results[] = $this->createEntityFromWpdbResult( | |
| 360 | - $model, | |
| 361 | - $result, | |
| 362 | - $request | |
| 363 | - ); | |
| 364 | - } | |
| 365 | - return $nice_results; | |
| 366 | - } | |
| 367 | - | |
| 368 | - | |
| 369 | - /** | |
| 370 | - * Gets the collection for given relation object | |
| 371 | - * The same as Read::get_entities_from_model(), except if the relation | |
| 372 | - * is a HABTM relation, in which case it merges any non-foreign-key fields from | |
| 373 | - * the join-model-object into the results | |
| 374 | - * | |
| 375 | - * @param array $primary_model_query_params query params for finding the item from which | |
| 376 | - * relations will be based | |
| 377 | - * @param \EE_Model_Relation_Base $relation | |
| 378 | - * @param WP_REST_Request $request | |
| 379 | - * @return array | |
| 380 | - * @throws EE_Error | |
| 381 | - * @throws InvalidArgumentException | |
| 382 | - * @throws InvalidDataTypeException | |
| 383 | - * @throws InvalidInterfaceException | |
| 384 | - * @throws ReflectionException | |
| 385 | - * @throws RestException | |
| 386 | - * @throws \EventEspresso\core\exceptions\ModelConfigurationException | |
| 387 | - */ | |
| 388 | - protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request) | |
| 389 | -    { | |
| 390 | -        $context = $this->validateContext($request->get_param('caps')); | |
| 391 | - $model = $relation->get_this_model(); | |
| 392 | - $related_model = $relation->get_other_model(); | |
| 393 | -        if (! isset($primary_model_query_params[0])) { | |
| 394 | - $primary_model_query_params[0] = array(); | |
| 395 | - } | |
| 396 | - // check if they can access the 1st model object | |
| 397 | - $primary_model_query_params = array( | |
| 398 | - 0 => $primary_model_query_params[0], | |
| 399 | - 'limit' => 1, | |
| 400 | - ); | |
| 401 | -        if ($model instanceof EEM_Soft_Delete_Base) { | |
| 402 | - $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included( | |
| 403 | - $primary_model_query_params | |
| 404 | - ); | |
| 405 | - } | |
| 406 | - $restricted_query_params = $primary_model_query_params; | |
| 407 | - $restricted_query_params['caps'] = $context; | |
| 408 | - $restricted_query_params['limit'] = 1; | |
| 409 | -        $this->setDebugInfo('main model query params', $restricted_query_params); | |
| 410 | -        $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context)); | |
| 411 | - $primary_model_rows = $model->get_all_wpdb_results($restricted_query_params); | |
| 412 | - $primary_model_row = null; | |
| 413 | -        if (is_array($primary_model_rows)) { | |
| 414 | - $primary_model_row = reset($primary_model_rows); | |
| 415 | - } | |
| 416 | - if (! ( | |
| 417 | - Capabilities::currentUserHasPartialAccessTo($related_model, $context) | |
| 418 | - && $primary_model_row | |
| 419 | - ) | |
| 420 | -        ) { | |
| 421 | -            if ($relation instanceof EE_Belongs_To_Relation) { | |
| 422 | - $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name()); | |
| 423 | -            } else { | |
| 424 | - $related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower( | |
| 425 | - $related_model->get_this_model_name() | |
| 426 | - ); | |
| 427 | - } | |
| 428 | - throw new RestException( | |
| 429 | -                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural), | |
| 430 | - sprintf( | |
| 431 | - __( | |
| 432 | - 'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s', | |
| 433 | - 'event_espresso' | |
| 434 | - ), | |
| 435 | - $related_model_name_maybe_plural, | |
| 436 | - $relation->get_this_model()->get_this_model_name(), | |
| 437 | - implode( | |
| 438 | - ',', | |
| 439 | - array_keys( | |
| 440 | - Capabilities::getMissingPermissions($related_model, $context) | |
| 441 | - ) | |
| 442 | - ) | |
| 443 | - ), | |
| 444 | -                array('status' => 403) | |
| 445 | - ); | |
| 446 | - } | |
| 447 | - | |
| 448 | - $this->checkPassword( | |
| 449 | - $model, | |
| 450 | - $primary_model_row, | |
| 451 | - $restricted_query_params, | |
| 452 | - $request | |
| 453 | - ); | |
| 454 | - $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params()); | |
| 455 | -        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) { | |
| 456 | - $query_params[0][ $relation->get_this_model()->get_this_model_name() | |
| 457 | - . '.' | |
| 458 | - . $where_condition_key ] = $where_condition_value; | |
| 459 | - } | |
| 460 | - $query_params['default_where_conditions'] = 'none'; | |
| 461 | - $query_params['caps'] = $context; | |
| 462 | -        if (! $request->get_header('no_rest_headers')) { | |
| 463 | - $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params); | |
| 464 | - } | |
| 465 | - /** @type array $results */ | |
| 466 | - $results = $relation->get_other_model()->get_all_wpdb_results($query_params); | |
| 467 | - $nice_results = array(); | |
| 468 | -        foreach ($results as $result) { | |
| 469 | - $nice_result = $this->createEntityFromWpdbResult( | |
| 470 | - $relation->get_other_model(), | |
| 471 | - $result, | |
| 472 | - $request | |
| 473 | - ); | |
| 474 | -            if ($relation instanceof \EE_HABTM_Relation) { | |
| 475 | - // put the unusual stuff (properties from the HABTM relation) first, and make sure | |
| 476 | - // if there are conflicts we prefer the properties from the main model | |
| 477 | - $join_model_result = $this->createEntityFromWpdbResult( | |
| 478 | - $relation->get_join_model(), | |
| 479 | - $result, | |
| 480 | - $request | |
| 481 | - ); | |
| 482 | - $joined_result = array_merge($nice_result, $join_model_result); | |
| 483 | - // but keep the meta stuff from the main model | |
| 484 | -                if (isset($nice_result['meta'])) { | |
| 485 | - $joined_result['meta'] = $nice_result['meta']; | |
| 486 | - } | |
| 487 | - $nice_result = $joined_result; | |
| 488 | - } | |
| 489 | - $nice_results[] = $nice_result; | |
| 490 | - } | |
| 491 | -        if ($relation instanceof EE_Belongs_To_Relation) { | |
| 492 | - return array_shift($nice_results); | |
| 493 | -        } else { | |
| 494 | - return $nice_results; | |
| 495 | - } | |
| 496 | - } | |
| 497 | - | |
| 498 | - | |
| 499 | - /** | |
| 500 | - * Gets the collection for given relation object | |
| 501 | - * The same as Read::get_entities_from_model(), except if the relation | |
| 502 | - * is a HABTM relation, in which case it merges any non-foreign-key fields from | |
| 503 | - * the join-model-object into the results | |
| 504 | - * | |
| 505 | - * @param string $id the ID of the thing we are fetching related stuff from | |
| 506 | - * @param \EE_Model_Relation_Base $relation | |
| 507 | - * @param WP_REST_Request $request | |
| 508 | - * @return array | |
| 509 | - * @throws EE_Error | |
| 510 | - */ | |
| 511 | - public function getEntitiesFromRelation($id, $relation, $request) | |
| 512 | -    { | |
| 513 | -        if (! $relation->get_this_model()->has_primary_key_field()) { | |
| 514 | - throw new EE_Error( | |
| 515 | - sprintf( | |
| 516 | - __( | |
| 517 | - // @codingStandardsIgnoreStart | |
| 518 | - 'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s', | |
| 519 | - // @codingStandardsIgnoreEnd | |
| 520 | - 'event_espresso' | |
| 521 | - ), | |
| 522 | - $relation->get_this_model()->get_this_model_name() | |
| 523 | - ) | |
| 524 | - ); | |
| 525 | - } | |
| 526 | - // can we edit that main item? | |
| 527 | - // if not, show nothing but an error | |
| 528 | - // otherwise, please proceed | |
| 529 | - return $this->getEntitiesFromRelationUsingModelQueryParams( | |
| 530 | - array( | |
| 531 | - array( | |
| 532 | - $relation->get_this_model()->primary_key_name() => $id, | |
| 533 | - ), | |
| 534 | - ), | |
| 535 | - $relation, | |
| 536 | - $request | |
| 537 | - ); | |
| 538 | - } | |
| 539 | - | |
| 540 | - | |
| 541 | - /** | |
| 542 | - * Sets the headers that are based on the model and query params, | |
| 543 | - * like the total records. This should only be called on the original request | |
| 544 | - * from the client, not on subsequent internal | |
| 545 | - * | |
| 546 | - * @param EEM_Base $model | |
| 547 | - * @param array $query_params | |
| 548 | - * @return void | |
| 549 | - */ | |
| 550 | - protected function setHeadersFromQueryParams($model, $query_params) | |
| 551 | -    { | |
| 552 | -        $this->setDebugInfo('model query params', $query_params); | |
| 553 | - $this->setDebugInfo( | |
| 554 | - 'missing caps', | |
| 555 | - Capabilities::getMissingPermissionsString($model, $query_params['caps']) | |
| 556 | - ); | |
| 557 | - // normally the limit to a 2-part array, where the 2nd item is the limit | |
| 558 | -        if (! isset($query_params['limit'])) { | |
| 559 | - $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit(); | |
| 560 | - } | |
| 561 | -        if (is_array($query_params['limit'])) { | |
| 562 | - $limit_parts = $query_params['limit']; | |
| 563 | -        } else { | |
| 564 | -            $limit_parts = explode(',', $query_params['limit']); | |
| 565 | -            if (count($limit_parts) == 1) { | |
| 566 | - $limit_parts = array(0, $limit_parts[0]); | |
| 567 | - } | |
| 568 | - } | |
| 569 | - // remove the group by and having parts of the query, as those will | |
| 570 | - // make the sql query return an array of values, instead of just a single value | |
| 571 | - unset($query_params['group_by'], $query_params['having'], $query_params['limit']); | |
| 572 | - $count = $model->count($query_params, null, true); | |
| 573 | - $pages = $count / $limit_parts[1]; | |
| 574 | -        $this->setResponseHeader('Total', $count, false); | |
| 575 | -        $this->setResponseHeader('PageSize', $limit_parts[1], false); | |
| 576 | -        $this->setResponseHeader('TotalPages', ceil($pages), false); | |
| 577 | - } | |
| 578 | - | |
| 579 | - | |
| 580 | - /** | |
| 581 | - * Changes database results into REST API entities | |
| 582 | - * | |
| 583 | - * @param EEM_Base $model | |
| 584 | - * @param array $db_row like results from $wpdb->get_results() | |
| 585 | - * @param WP_REST_Request $rest_request | |
| 586 | - * @param string $deprecated no longer used | |
| 587 | - * @return array ready for being converted into json for sending to client | |
| 588 | - * @throws EE_Error | |
| 589 | - * @throws RestException | |
| 590 | - * @throws InvalidDataTypeException | |
| 591 | - * @throws InvalidInterfaceException | |
| 592 | - * @throws InvalidArgumentException | |
| 593 | - * @throws ReflectionException | |
| 594 | - */ | |
| 595 | - public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null) | |
| 596 | -    { | |
| 597 | -        if (! $rest_request instanceof WP_REST_Request) { | |
| 598 | - // ok so this was called in the old style, where the 3rd arg was | |
| 599 | - // $include, and the 4th arg was $context | |
| 600 | - // now setup the request just to avoid fatal errors, although we won't be able | |
| 601 | - // to truly make use of it because it's kinda devoid of info | |
| 602 | - $rest_request = new WP_REST_Request(); | |
| 603 | -            $rest_request->set_param('include', $rest_request); | |
| 604 | -            $rest_request->set_param('caps', $deprecated); | |
| 605 | - } | |
| 606 | -        if ($rest_request->get_param('caps') == null) { | |
| 607 | -            $rest_request->set_param('caps', EEM_Base::caps_read); | |
| 608 | - } | |
| 609 | - $current_user_full_access_to_entity = $model->currentUserCan( | |
| 610 | - EEM_Base::caps_read_admin, | |
| 611 | - $model->deduce_fields_n_values_from_cols_n_values($db_row) | |
| 612 | - ); | |
| 613 | - $entity_array = $this->createBareEntityFromWpdbResults($model, $db_row); | |
| 614 | - $entity_array = $this->addExtraFields($model, $db_row, $entity_array); | |
| 615 | - $entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array); | |
| 616 | - // when it's a regular read request for a model with a password and the password wasn't provided | |
| 617 | - // remove the password protected fields | |
| 618 | - $has_protected_fields = false; | |
| 619 | -        try { | |
| 620 | - $this->checkPassword( | |
| 621 | - $model, | |
| 622 | - $db_row, | |
| 623 | - array( | |
| 624 | - 0 => array( | |
| 625 | - $model->primary_key_name() => $db_row[ $model->get_primary_key_field()->get_qualified_column() ] | |
| 626 | - ) | |
| 627 | - ), | |
| 628 | - $rest_request | |
| 629 | - ); | |
| 630 | -        } catch (RestPasswordRequiredException $e) { | |
| 631 | -            if ($model->hasPassword()) { | |
| 632 | - // just remove protected fields | |
| 633 | - $has_protected_fields = true; | |
| 634 | - $entity_array = Capabilities::filterOutPasswordProtectedFields( | |
| 635 | - $entity_array, | |
| 636 | - $model, | |
| 637 | - $this->getModelVersionInfo() | |
| 638 | - ); | |
| 639 | -            } else { | |
| 640 | - // that's a problem. None of this should be accessible if no password was provided | |
| 641 | - throw $e; | |
| 642 | - } | |
| 643 | - } | |
| 644 | - | |
| 645 | - $entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request, $has_protected_fields); | |
| 646 | - $entity_array = apply_filters( | |
| 647 | - 'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models', | |
| 648 | - $entity_array, | |
| 649 | - $model, | |
| 650 | -            $rest_request->get_param('caps'), | |
| 651 | - $rest_request, | |
| 652 | - $this | |
| 653 | - ); | |
| 654 | - // add an empty protected property for now. If it's still around after we remove everything the request didn't | |
| 655 | - // want, we'll populate it then. k? | |
| 656 | - $entity_array['_protected'] = array(); | |
| 657 | - // remove any properties the request didn't want. This way _protected won't bother mentioning them | |
| 658 | - $entity_array = $this->includeOnlyRequestedProperties($model, $rest_request, $entity_array); | |
| 659 | - $entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row, $has_protected_fields); | |
| 660 | - // if they still wanted the _protected property, add it. | |
| 661 | -        if (isset($entity_array['_protected'])) { | |
| 662 | - $entity_array = $this->addProtectedProperty($model, $entity_array, $has_protected_fields); | |
| 663 | - } | |
| 664 | - $entity_array = apply_filters( | |
| 665 | - 'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal', | |
| 666 | - $entity_array, | |
| 667 | - $model, | |
| 668 | -            $rest_request->get_param('caps'), | |
| 669 | - $rest_request, | |
| 670 | - $this | |
| 671 | - ); | |
| 672 | -        if (! $current_user_full_access_to_entity) { | |
| 673 | - $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields( | |
| 674 | - $entity_array, | |
| 675 | - $model, | |
| 676 | -                $rest_request->get_param('caps'), | |
| 677 | - $this->getModelVersionInfo() | |
| 678 | - ); | |
| 679 | -        } else { | |
| 680 | - $result_without_inaccessible_fields = $entity_array; | |
| 681 | - } | |
| 682 | - $this->setDebugInfo( | |
| 683 | - 'inaccessible fields', | |
| 684 | - array_keys(array_diff_key((array) $entity_array, (array) $result_without_inaccessible_fields)) | |
| 685 | - ); | |
| 686 | - return apply_filters( | |
| 687 | - 'FHEE__Read__create_entity_from_wpdb_results__entity_return', | |
| 688 | - $result_without_inaccessible_fields, | |
| 689 | - $model, | |
| 690 | -            $rest_request->get_param('caps') | |
| 691 | - ); | |
| 692 | - } | |
| 693 | - | |
| 694 | - /** | |
| 695 | - * Returns an array describing which fields can be protected, and which actually were removed this request | |
| 696 | - * @since 4.9.74.p | |
| 697 | - * @param $model | |
| 698 | - * @param $results_so_far | |
| 699 | - * @param $protected | |
| 700 | - * @return array results | |
| 701 | - */ | |
| 702 | - protected function addProtectedProperty(EEM_Base $model, $results_so_far, $protected) | |
| 703 | -    { | |
| 704 | -        if (! $model->hasPassword() || ! $protected) { | |
| 705 | - return $results_so_far; | |
| 706 | - } | |
| 707 | - $password_field = $model->getPasswordField(); | |
| 708 | - $all_protected = array_merge( | |
| 709 | - array($password_field->get_name()), | |
| 710 | - $password_field->protectedFields() | |
| 711 | - ); | |
| 712 | - $fields_included = array_keys($results_so_far); | |
| 713 | - $fields_included = array_intersect( | |
| 714 | - $all_protected, | |
| 715 | - $fields_included | |
| 716 | - ); | |
| 717 | -        foreach ($fields_included as $field_name) { | |
| 718 | - $results_so_far['_protected'][] = $field_name ; | |
| 719 | - } | |
| 720 | - return $results_so_far; | |
| 721 | - } | |
| 722 | - | |
| 723 | - /** | |
| 724 | - * Creates a REST entity array (JSON object we're going to return in the response, but | |
| 725 | - * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry), | |
| 726 | - * from $wpdb->get_row( $sql, ARRAY_A) | |
| 727 | - * | |
| 728 | - * @param EEM_Base $model | |
| 729 | - * @param array $db_row | |
| 730 | - * @return array entity mostly ready for converting to JSON and sending in the response | |
| 731 | - */ | |
| 732 | - protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row) | |
| 733 | -    { | |
| 734 | - $result = $model->deduce_fields_n_values_from_cols_n_values($db_row); | |
| 735 | - $result = array_intersect_key( | |
| 736 | - $result, | |
| 737 | - $this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) | |
| 738 | - ); | |
| 739 | - // if this is a CPT, we need to set the global $post to it, | |
| 740 | - // otherwise shortcodes etc won't work properly while rendering it | |
| 741 | -        if ($model instanceof \EEM_CPT_Base) { | |
| 742 | - $do_chevy_shuffle = true; | |
| 743 | -        } else { | |
| 744 | - $do_chevy_shuffle = false; | |
| 745 | - } | |
| 746 | -        if ($do_chevy_shuffle) { | |
| 747 | - global $post; | |
| 748 | - $old_post = $post; | |
| 749 | - $post = get_post($result[ $model->primary_key_name() ]); | |
| 750 | -            if (! $post instanceof \WP_Post) { | |
| 751 | - // well that's weird, because $result is what we JUST fetched from the database | |
| 752 | - throw new RestException( | |
| 753 | - 'error_fetching_post_from_database_results', | |
| 754 | - esc_html__( | |
| 755 | - 'An item was retrieved from the database but it\'s not a WP_Post like it should be.', | |
| 756 | - 'event_espresso' | |
| 757 | - ) | |
| 758 | - ); | |
| 759 | - } | |
| 760 | - $model_object_classname = 'EE_' . $model->get_this_model_name(); | |
| 761 | -            $post->{$model_object_classname} = \EE_Registry::instance()->load_class( | |
| 762 | - $model_object_classname, | |
| 763 | - $result, | |
| 764 | - false, | |
| 765 | - false | |
| 766 | - ); | |
| 767 | - } | |
| 768 | -        foreach ($result as $field_name => $field_value) { | |
| 769 | - $field_obj = $model->field_settings_for($field_name); | |
| 770 | -            if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) { | |
| 771 | - unset($result[ $field_name ]); | |
| 772 | - } elseif ($this->isSubclassOfOne( | |
| 773 | - $field_obj, | |
| 774 | - $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat() | |
| 775 | - ) | |
| 776 | -            ) { | |
| 777 | - $result[ $field_name ] = array( | |
| 778 | - 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | |
| 779 | - 'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | |
| 780 | - ); | |
| 781 | - } elseif ($this->isSubclassOfOne( | |
| 782 | - $field_obj, | |
| 783 | - $this->getModelVersionInfo()->fieldsThatHavePrettyFormat() | |
| 784 | - ) | |
| 785 | -            ) { | |
| 786 | - $result[ $field_name ] = array( | |
| 787 | - 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | |
| 788 | - 'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | |
| 789 | - ); | |
| 790 | -            } elseif ($field_obj instanceof \EE_Datetime_Field) { | |
| 791 | - $field_value = $field_obj->prepare_for_set_from_db($field_value); | |
| 792 | - // if the value is null, but we're not supposed to permit null, then set to the field's default | |
| 793 | -                if (is_null($field_value)) { | |
| 794 | - $field_value = $field_obj->getDefaultDateTimeObj(); | |
| 795 | - } | |
| 796 | -                if (is_null($field_value)) { | |
| 797 | - $gmt_date = $local_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 798 | - $field_obj, | |
| 799 | - $field_value, | |
| 800 | - $this->getModelVersionInfo()->requestedVersion() | |
| 801 | - ); | |
| 802 | -                } else { | |
| 803 | - $timezone = $field_value->getTimezone(); | |
| 804 | -                    EEH_DTT_Helper::setTimezone($field_value, new DateTimeZone('UTC')); | |
| 805 | - $gmt_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 806 | - $field_obj, | |
| 807 | - $field_value, | |
| 808 | - $this->getModelVersionInfo()->requestedVersion() | |
| 809 | - ); | |
| 810 | - EEH_DTT_Helper::setTimezone($field_value, $timezone); | |
| 811 | - $local_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 812 | - $field_obj, | |
| 813 | - $field_value, | |
| 814 | - $this->getModelVersionInfo()->requestedVersion() | |
| 815 | - ); | |
| 816 | - } | |
| 817 | - $result[ $field_name . '_gmt' ] = $gmt_date; | |
| 818 | - $result[ $field_name ] = $local_date; | |
| 819 | -            } else { | |
| 820 | - $result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value); | |
| 821 | - } | |
| 822 | - } | |
| 823 | -        if ($do_chevy_shuffle) { | |
| 824 | - $post = $old_post; | |
| 825 | - } | |
| 826 | - return $result; | |
| 827 | - } | |
| 828 | - | |
| 829 | - | |
| 830 | - /** | |
| 831 | - * Takes a value all the way from the DB representation, to the model object's representation, to the | |
| 832 | - * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB | |
| 833 | - * representation using $field_obj->prepare_for_set_from_db()) | |
| 834 | - * | |
| 835 | - * @param EE_Model_Field_Base $field_obj | |
| 836 | - * @param mixed $value as it's stored on a model object | |
| 837 | - * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj' | |
| 838 | - * @return mixed | |
| 839 | - * @throws ObjectDetectedException if $value contains a PHP object | |
| 840 | - */ | |
| 841 | - protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal') | |
| 842 | -    { | |
| 843 | - $value = $field_obj->prepare_for_set_from_db($value); | |
| 844 | -        switch ($format) { | |
| 845 | - case 'pretty': | |
| 846 | - $value = $field_obj->prepare_for_pretty_echoing($value); | |
| 847 | - break; | |
| 848 | - case 'normal': | |
| 849 | - default: | |
| 850 | - $value = $field_obj->prepare_for_get($value); | |
| 851 | - break; | |
| 852 | - } | |
| 853 | - return ModelDataTranslator::prepareFieldValuesForJson( | |
| 854 | - $field_obj, | |
| 855 | - $value, | |
| 856 | - $this->getModelVersionInfo()->requestedVersion() | |
| 857 | - ); | |
| 858 | - } | |
| 859 | - | |
| 860 | - | |
| 861 | - /** | |
| 862 | - * Adds a few extra fields to the entity response | |
| 863 | - * | |
| 864 | - * @param EEM_Base $model | |
| 865 | - * @param array $db_row | |
| 866 | - * @param array $entity_array | |
| 867 | - * @return array modified entity | |
| 868 | - */ | |
| 869 | - protected function addExtraFields(EEM_Base $model, $db_row, $entity_array) | |
| 870 | -    { | |
| 871 | -        if ($model instanceof EEM_CPT_Base) { | |
| 872 | - $entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]); | |
| 873 | - } | |
| 874 | - return $entity_array; | |
| 875 | - } | |
| 876 | - | |
| 877 | - | |
| 878 | - /** | |
| 879 | - * Gets links we want to add to the response | |
| 880 | - * | |
| 881 | - * @global \WP_REST_Server $wp_rest_server | |
| 882 | - * @param EEM_Base $model | |
| 883 | - * @param array $db_row | |
| 884 | - * @param array $entity_array | |
| 885 | - * @return array the _links item in the entity | |
| 886 | - */ | |
| 887 | - protected function getEntityLinks($model, $db_row, $entity_array) | |
| 888 | -    { | |
| 889 | - // add basic links | |
| 890 | - $links = array(); | |
| 891 | -        if ($model->has_primary_key_field()) { | |
| 892 | - $links['self'] = array( | |
| 893 | - array( | |
| 894 | - 'href' => $this->getVersionedLinkTo( | |
| 895 | - EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 896 | - . '/' | |
| 897 | - . $entity_array[ $model->primary_key_name() ] | |
| 898 | - ), | |
| 899 | - ), | |
| 900 | - ); | |
| 901 | - } | |
| 902 | - $links['collection'] = array( | |
| 903 | - array( | |
| 904 | - 'href' => $this->getVersionedLinkTo( | |
| 905 | - EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 906 | - ), | |
| 907 | - ), | |
| 908 | - ); | |
| 909 | - // add links to related models | |
| 910 | -        if ($model->has_primary_key_field()) { | |
| 911 | -            foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) { | |
| 912 | - $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj); | |
| 913 | - $links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array( | |
| 914 | - array( | |
| 915 | - 'href' => $this->getVersionedLinkTo( | |
| 916 | - EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 917 | - . '/' | |
| 918 | - . $entity_array[ $model->primary_key_name() ] | |
| 919 | - . '/' | |
| 920 | - . $related_model_part | |
| 921 | - ), | |
| 922 | - 'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false, | |
| 923 | - ), | |
| 924 | - ); | |
| 925 | - } | |
| 926 | - } | |
| 927 | - return $links; | |
| 928 | - } | |
| 929 | - | |
| 930 | - | |
| 931 | - /** | |
| 932 | - * Adds the included models indicated in the request to the entity provided | |
| 933 | - * | |
| 934 | - * @param EEM_Base $model | |
| 935 | - * @param WP_REST_Request $rest_request | |
| 936 | - * @param array $entity_array | |
| 937 | - * @param array $db_row | |
| 938 | - * @param boolean $included_items_protected if the original item is password protected, don't include any related models. | |
| 939 | - * @return array the modified entity | |
| 940 | - * @throws RestException | |
| 941 | - */ | |
| 942 | - protected function includeRequestedModels( | |
| 943 | - EEM_Base $model, | |
| 944 | - WP_REST_Request $rest_request, | |
| 945 | - $entity_array, | |
| 946 | - $db_row = array(), | |
| 947 | - $included_items_protected = false | |
| 948 | -    ) { | |
| 949 | - // if $db_row not included, hope the entity array has what we need | |
| 950 | -        if (! $db_row) { | |
| 951 | - $db_row = $entity_array; | |
| 952 | - } | |
| 953 | - $relation_settings = $this->getModelVersionInfo()->relationSettings($model); | |
| 954 | -        foreach ($relation_settings as $relation_name => $relation_obj) { | |
| 955 | - $related_fields_to_include = $this->explodeAndGetItemsPrefixedWith( | |
| 956 | -                $rest_request->get_param('include'), | |
| 957 | - $relation_name | |
| 958 | - ); | |
| 959 | - $related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith( | |
| 960 | -                $rest_request->get_param('calculate'), | |
| 961 | - $relation_name | |
| 962 | - ); | |
| 963 | - // did they specify they wanted to include a related model, or | |
| 964 | - // specific fields from a related model? | |
| 965 | - // or did they specify to calculate a field from a related model? | |
| 966 | -            if ($related_fields_to_include || $related_fields_to_calculate) { | |
| 967 | - // if so, we should include at least some part of the related model | |
| 968 | - $pretend_related_request = new WP_REST_Request(); | |
| 969 | - $pretend_related_request->set_query_params( | |
| 970 | - array( | |
| 971 | -                        'caps'      => $rest_request->get_param('caps'), | |
| 972 | - 'include' => $related_fields_to_include, | |
| 973 | - 'calculate' => $related_fields_to_calculate, | |
| 974 | -                        'password' => $rest_request->get_param('password') | |
| 975 | - ) | |
| 976 | - ); | |
| 977 | -                $pretend_related_request->add_header('no_rest_headers', true); | |
| 978 | - $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID( | |
| 979 | - $model->get_index_primary_key_string( | |
| 980 | - $model->deduce_fields_n_values_from_cols_n_values($db_row) | |
| 981 | - ) | |
| 982 | - ); | |
| 983 | -                if (! $included_items_protected) { | |
| 984 | - $related_results = $this->getEntitiesFromRelationUsingModelQueryParams( | |
| 985 | - $primary_model_query_params, | |
| 986 | - $relation_obj, | |
| 987 | - $pretend_related_request | |
| 988 | - ); | |
| 989 | -                } else { | |
| 990 | - // they're protected, hide them. | |
| 991 | - $related_results = $relation_obj instanceof EE_Belongs_To_Relation ? null : array(); | |
| 992 | - $entity_array['_protected'][] = Read::getRelatedEntityName($relation_name, $relation_obj); | |
| 993 | - } | |
| 994 | -                if ($related_results instanceof WP_Error) { | |
| 995 | - $related_results = null; | |
| 996 | - } | |
| 997 | - $entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results; | |
| 998 | - } | |
| 999 | - } | |
| 1000 | - return $entity_array; | |
| 1001 | - } | |
| 1002 | - | |
| 1003 | - /** | |
| 1004 | - * If the user has requested only specific properties (including meta properties like _links or _protected) | |
| 1005 | - * remove everything else. | |
| 1006 | - * @since 4.9.74.p | |
| 1007 | - * @param EEM_Base $model | |
| 1008 | - * @param WP_REST_Request $rest_request | |
| 1009 | - * @param $entity_array | |
| 1010 | - * @return array | |
| 1011 | - * @throws EE_Error | |
| 1012 | - */ | |
| 1013 | - protected function includeOnlyRequestedProperties( | |
| 1014 | - EEM_Base $model, | |
| 1015 | - WP_REST_Request $rest_request, | |
| 1016 | - $entity_array | |
| 1017 | -    ) { | |
| 1018 | - | |
| 1019 | -        $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), ''); | |
| 1020 | - $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model); | |
| 1021 | - // if they passed in * or didn't specify any includes, return everything | |
| 1022 | -        if (! in_array('*', $includes_for_this_model) | |
| 1023 | - && ! empty($includes_for_this_model) | |
| 1024 | -        ) { | |
| 1025 | -            if ($model->has_primary_key_field()) { | |
| 1026 | - // always include the primary key. ya just gotta know that at least | |
| 1027 | - $includes_for_this_model[] = $model->primary_key_name(); | |
| 1028 | - } | |
| 1029 | -            if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) { | |
| 1030 | - $includes_for_this_model[] = '_calculated_fields'; | |
| 1031 | - } | |
| 1032 | - $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model)); | |
| 1033 | - } | |
| 1034 | - return $entity_array; | |
| 1035 | - } | |
| 1036 | - | |
| 1037 | - | |
| 1038 | - /** | |
| 1039 | - * Returns a new array with all the names of models removed. Eg | |
| 1040 | - * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' ) | |
| 1041 | - * | |
| 1042 | - * @param array $arr | |
| 1043 | - * @return array | |
| 1044 | - */ | |
| 1045 | - private function removeModelNamesFromArray($arr) | |
| 1046 | -    { | |
| 1047 | - return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models)); | |
| 1048 | - } | |
| 1049 | - | |
| 1050 | - | |
| 1051 | - /** | |
| 1052 | - * Gets the calculated fields for the response | |
| 1053 | - * | |
| 1054 | - * @param EEM_Base $model | |
| 1055 | - * @param array $wpdb_row | |
| 1056 | - * @param WP_REST_Request $rest_request | |
| 1057 | - * @param boolean $row_is_protected whether this row is password protected or not | |
| 1058 | - * @return \stdClass the _calculations item in the entity | |
| 1059 | - * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we | |
| 1060 | - * did, let's know about it ASAP, so let the exception bubble up) | |
| 1061 | - */ | |
| 1062 | - protected function getEntityCalculations($model, $wpdb_row, $rest_request, $row_is_protected = false) | |
| 1063 | -    { | |
| 1064 | - $calculated_fields = $this->explodeAndGetItemsPrefixedWith( | |
| 1065 | -            $rest_request->get_param('calculate'), | |
| 1066 | - '' | |
| 1067 | - ); | |
| 1068 | - // note: setting calculate=* doesn't do anything | |
| 1069 | - $calculated_fields_to_return = new \stdClass(); | |
| 1070 | - $protected_fields = array(); | |
| 1071 | -        foreach ($calculated_fields as $field_to_calculate) { | |
| 1072 | -            try { | |
| 1073 | - // it's password protected, so they shouldn't be able to read this. Remove the value | |
| 1074 | - $schema = $this->fields_calculator->getJsonSchemaForModel($model); | |
| 1075 | - if ($row_is_protected | |
| 1076 | - && isset($schema['properties'][ $field_to_calculate ]['protected']) | |
| 1077 | -                    && $schema['properties'][ $field_to_calculate ]['protected']) { | |
| 1078 | - $calculated_value = null; | |
| 1079 | - $protected_fields[] = $field_to_calculate; | |
| 1080 | -                    if ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1081 | -                        switch ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1082 | - case 'boolean': | |
| 1083 | - $calculated_value = false; | |
| 1084 | - break; | |
| 1085 | - case 'integer': | |
| 1086 | - $calculated_value = 0; | |
| 1087 | - break; | |
| 1088 | - case 'string': | |
| 1089 | - $calculated_value = ''; | |
| 1090 | - break; | |
| 1091 | - case 'array': | |
| 1092 | - $calculated_value = array(); | |
| 1093 | - break; | |
| 1094 | - case 'object': | |
| 1095 | - $calculated_value = new stdClass(); | |
| 1096 | - break; | |
| 1097 | - } | |
| 1098 | - } | |
| 1099 | -                } else { | |
| 1100 | - $calculated_value = ModelDataTranslator::prepareFieldValueForJson( | |
| 1101 | - null, | |
| 1102 | - $this->fields_calculator->retrieveCalculatedFieldValue( | |
| 1103 | - $model, | |
| 1104 | - $field_to_calculate, | |
| 1105 | - $wpdb_row, | |
| 1106 | - $rest_request, | |
| 1107 | - $this | |
| 1108 | - ), | |
| 1109 | - $this->getModelVersionInfo()->requestedVersion() | |
| 1110 | - ); | |
| 1111 | - } | |
| 1112 | -                $calculated_fields_to_return->{$field_to_calculate} = $calculated_value; | |
| 1113 | -            } catch (RestException $e) { | |
| 1114 | - // if we don't have permission to read it, just leave it out. but let devs know about the problem | |
| 1115 | - $this->setResponseHeader( | |
| 1116 | - 'Notices-Field-Calculation-Errors[' | |
| 1117 | - . $e->getStringCode() | |
| 1118 | - . '][' | |
| 1119 | - . $model->get_this_model_name() | |
| 1120 | - . '][' | |
| 1121 | - . $field_to_calculate | |
| 1122 | - . ']', | |
| 1123 | - $e->getMessage(), | |
| 1124 | - true | |
| 1125 | - ); | |
| 1126 | - } | |
| 1127 | - } | |
| 1128 | - $calculated_fields_to_return->_protected = $protected_fields; | |
| 1129 | - return $calculated_fields_to_return; | |
| 1130 | - } | |
| 1131 | - | |
| 1132 | - | |
| 1133 | - /** | |
| 1134 | - * Gets the full URL to the resource, taking the requested version into account | |
| 1135 | - * | |
| 1136 | - * @param string $link_part_after_version_and_slash eg "events/10/datetimes" | |
| 1137 | - * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes" | |
| 1138 | - */ | |
| 1139 | - public function getVersionedLinkTo($link_part_after_version_and_slash) | |
| 1140 | -    { | |
| 1141 | - return rest_url( | |
| 1142 | - EED_Core_Rest_Api::get_versioned_route_to( | |
| 1143 | - $link_part_after_version_and_slash, | |
| 1144 | - $this->getModelVersionInfo()->requestedVersion() | |
| 1145 | - ) | |
| 1146 | - ); | |
| 1147 | - } | |
| 1148 | - | |
| 1149 | - | |
| 1150 | - /** | |
| 1151 | - * Gets the correct lowercase name for the relation in the API according | |
| 1152 | - * to the relation's type | |
| 1153 | - * | |
| 1154 | - * @param string $relation_name | |
| 1155 | - * @param \EE_Model_Relation_Base $relation_obj | |
| 1156 | - * @return string | |
| 1157 | - */ | |
| 1158 | - public static function getRelatedEntityName($relation_name, $relation_obj) | |
| 1159 | -    { | |
| 1160 | -        if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 1161 | - return strtolower($relation_name); | |
| 1162 | -        } else { | |
| 1163 | - return EEH_Inflector::pluralize_and_lower($relation_name); | |
| 1164 | - } | |
| 1165 | - } | |
| 1166 | - | |
| 1167 | - | |
| 1168 | - /** | |
| 1169 | - * Gets the one model object with the specified id for the specified model | |
| 1170 | - * | |
| 1171 | - * @param EEM_Base $model | |
| 1172 | - * @param WP_REST_Request $request | |
| 1173 | - * @return array | |
| 1174 | - */ | |
| 1175 | - public function getEntityFromModel($model, $request) | |
| 1176 | -    { | |
| 1177 | -        $context = $this->validateContext($request->get_param('caps')); | |
| 1178 | - return $this->getOneOrReportPermissionError($model, $request, $context); | |
| 1179 | - } | |
| 1180 | - | |
| 1181 | - | |
| 1182 | - /** | |
| 1183 | - * If a context is provided which isn't valid, maybe it was added in a future | |
| 1184 | - * version so just treat it as a default read | |
| 1185 | - * | |
| 1186 | - * @param string $context | |
| 1187 | - * @return string array key of EEM_Base::cap_contexts_to_cap_action_map() | |
| 1188 | - */ | |
| 1189 | - public function validateContext($context) | |
| 1190 | -    { | |
| 1191 | -        if (! $context) { | |
| 1192 | - $context = EEM_Base::caps_read; | |
| 1193 | - } | |
| 1194 | - $valid_contexts = EEM_Base::valid_cap_contexts(); | |
| 1195 | -        if (in_array($context, $valid_contexts)) { | |
| 1196 | - return $context; | |
| 1197 | -        } else { | |
| 1198 | - return EEM_Base::caps_read; | |
| 1199 | - } | |
| 1200 | - } | |
| 1201 | - | |
| 1202 | - | |
| 1203 | - /** | |
| 1204 | - * Verifies the passed in value is an allowable default where conditions value. | |
| 1205 | - * | |
| 1206 | - * @param $default_query_params | |
| 1207 | - * @return string | |
| 1208 | - */ | |
| 1209 | - public function validateDefaultQueryParams($default_query_params) | |
| 1210 | -    { | |
| 1211 | - $valid_default_where_conditions_for_api_calls = array( | |
| 1212 | - EEM_Base::default_where_conditions_all, | |
| 1213 | - EEM_Base::default_where_conditions_minimum_all, | |
| 1214 | - EEM_Base::default_where_conditions_minimum_others, | |
| 1215 | - ); | |
| 1216 | -        if (! $default_query_params) { | |
| 1217 | - $default_query_params = EEM_Base::default_where_conditions_all; | |
| 1218 | - } | |
| 1219 | - if (in_array( | |
| 1220 | - $default_query_params, | |
| 1221 | - $valid_default_where_conditions_for_api_calls, | |
| 1222 | - true | |
| 1223 | -        )) { | |
| 1224 | - return $default_query_params; | |
| 1225 | -        } else { | |
| 1226 | - return EEM_Base::default_where_conditions_all; | |
| 1227 | - } | |
| 1228 | - } | |
| 1229 | - | |
| 1230 | - | |
| 1231 | - /** | |
| 1232 | - * Translates API filter get parameter into model query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions. | |
| 1233 | - * Note: right now the query parameter keys for fields (and related fields) | |
| 1234 | - * can be left as-is, but it's quite possible this will change someday. | |
| 1235 | - * Also, this method's contents might be candidate for moving to Model_Data_Translator | |
| 1236 | - * | |
| 1237 | - * @param EEM_Base $model | |
| 1238 | - * @param array $query_parameters from $_GET parameter @see Read:handle_request_get_all | |
| 1239 | - * @return array model query params (@see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions) | |
| 1240 | - * or FALSE to indicate that absolutely no results should be returned | |
| 1241 | - * @throws EE_Error | |
| 1242 | - * @throws RestException | |
| 1243 | - */ | |
| 1244 | - public function createModelQueryParams($model, $query_params) | |
| 1245 | -    { | |
| 1246 | - $model_query_params = array(); | |
| 1247 | -        if (isset($query_params['where'])) { | |
| 1248 | - $model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 1249 | - $query_params['where'], | |
| 1250 | - $model, | |
| 1251 | - $this->getModelVersionInfo()->requestedVersion() | |
| 1252 | - ); | |
| 1253 | - } | |
| 1254 | -        if (isset($query_params['order_by'])) { | |
| 1255 | - $order_by = $query_params['order_by']; | |
| 1256 | -        } elseif (isset($query_params['orderby'])) { | |
| 1257 | - $order_by = $query_params['orderby']; | |
| 1258 | -        } else { | |
| 1259 | - $order_by = null; | |
| 1260 | - } | |
| 1261 | -        if ($order_by !== null) { | |
| 1262 | -            if (is_array($order_by)) { | |
| 1263 | - $order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by); | |
| 1264 | -            } else { | |
| 1265 | - // it's a single item | |
| 1266 | - $order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by); | |
| 1267 | - } | |
| 1268 | - $model_query_params['order_by'] = $order_by; | |
| 1269 | - } | |
| 1270 | -        if (isset($query_params['group_by'])) { | |
| 1271 | - $group_by = $query_params['group_by']; | |
| 1272 | -        } elseif (isset($query_params['groupby'])) { | |
| 1273 | - $group_by = $query_params['groupby']; | |
| 1274 | -        } else { | |
| 1275 | - $group_by = array_keys($model->get_combined_primary_key_fields()); | |
| 1276 | - } | |
| 1277 | - // make sure they're all real names | |
| 1278 | -        if (is_array($group_by)) { | |
| 1279 | - $group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by); | |
| 1280 | - } | |
| 1281 | -        if ($group_by !== null) { | |
| 1282 | - $model_query_params['group_by'] = $group_by; | |
| 1283 | - } | |
| 1284 | -        if (isset($query_params['having'])) { | |
| 1285 | - $model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 1286 | - $query_params['having'], | |
| 1287 | - $model, | |
| 1288 | - $this->getModelVersionInfo()->requestedVersion() | |
| 1289 | - ); | |
| 1290 | - } | |
| 1291 | -        if (isset($query_params['order'])) { | |
| 1292 | - $model_query_params['order'] = $query_params['order']; | |
| 1293 | - } | |
| 1294 | -        if (isset($query_params['mine'])) { | |
| 1295 | - $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params); | |
| 1296 | - } | |
| 1297 | -        if (isset($query_params['limit'])) { | |
| 1298 | - // limit should be either a string like '23' or '23,43', or an array with two items in it | |
| 1299 | -            if (! is_array($query_params['limit'])) { | |
| 1300 | -                $limit_array = explode(',', (string) $query_params['limit']); | |
| 1301 | -            } else { | |
| 1302 | - $limit_array = $query_params['limit']; | |
| 1303 | - } | |
| 1304 | - $sanitized_limit = array(); | |
| 1305 | -            foreach ($limit_array as $key => $limit_part) { | |
| 1306 | -                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) { | |
| 1307 | - throw new EE_Error( | |
| 1308 | - sprintf( | |
| 1309 | - __( | |
| 1310 | - // @codingStandardsIgnoreStart | |
| 1311 | - 'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.', | |
| 1312 | - // @codingStandardsIgnoreEnd | |
| 1313 | - 'event_espresso' | |
| 1314 | - ), | |
| 1315 | - wp_json_encode($query_params['limit']) | |
| 1316 | - ) | |
| 1317 | - ); | |
| 1318 | - } | |
| 1319 | - $sanitized_limit[] = (int) $limit_part; | |
| 1320 | - } | |
| 1321 | -            $model_query_params['limit'] = implode(',', $sanitized_limit); | |
| 1322 | -        } else { | |
| 1323 | - $model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit(); | |
| 1324 | - } | |
| 1325 | -        if (isset($query_params['caps'])) { | |
| 1326 | - $model_query_params['caps'] = $this->validateContext($query_params['caps']); | |
| 1327 | -        } else { | |
| 1328 | - $model_query_params['caps'] = EEM_Base::caps_read; | |
| 1329 | - } | |
| 1330 | -        if (isset($query_params['default_where_conditions'])) { | |
| 1331 | - $model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams( | |
| 1332 | - $query_params['default_where_conditions'] | |
| 1333 | - ); | |
| 1334 | - } | |
| 1335 | - // if this is a model protected by a password on another model, exclude the password protected | |
| 1336 | - // entities by default. But if they passed in a password, try to show them all. If the password is wrong, | |
| 1337 | - // though, they'll get an error (see Read::createEntityFromWpdbResult() which calls Read::checkPassword) | |
| 1338 | - if (! $model->hasPassword() | |
| 1339 | - && $model->restrictedByRelatedModelPassword() | |
| 1340 | -            && $model_query_params['caps'] === EEM_Base::caps_read) { | |
| 1341 | -            if (empty($query_params['password'])) { | |
| 1342 | - $model_query_params['exclude_protected'] = true; | |
| 1343 | - } | |
| 1344 | - } | |
| 1345 | - | |
| 1346 | -        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_params, $model); | |
| 1347 | - } | |
| 1348 | - | |
| 1349 | - | |
| 1350 | - /** | |
| 1351 | - * Changes the REST-style query params for use in the models | |
| 1352 | - * | |
| 1353 | - * @deprecated | |
| 1354 | - * @param EEM_Base $model | |
| 1355 | - * @param array $query_params sub-array from @see EEM_Base::get_all() | |
| 1356 | - * @return array | |
| 1357 | - */ | |
| 1358 | - public function prepareRestQueryParamsKeyForModels($model, $query_params) | |
| 1359 | -    { | |
| 1360 | - $model_ready_query_params = array(); | |
| 1361 | -        foreach ($query_params as $key => $value) { | |
| 1362 | -            if (is_array($value)) { | |
| 1363 | - $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value); | |
| 1364 | -            } else { | |
| 1365 | - $model_ready_query_params[ $key ] = $value; | |
| 1366 | - } | |
| 1367 | - } | |
| 1368 | - return $model_ready_query_params; | |
| 1369 | - } | |
| 1370 | - | |
| 1371 | - | |
| 1372 | - /** | |
| 1373 | - * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson() | |
| 1374 | - * @param $model | |
| 1375 | - * @param $query_params | |
| 1376 | - * @return array | |
| 1377 | - */ | |
| 1378 | - public function prepareRestQueryParamsValuesForModels($model, $query_params) | |
| 1379 | -    { | |
| 1380 | - $model_ready_query_params = array(); | |
| 1381 | -        foreach ($query_params as $key => $value) { | |
| 1382 | -            if (is_array($value)) { | |
| 1383 | - $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value); | |
| 1384 | -            } else { | |
| 1385 | - $model_ready_query_params[ $key ] = $value; | |
| 1386 | - } | |
| 1387 | - } | |
| 1388 | - return $model_ready_query_params; | |
| 1389 | - } | |
| 1390 | - | |
| 1391 | - | |
| 1392 | - /** | |
| 1393 | - * Explodes the string on commas, and only returns items with $prefix followed by a period. | |
| 1394 | - * If no prefix is specified, returns items with no period. | |
| 1395 | - * | |
| 1396 | -     * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' ) | |
| 1397 | - * @param string $prefix "Event" or "foobar" | |
| 1398 | - * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified | |
| 1399 | - * we only return strings starting with that and a period; if no prefix was | |
| 1400 | - * specified we return all items containing NO periods | |
| 1401 | - */ | |
| 1402 | - public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix) | |
| 1403 | -    { | |
| 1404 | -        if (is_string($string_to_explode)) { | |
| 1405 | -            $exploded_contents = explode(',', $string_to_explode); | |
| 1406 | -        } elseif (is_array($string_to_explode)) { | |
| 1407 | - $exploded_contents = $string_to_explode; | |
| 1408 | -        } else { | |
| 1409 | - $exploded_contents = array(); | |
| 1410 | - } | |
| 1411 | - // if the string was empty, we want an empty array | |
| 1412 | - $exploded_contents = array_filter($exploded_contents); | |
| 1413 | - $contents_with_prefix = array(); | |
| 1414 | -        foreach ($exploded_contents as $item) { | |
| 1415 | - $item = trim($item); | |
| 1416 | - // if no prefix was provided, so we look for items with no "." in them | |
| 1417 | -            if (! $prefix) { | |
| 1418 | - // does this item have a period? | |
| 1419 | -                if (strpos($item, '.') === false) { | |
| 1420 | - // if not, then its what we're looking for | |
| 1421 | - $contents_with_prefix[] = $item; | |
| 1422 | - } | |
| 1423 | -            } elseif (strpos($item, $prefix . '.') === 0) { | |
| 1424 | - // this item has the prefix and a period, grab it | |
| 1425 | - $contents_with_prefix[] = substr( | |
| 1426 | - $item, | |
| 1427 | - strpos($item, $prefix . '.') + strlen($prefix . '.') | |
| 1428 | - ); | |
| 1429 | -            } elseif ($item === $prefix) { | |
| 1430 | - // this item is JUST the prefix | |
| 1431 | - // so let's grab everything after, which is a blank string | |
| 1432 | - $contents_with_prefix[] = ''; | |
| 1433 | - } | |
| 1434 | - } | |
| 1435 | - return $contents_with_prefix; | |
| 1436 | - } | |
| 1437 | - | |
| 1438 | - | |
| 1439 | - /** | |
| 1440 | - * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with. | |
| 1441 | - * Deprecated because its return values were really quite confusing- sometimes it returned | |
| 1442 | - * an empty array (when the include string was blank or '*') or sometimes it returned | |
| 1443 | -     * array('*') (when you provided a model and a model of that kind was found). | |
| 1444 | - * Parses the $include_string so we fetch all the field names relating to THIS model | |
| 1445 | - * (ie have NO period in them), or for the provided model (ie start with the model | |
| 1446 | - * name and then a period). | |
| 1447 | - * @param string $include_string @see Read:handle_request_get_all | |
| 1448 | - * @param string $model_name | |
| 1449 | - * @return array of fields for this model. If $model_name is provided, then | |
| 1450 | - * the fields for that model, with the model's name removed from each. | |
| 1451 | - * If $include_string was blank or '*' returns an empty array | |
| 1452 | - */ | |
| 1453 | - public function extractIncludesForThisModel($include_string, $model_name = null) | |
| 1454 | -    { | |
| 1455 | -        if (is_array($include_string)) { | |
| 1456 | -            $include_string = implode(',', $include_string); | |
| 1457 | - } | |
| 1458 | -        if ($include_string === '*' || $include_string === '') { | |
| 1459 | - return array(); | |
| 1460 | - } | |
| 1461 | -        $includes = explode(',', $include_string); | |
| 1462 | - $extracted_fields_to_include = array(); | |
| 1463 | -        if ($model_name) { | |
| 1464 | -            foreach ($includes as $field_to_include) { | |
| 1465 | - $field_to_include = trim($field_to_include); | |
| 1466 | -                if (strpos($field_to_include, $model_name . '.') === 0) { | |
| 1467 | - // found the model name at the exact start | |
| 1468 | - $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include); | |
| 1469 | - $extracted_fields_to_include[] = $field_sans_model_name; | |
| 1470 | -                } elseif ($field_to_include == $model_name) { | |
| 1471 | - $extracted_fields_to_include[] = '*'; | |
| 1472 | - } | |
| 1473 | - } | |
| 1474 | -        } else { | |
| 1475 | - // look for ones with no period | |
| 1476 | -            foreach ($includes as $field_to_include) { | |
| 1477 | - $field_to_include = trim($field_to_include); | |
| 1478 | - if (strpos($field_to_include, '.') === false | |
| 1479 | - && ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include) | |
| 1480 | -                ) { | |
| 1481 | - $extracted_fields_to_include[] = $field_to_include; | |
| 1482 | - } | |
| 1483 | - } | |
| 1484 | - } | |
| 1485 | - return $extracted_fields_to_include; | |
| 1486 | - } | |
| 1487 | - | |
| 1488 | - | |
| 1489 | - /** | |
| 1490 | - * Gets the single item using the model according to the request in the context given, otherwise | |
| 1491 | - * returns that it's inaccessible to the current user | |
| 1492 | - * | |
| 1493 | - * @param EEM_Base $model | |
| 1494 | - * @param WP_REST_Request $request | |
| 1495 | - * @param null $context | |
| 1496 | - * @return array | |
| 1497 | - * @throws EE_Error | |
| 1498 | - */ | |
| 1499 | - public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null) | |
| 1500 | -    { | |
| 1501 | -        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1); | |
| 1502 | -        if ($model instanceof EEM_Soft_Delete_Base) { | |
| 1503 | - $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params); | |
| 1504 | - } | |
| 1505 | - $restricted_query_params = $query_params; | |
| 1506 | - $restricted_query_params['caps'] = $context; | |
| 1507 | -        $this->setDebugInfo('model query params', $restricted_query_params); | |
| 1508 | - $model_rows = $model->get_all_wpdb_results($restricted_query_params); | |
| 1509 | -        if (! empty($model_rows)) { | |
| 1510 | - return $this->createEntityFromWpdbResult( | |
| 1511 | - $model, | |
| 1512 | - reset($model_rows), | |
| 1513 | - $request | |
| 1514 | - ); | |
| 1515 | -        } else { | |
| 1516 | - // ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities | |
| 1517 | - $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 1518 | -            if ($model->exists($query_params)) { | |
| 1519 | - // you got shafted- it existed but we didn't want to tell you! | |
| 1520 | - throw new RestException( | |
| 1521 | - 'rest_user_cannot_' . $context, | |
| 1522 | - sprintf( | |
| 1523 | -                        __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'), | |
| 1524 | - $context, | |
| 1525 | - $lowercase_model_name, | |
| 1526 | - Capabilities::getMissingPermissionsString( | |
| 1527 | - $model, | |
| 1528 | - $context | |
| 1529 | - ) | |
| 1530 | - ), | |
| 1531 | -                    array('status' => 403) | |
| 1532 | - ); | |
| 1533 | -            } else { | |
| 1534 | - // it's not you. It just doesn't exist | |
| 1535 | - throw new RestException( | |
| 1536 | -                    sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 1537 | -                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 1538 | -                    array('status' => 404) | |
| 1539 | - ); | |
| 1540 | - } | |
| 1541 | - } | |
| 1542 | - } | |
| 1543 | - | |
| 1544 | - /** | |
| 1545 | - * Checks that if this content requires a password to be read, that it's been provided and is correct. | |
| 1546 | - * @since 4.9.74.p | |
| 1547 | - * @param EEM_Base $model | |
| 1548 | - * @param $model_row | |
| 1549 | - * @param $query_params Adds 'default_where_conditions' => 'minimum' to ensure we don't confuse trashed with | |
| 1550 | - * password protected. | |
| 1551 | - * @param WP_REST_Request $request | |
| 1552 | - * @throws EE_Error | |
| 1553 | - * @throws InvalidArgumentException | |
| 1554 | - * @throws InvalidDataTypeException | |
| 1555 | - * @throws InvalidInterfaceException | |
| 1556 | - * @throws RestPasswordRequiredException | |
| 1557 | - * @throws RestPasswordIncorrectException | |
| 1558 | - * @throws \EventEspresso\core\exceptions\ModelConfigurationException | |
| 1559 | - * @throws ReflectionException | |
| 1560 | - */ | |
| 1561 | - protected function checkPassword(EEM_Base $model, $model_row, $query_params, WP_REST_Request $request) | |
| 1562 | -    { | |
| 1563 | - $query_params['default_where_conditions'] = 'minimum'; | |
| 1564 | - // stuff is only "protected" for front-end requests. Elsewhere, you either get full permission to access the object | |
| 1565 | - // or you don't. | |
| 1566 | -        $request_caps = $request->get_param('caps'); | |
| 1567 | -        if (isset($request_caps) && $request_caps !== EEM_Base::caps_read) { | |
| 1568 | - return; | |
| 1569 | - } | |
| 1570 | - // if this entity requires a password, they better give it and it better be right! | |
| 1571 | - if ($model->hasPassword() | |
| 1572 | -            && $model_row[ $model->getPasswordField()->get_qualified_column() ] !== '') { | |
| 1573 | -            if (empty($request['password'])) { | |
| 1574 | - throw new RestPasswordRequiredException(); | |
| 1575 | - } elseif (!hash_equals( | |
| 1576 | - $model_row[ $model->getPasswordField()->get_qualified_column() ], | |
| 1577 | - $request['password'] | |
| 1578 | -            )) { | |
| 1579 | - throw new RestPasswordIncorrectException(); | |
| 1580 | - } | |
| 1581 | - } // wait! maybe this content is password protected | |
| 1582 | - elseif ($model->restrictedByRelatedModelPassword() | |
| 1583 | -            && $request->get_param('caps') === EEM_Base::caps_read) { | |
| 1584 | -            $password_supplied = $request->get_param('password'); | |
| 1585 | -            if (empty($password_supplied)) { | |
| 1586 | - $query_params['exclude_protected'] = true; | |
| 1587 | -                if (!$model->exists($query_params)) { | |
| 1588 | - throw new RestPasswordRequiredException(); | |
| 1589 | - } | |
| 1590 | -            } else { | |
| 1591 | - $query_params[0][ $model->modelChainAndPassword() ] = $password_supplied; | |
| 1592 | -                if (!$model->exists($query_params)) { | |
| 1593 | - throw new RestPasswordIncorrectException(); | |
| 1594 | - } | |
| 1595 | - } | |
| 1596 | - } | |
| 1597 | - } | |
| 48 | + /** | |
| 49 | + * @var CalculatedModelFields | |
| 50 | + */ | |
| 51 | + protected $fields_calculator; | |
| 52 | + | |
| 53 | + | |
| 54 | + /** | |
| 55 | + * Read constructor. | |
| 56 | + * @param CalculatedModelFields $fields_calculator | |
| 57 | + */ | |
| 58 | + public function __construct(CalculatedModelFields $fields_calculator) | |
| 59 | +	{ | |
| 60 | + parent::__construct(); | |
| 61 | + $this->fields_calculator = $fields_calculator; | |
| 62 | + } | |
| 63 | + | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * Handles requests to get all (or a filtered subset) of entities for a particular model | |
| 67 | + * | |
| 68 | + * @param WP_REST_Request $request | |
| 69 | + * @param string $version | |
| 70 | + * @param string $model_name | |
| 71 | + * @return WP_REST_Response|WP_Error | |
| 72 | + * @throws InvalidArgumentException | |
| 73 | + * @throws InvalidDataTypeException | |
| 74 | + * @throws InvalidInterfaceException | |
| 75 | + */ | |
| 76 | + public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name) | |
| 77 | +	{ | |
| 78 | +		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 79 | +		try { | |
| 80 | + $controller->setRequestedVersion($version); | |
| 81 | +			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 82 | + return $controller->sendResponse( | |
| 83 | + new WP_Error( | |
| 84 | + 'endpoint_parsing_error', | |
| 85 | + sprintf( | |
| 86 | + __( | |
| 87 | + 'There is no model for endpoint %s. Please contact event espresso support', | |
| 88 | + 'event_espresso' | |
| 89 | + ), | |
| 90 | + $model_name | |
| 91 | + ) | |
| 92 | + ) | |
| 93 | + ); | |
| 94 | + } | |
| 95 | + return $controller->sendResponse( | |
| 96 | + $controller->getEntitiesFromModel( | |
| 97 | + $controller->getModelVersionInfo()->loadModel($model_name), | |
| 98 | + $request | |
| 99 | + ) | |
| 100 | + ); | |
| 101 | +		} catch (Exception $e) { | |
| 102 | + return $controller->sendResponse($e); | |
| 103 | + } | |
| 104 | + } | |
| 105 | + | |
| 106 | + | |
| 107 | + /** | |
| 108 | + * Prepares and returns schema for any OPTIONS request. | |
| 109 | + * | |
| 110 | + * @param string $version The API endpoint version being used. | |
| 111 | + * @param string $model_name Something like `Event` or `Registration` | |
| 112 | + * @return array | |
| 113 | + * @throws InvalidArgumentException | |
| 114 | + * @throws InvalidDataTypeException | |
| 115 | + * @throws InvalidInterfaceException | |
| 116 | + */ | |
| 117 | + public static function handleSchemaRequest($version, $model_name) | |
| 118 | +	{ | |
| 119 | +		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 120 | +		try { | |
| 121 | + $controller->setRequestedVersion($version); | |
| 122 | +			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 123 | + return array(); | |
| 124 | + } | |
| 125 | + // get the model for this version | |
| 126 | + $model = $controller->getModelVersionInfo()->loadModel($model_name); | |
| 127 | +			$model_schema = new JsonModelSchema($model, LoaderFactory::getLoader()->getShared('EventEspresso\core\libraries\rest_api\CalculatedModelFields')); | |
| 128 | + return $model_schema->getModelSchemaForRelations( | |
| 129 | + $controller->getModelVersionInfo()->relationSettings($model), | |
| 130 | + $controller->customizeSchemaForRestResponse( | |
| 131 | + $model, | |
| 132 | + $model_schema->getModelSchemaForFields( | |
| 133 | + $controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model), | |
| 134 | + $model_schema->getInitialSchemaStructure() | |
| 135 | + ) | |
| 136 | + ) | |
| 137 | + ); | |
| 138 | +		} catch (Exception $e) { | |
| 139 | + return array(); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + | |
| 144 | + /** | |
| 145 | + * This loops through each field in the given schema for the model and does the following: | |
| 146 | + * - add any extra fields that are REST API specific and related to existing fields. | |
| 147 | + * - transform default values into the correct format for a REST API response. | |
| 148 | + * | |
| 149 | + * @param EEM_Base $model | |
| 150 | + * @param array $schema | |
| 151 | + * @return array The final schema. | |
| 152 | + */ | |
| 153 | + protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema) | |
| 154 | +	{ | |
| 155 | +		foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) { | |
| 156 | + $schema = $this->translateDefaultsForRestResponse( | |
| 157 | + $field_name, | |
| 158 | + $field, | |
| 159 | + $this->maybeAddExtraFieldsToSchema($field_name, $field, $schema) | |
| 160 | + ); | |
| 161 | + } | |
| 162 | + return $schema; | |
| 163 | + } | |
| 164 | + | |
| 165 | + | |
| 166 | + /** | |
| 167 | + * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST | |
| 168 | + * response. | |
| 169 | + * | |
| 170 | + * @param $field_name | |
| 171 | + * @param EE_Model_Field_Base $field | |
| 172 | + * @param array $schema | |
| 173 | + * @return array | |
| 174 | + * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we | |
| 175 | + * did, let's know about it ASAP, so let the exception bubble up) | |
| 176 | + */ | |
| 177 | + protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema) | |
| 178 | +	{ | |
| 179 | +		if (isset($schema['properties'][ $field_name ]['default'])) { | |
| 180 | +			if (is_array($schema['properties'][ $field_name ]['default'])) { | |
| 181 | +				foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) { | |
| 182 | +					if ($default_key === 'raw') { | |
| 183 | + $schema['properties'][ $field_name ]['default'][ $default_key ] = | |
| 184 | + ModelDataTranslator::prepareFieldValueForJson( | |
| 185 | + $field, | |
| 186 | + $default_value, | |
| 187 | + $this->getModelVersionInfo()->requestedVersion() | |
| 188 | + ); | |
| 189 | + } | |
| 190 | + } | |
| 191 | +			} else { | |
| 192 | + $schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson( | |
| 193 | + $field, | |
| 194 | + $schema['properties'][ $field_name ]['default'], | |
| 195 | + $this->getModelVersionInfo()->requestedVersion() | |
| 196 | + ); | |
| 197 | + } | |
| 198 | + } | |
| 199 | + return $schema; | |
| 200 | + } | |
| 201 | + | |
| 202 | + | |
| 203 | + /** | |
| 204 | + * Adds additional fields to the schema | |
| 205 | + * The REST API returns a GMT value field for each datetime field in the resource. Thus the description about this | |
| 206 | + * needs to be added to the schema. | |
| 207 | + * | |
| 208 | + * @param $field_name | |
| 209 | + * @param EE_Model_Field_Base $field | |
| 210 | + * @param array $schema | |
| 211 | + * @return array | |
| 212 | + */ | |
| 213 | + protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema) | |
| 214 | +	{ | |
| 215 | +		if ($field instanceof EE_Datetime_Field) { | |
| 216 | + $schema['properties'][ $field_name . '_gmt' ] = $field->getSchema(); | |
| 217 | + // modify the description | |
| 218 | + $schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf( | |
| 219 | +				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'), | |
| 220 | + wp_specialchars_decode($field->get_nicename(), ENT_QUOTES) | |
| 221 | + ); | |
| 222 | + } | |
| 223 | + return $schema; | |
| 224 | + } | |
| 225 | + | |
| 226 | + | |
| 227 | + /** | |
| 228 | + * Used to figure out the route from the request when a `WP_REST_Request` object is not available | |
| 229 | + * | |
| 230 | + * @return string | |
| 231 | + */ | |
| 232 | + protected function getRouteFromRequest() | |
| 233 | +	{ | |
| 234 | + if (isset($GLOBALS['wp']) | |
| 235 | + && $GLOBALS['wp'] instanceof \WP | |
| 236 | + && isset($GLOBALS['wp']->query_vars['rest_route']) | |
| 237 | +		) { | |
| 238 | + return $GLOBALS['wp']->query_vars['rest_route']; | |
| 239 | +		} else { | |
| 240 | + return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/'; | |
| 241 | + } | |
| 242 | + } | |
| 243 | + | |
| 244 | + | |
| 245 | + /** | |
| 246 | + * Gets a single entity related to the model indicated in the path and its id | |
| 247 | + * | |
| 248 | + * @param WP_REST_Request $request | |
| 249 | + * @param string $version | |
| 250 | + * @param string $model_name | |
| 251 | + * @return WP_REST_Response|WP_Error | |
| 252 | + * @throws InvalidDataTypeException | |
| 253 | + * @throws InvalidInterfaceException | |
| 254 | + * @throws InvalidArgumentException | |
| 255 | + */ | |
| 256 | + public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name) | |
| 257 | +	{ | |
| 258 | +		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 259 | +		try { | |
| 260 | + $controller->setRequestedVersion($version); | |
| 261 | +			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) { | |
| 262 | + return $controller->sendResponse( | |
| 263 | + new WP_Error( | |
| 264 | + 'endpoint_parsing_error', | |
| 265 | + sprintf( | |
| 266 | + __( | |
| 267 | + 'There is no model for endpoint %s. Please contact event espresso support', | |
| 268 | + 'event_espresso' | |
| 269 | + ), | |
| 270 | + $model_name | |
| 271 | + ) | |
| 272 | + ) | |
| 273 | + ); | |
| 274 | + } | |
| 275 | + return $controller->sendResponse( | |
| 276 | + $controller->getEntityFromModel( | |
| 277 | + $controller->getModelVersionInfo()->loadModel($model_name), | |
| 278 | + $request | |
| 279 | + ) | |
| 280 | + ); | |
| 281 | +		} catch (Exception $e) { | |
| 282 | + return $controller->sendResponse($e); | |
| 283 | + } | |
| 284 | + } | |
| 285 | + | |
| 286 | + | |
| 287 | + /** | |
| 288 | + * Gets all the related entities (or if its a belongs-to relation just the one) | |
| 289 | + * to the item with the given id | |
| 290 | + * | |
| 291 | + * @param WP_REST_Request $request | |
| 292 | + * @param string $version | |
| 293 | + * @param string $model_name | |
| 294 | + * @param string $related_model_name | |
| 295 | + * @return WP_REST_Response|WP_Error | |
| 296 | + * @throws InvalidDataTypeException | |
| 297 | + * @throws InvalidInterfaceException | |
| 298 | + * @throws InvalidArgumentException | |
| 299 | + */ | |
| 300 | + public static function handleRequestGetRelated( | |
| 301 | + WP_REST_Request $request, | |
| 302 | + $version, | |
| 303 | + $model_name, | |
| 304 | + $related_model_name | |
| 305 | +	) { | |
| 306 | +		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read'); | |
| 307 | +		try { | |
| 308 | + $controller->setRequestedVersion($version); | |
| 309 | + $main_model = $controller->validateModel($model_name); | |
| 310 | + $controller->validateModel($related_model_name); | |
| 311 | + return $controller->sendResponse( | |
| 312 | + $controller->getEntitiesFromRelation( | |
| 313 | +					$request->get_param('id'), | |
| 314 | + $main_model->related_settings_for($related_model_name), | |
| 315 | + $request | |
| 316 | + ) | |
| 317 | + ); | |
| 318 | +		} catch (Exception $e) { | |
| 319 | + return $controller->sendResponse($e); | |
| 320 | + } | |
| 321 | + } | |
| 322 | + | |
| 323 | + | |
| 324 | + /** | |
| 325 | + * Gets a collection for the given model and filters | |
| 326 | + * | |
| 327 | + * @param EEM_Base $model | |
| 328 | + * @param WP_REST_Request $request | |
| 329 | + * @return array | |
| 330 | + * @throws EE_Error | |
| 331 | + * @throws InvalidArgumentException | |
| 332 | + * @throws InvalidDataTypeException | |
| 333 | + * @throws InvalidInterfaceException | |
| 334 | + * @throws ReflectionException | |
| 335 | + * @throws RestException | |
| 336 | + */ | |
| 337 | + public function getEntitiesFromModel($model, $request) | |
| 338 | +	{ | |
| 339 | + $query_params = $this->createModelQueryParams($model, $request->get_params()); | |
| 340 | +		if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) { | |
| 341 | + $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name()); | |
| 342 | + throw new RestException( | |
| 343 | +				sprintf('rest_%s_cannot_list', $model_name_plural), | |
| 344 | + sprintf( | |
| 345 | +					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'), | |
| 346 | + $model_name_plural, | |
| 347 | + Capabilities::getMissingPermissionsString($model, $query_params['caps']) | |
| 348 | + ), | |
| 349 | +				array('status' => 403) | |
| 350 | + ); | |
| 351 | + } | |
| 352 | +		if (! $request->get_header('no_rest_headers')) { | |
| 353 | + $this->setHeadersFromQueryParams($model, $query_params); | |
| 354 | + } | |
| 355 | + /** @type array $results */ | |
| 356 | + $results = $model->get_all_wpdb_results($query_params); | |
| 357 | + $nice_results = array(); | |
| 358 | +		foreach ($results as $result) { | |
| 359 | + $nice_results[] = $this->createEntityFromWpdbResult( | |
| 360 | + $model, | |
| 361 | + $result, | |
| 362 | + $request | |
| 363 | + ); | |
| 364 | + } | |
| 365 | + return $nice_results; | |
| 366 | + } | |
| 367 | + | |
| 368 | + | |
| 369 | + /** | |
| 370 | + * Gets the collection for given relation object | |
| 371 | + * The same as Read::get_entities_from_model(), except if the relation | |
| 372 | + * is a HABTM relation, in which case it merges any non-foreign-key fields from | |
| 373 | + * the join-model-object into the results | |
| 374 | + * | |
| 375 | + * @param array $primary_model_query_params query params for finding the item from which | |
| 376 | + * relations will be based | |
| 377 | + * @param \EE_Model_Relation_Base $relation | |
| 378 | + * @param WP_REST_Request $request | |
| 379 | + * @return array | |
| 380 | + * @throws EE_Error | |
| 381 | + * @throws InvalidArgumentException | |
| 382 | + * @throws InvalidDataTypeException | |
| 383 | + * @throws InvalidInterfaceException | |
| 384 | + * @throws ReflectionException | |
| 385 | + * @throws RestException | |
| 386 | + * @throws \EventEspresso\core\exceptions\ModelConfigurationException | |
| 387 | + */ | |
| 388 | + protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request) | |
| 389 | +	{ | |
| 390 | +		$context = $this->validateContext($request->get_param('caps')); | |
| 391 | + $model = $relation->get_this_model(); | |
| 392 | + $related_model = $relation->get_other_model(); | |
| 393 | +		if (! isset($primary_model_query_params[0])) { | |
| 394 | + $primary_model_query_params[0] = array(); | |
| 395 | + } | |
| 396 | + // check if they can access the 1st model object | |
| 397 | + $primary_model_query_params = array( | |
| 398 | + 0 => $primary_model_query_params[0], | |
| 399 | + 'limit' => 1, | |
| 400 | + ); | |
| 401 | +		if ($model instanceof EEM_Soft_Delete_Base) { | |
| 402 | + $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included( | |
| 403 | + $primary_model_query_params | |
| 404 | + ); | |
| 405 | + } | |
| 406 | + $restricted_query_params = $primary_model_query_params; | |
| 407 | + $restricted_query_params['caps'] = $context; | |
| 408 | + $restricted_query_params['limit'] = 1; | |
| 409 | +		$this->setDebugInfo('main model query params', $restricted_query_params); | |
| 410 | +		$this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context)); | |
| 411 | + $primary_model_rows = $model->get_all_wpdb_results($restricted_query_params); | |
| 412 | + $primary_model_row = null; | |
| 413 | +		if (is_array($primary_model_rows)) { | |
| 414 | + $primary_model_row = reset($primary_model_rows); | |
| 415 | + } | |
| 416 | + if (! ( | |
| 417 | + Capabilities::currentUserHasPartialAccessTo($related_model, $context) | |
| 418 | + && $primary_model_row | |
| 419 | + ) | |
| 420 | +		) { | |
| 421 | +			if ($relation instanceof EE_Belongs_To_Relation) { | |
| 422 | + $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name()); | |
| 423 | +			} else { | |
| 424 | + $related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower( | |
| 425 | + $related_model->get_this_model_name() | |
| 426 | + ); | |
| 427 | + } | |
| 428 | + throw new RestException( | |
| 429 | +				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural), | |
| 430 | + sprintf( | |
| 431 | + __( | |
| 432 | + 'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s', | |
| 433 | + 'event_espresso' | |
| 434 | + ), | |
| 435 | + $related_model_name_maybe_plural, | |
| 436 | + $relation->get_this_model()->get_this_model_name(), | |
| 437 | + implode( | |
| 438 | + ',', | |
| 439 | + array_keys( | |
| 440 | + Capabilities::getMissingPermissions($related_model, $context) | |
| 441 | + ) | |
| 442 | + ) | |
| 443 | + ), | |
| 444 | +				array('status' => 403) | |
| 445 | + ); | |
| 446 | + } | |
| 447 | + | |
| 448 | + $this->checkPassword( | |
| 449 | + $model, | |
| 450 | + $primary_model_row, | |
| 451 | + $restricted_query_params, | |
| 452 | + $request | |
| 453 | + ); | |
| 454 | + $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params()); | |
| 455 | +		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) { | |
| 456 | + $query_params[0][ $relation->get_this_model()->get_this_model_name() | |
| 457 | + . '.' | |
| 458 | + . $where_condition_key ] = $where_condition_value; | |
| 459 | + } | |
| 460 | + $query_params['default_where_conditions'] = 'none'; | |
| 461 | + $query_params['caps'] = $context; | |
| 462 | +		if (! $request->get_header('no_rest_headers')) { | |
| 463 | + $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params); | |
| 464 | + } | |
| 465 | + /** @type array $results */ | |
| 466 | + $results = $relation->get_other_model()->get_all_wpdb_results($query_params); | |
| 467 | + $nice_results = array(); | |
| 468 | +		foreach ($results as $result) { | |
| 469 | + $nice_result = $this->createEntityFromWpdbResult( | |
| 470 | + $relation->get_other_model(), | |
| 471 | + $result, | |
| 472 | + $request | |
| 473 | + ); | |
| 474 | +			if ($relation instanceof \EE_HABTM_Relation) { | |
| 475 | + // put the unusual stuff (properties from the HABTM relation) first, and make sure | |
| 476 | + // if there are conflicts we prefer the properties from the main model | |
| 477 | + $join_model_result = $this->createEntityFromWpdbResult( | |
| 478 | + $relation->get_join_model(), | |
| 479 | + $result, | |
| 480 | + $request | |
| 481 | + ); | |
| 482 | + $joined_result = array_merge($nice_result, $join_model_result); | |
| 483 | + // but keep the meta stuff from the main model | |
| 484 | +				if (isset($nice_result['meta'])) { | |
| 485 | + $joined_result['meta'] = $nice_result['meta']; | |
| 486 | + } | |
| 487 | + $nice_result = $joined_result; | |
| 488 | + } | |
| 489 | + $nice_results[] = $nice_result; | |
| 490 | + } | |
| 491 | +		if ($relation instanceof EE_Belongs_To_Relation) { | |
| 492 | + return array_shift($nice_results); | |
| 493 | +		} else { | |
| 494 | + return $nice_results; | |
| 495 | + } | |
| 496 | + } | |
| 497 | + | |
| 498 | + | |
| 499 | + /** | |
| 500 | + * Gets the collection for given relation object | |
| 501 | + * The same as Read::get_entities_from_model(), except if the relation | |
| 502 | + * is a HABTM relation, in which case it merges any non-foreign-key fields from | |
| 503 | + * the join-model-object into the results | |
| 504 | + * | |
| 505 | + * @param string $id the ID of the thing we are fetching related stuff from | |
| 506 | + * @param \EE_Model_Relation_Base $relation | |
| 507 | + * @param WP_REST_Request $request | |
| 508 | + * @return array | |
| 509 | + * @throws EE_Error | |
| 510 | + */ | |
| 511 | + public function getEntitiesFromRelation($id, $relation, $request) | |
| 512 | +	{ | |
| 513 | +		if (! $relation->get_this_model()->has_primary_key_field()) { | |
| 514 | + throw new EE_Error( | |
| 515 | + sprintf( | |
| 516 | + __( | |
| 517 | + // @codingStandardsIgnoreStart | |
| 518 | + 'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s', | |
| 519 | + // @codingStandardsIgnoreEnd | |
| 520 | + 'event_espresso' | |
| 521 | + ), | |
| 522 | + $relation->get_this_model()->get_this_model_name() | |
| 523 | + ) | |
| 524 | + ); | |
| 525 | + } | |
| 526 | + // can we edit that main item? | |
| 527 | + // if not, show nothing but an error | |
| 528 | + // otherwise, please proceed | |
| 529 | + return $this->getEntitiesFromRelationUsingModelQueryParams( | |
| 530 | + array( | |
| 531 | + array( | |
| 532 | + $relation->get_this_model()->primary_key_name() => $id, | |
| 533 | + ), | |
| 534 | + ), | |
| 535 | + $relation, | |
| 536 | + $request | |
| 537 | + ); | |
| 538 | + } | |
| 539 | + | |
| 540 | + | |
| 541 | + /** | |
| 542 | + * Sets the headers that are based on the model and query params, | |
| 543 | + * like the total records. This should only be called on the original request | |
| 544 | + * from the client, not on subsequent internal | |
| 545 | + * | |
| 546 | + * @param EEM_Base $model | |
| 547 | + * @param array $query_params | |
| 548 | + * @return void | |
| 549 | + */ | |
| 550 | + protected function setHeadersFromQueryParams($model, $query_params) | |
| 551 | +	{ | |
| 552 | +		$this->setDebugInfo('model query params', $query_params); | |
| 553 | + $this->setDebugInfo( | |
| 554 | + 'missing caps', | |
| 555 | + Capabilities::getMissingPermissionsString($model, $query_params['caps']) | |
| 556 | + ); | |
| 557 | + // normally the limit to a 2-part array, where the 2nd item is the limit | |
| 558 | +		if (! isset($query_params['limit'])) { | |
| 559 | + $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit(); | |
| 560 | + } | |
| 561 | +		if (is_array($query_params['limit'])) { | |
| 562 | + $limit_parts = $query_params['limit']; | |
| 563 | +		} else { | |
| 564 | +			$limit_parts = explode(',', $query_params['limit']); | |
| 565 | +			if (count($limit_parts) == 1) { | |
| 566 | + $limit_parts = array(0, $limit_parts[0]); | |
| 567 | + } | |
| 568 | + } | |
| 569 | + // remove the group by and having parts of the query, as those will | |
| 570 | + // make the sql query return an array of values, instead of just a single value | |
| 571 | + unset($query_params['group_by'], $query_params['having'], $query_params['limit']); | |
| 572 | + $count = $model->count($query_params, null, true); | |
| 573 | + $pages = $count / $limit_parts[1]; | |
| 574 | +		$this->setResponseHeader('Total', $count, false); | |
| 575 | +		$this->setResponseHeader('PageSize', $limit_parts[1], false); | |
| 576 | +		$this->setResponseHeader('TotalPages', ceil($pages), false); | |
| 577 | + } | |
| 578 | + | |
| 579 | + | |
| 580 | + /** | |
| 581 | + * Changes database results into REST API entities | |
| 582 | + * | |
| 583 | + * @param EEM_Base $model | |
| 584 | + * @param array $db_row like results from $wpdb->get_results() | |
| 585 | + * @param WP_REST_Request $rest_request | |
| 586 | + * @param string $deprecated no longer used | |
| 587 | + * @return array ready for being converted into json for sending to client | |
| 588 | + * @throws EE_Error | |
| 589 | + * @throws RestException | |
| 590 | + * @throws InvalidDataTypeException | |
| 591 | + * @throws InvalidInterfaceException | |
| 592 | + * @throws InvalidArgumentException | |
| 593 | + * @throws ReflectionException | |
| 594 | + */ | |
| 595 | + public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null) | |
| 596 | +	{ | |
| 597 | +		if (! $rest_request instanceof WP_REST_Request) { | |
| 598 | + // ok so this was called in the old style, where the 3rd arg was | |
| 599 | + // $include, and the 4th arg was $context | |
| 600 | + // now setup the request just to avoid fatal errors, although we won't be able | |
| 601 | + // to truly make use of it because it's kinda devoid of info | |
| 602 | + $rest_request = new WP_REST_Request(); | |
| 603 | +			$rest_request->set_param('include', $rest_request); | |
| 604 | +			$rest_request->set_param('caps', $deprecated); | |
| 605 | + } | |
| 606 | +		if ($rest_request->get_param('caps') == null) { | |
| 607 | +			$rest_request->set_param('caps', EEM_Base::caps_read); | |
| 608 | + } | |
| 609 | + $current_user_full_access_to_entity = $model->currentUserCan( | |
| 610 | + EEM_Base::caps_read_admin, | |
| 611 | + $model->deduce_fields_n_values_from_cols_n_values($db_row) | |
| 612 | + ); | |
| 613 | + $entity_array = $this->createBareEntityFromWpdbResults($model, $db_row); | |
| 614 | + $entity_array = $this->addExtraFields($model, $db_row, $entity_array); | |
| 615 | + $entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array); | |
| 616 | + // when it's a regular read request for a model with a password and the password wasn't provided | |
| 617 | + // remove the password protected fields | |
| 618 | + $has_protected_fields = false; | |
| 619 | +		try { | |
| 620 | + $this->checkPassword( | |
| 621 | + $model, | |
| 622 | + $db_row, | |
| 623 | + array( | |
| 624 | + 0 => array( | |
| 625 | + $model->primary_key_name() => $db_row[ $model->get_primary_key_field()->get_qualified_column() ] | |
| 626 | + ) | |
| 627 | + ), | |
| 628 | + $rest_request | |
| 629 | + ); | |
| 630 | +		} catch (RestPasswordRequiredException $e) { | |
| 631 | +			if ($model->hasPassword()) { | |
| 632 | + // just remove protected fields | |
| 633 | + $has_protected_fields = true; | |
| 634 | + $entity_array = Capabilities::filterOutPasswordProtectedFields( | |
| 635 | + $entity_array, | |
| 636 | + $model, | |
| 637 | + $this->getModelVersionInfo() | |
| 638 | + ); | |
| 639 | +			} else { | |
| 640 | + // that's a problem. None of this should be accessible if no password was provided | |
| 641 | + throw $e; | |
| 642 | + } | |
| 643 | + } | |
| 644 | + | |
| 645 | + $entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request, $has_protected_fields); | |
| 646 | + $entity_array = apply_filters( | |
| 647 | + 'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models', | |
| 648 | + $entity_array, | |
| 649 | + $model, | |
| 650 | +			$rest_request->get_param('caps'), | |
| 651 | + $rest_request, | |
| 652 | + $this | |
| 653 | + ); | |
| 654 | + // add an empty protected property for now. If it's still around after we remove everything the request didn't | |
| 655 | + // want, we'll populate it then. k? | |
| 656 | + $entity_array['_protected'] = array(); | |
| 657 | + // remove any properties the request didn't want. This way _protected won't bother mentioning them | |
| 658 | + $entity_array = $this->includeOnlyRequestedProperties($model, $rest_request, $entity_array); | |
| 659 | + $entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row, $has_protected_fields); | |
| 660 | + // if they still wanted the _protected property, add it. | |
| 661 | +		if (isset($entity_array['_protected'])) { | |
| 662 | + $entity_array = $this->addProtectedProperty($model, $entity_array, $has_protected_fields); | |
| 663 | + } | |
| 664 | + $entity_array = apply_filters( | |
| 665 | + 'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal', | |
| 666 | + $entity_array, | |
| 667 | + $model, | |
| 668 | +			$rest_request->get_param('caps'), | |
| 669 | + $rest_request, | |
| 670 | + $this | |
| 671 | + ); | |
| 672 | +		if (! $current_user_full_access_to_entity) { | |
| 673 | + $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields( | |
| 674 | + $entity_array, | |
| 675 | + $model, | |
| 676 | +				$rest_request->get_param('caps'), | |
| 677 | + $this->getModelVersionInfo() | |
| 678 | + ); | |
| 679 | +		} else { | |
| 680 | + $result_without_inaccessible_fields = $entity_array; | |
| 681 | + } | |
| 682 | + $this->setDebugInfo( | |
| 683 | + 'inaccessible fields', | |
| 684 | + array_keys(array_diff_key((array) $entity_array, (array) $result_without_inaccessible_fields)) | |
| 685 | + ); | |
| 686 | + return apply_filters( | |
| 687 | + 'FHEE__Read__create_entity_from_wpdb_results__entity_return', | |
| 688 | + $result_without_inaccessible_fields, | |
| 689 | + $model, | |
| 690 | +			$rest_request->get_param('caps') | |
| 691 | + ); | |
| 692 | + } | |
| 693 | + | |
| 694 | + /** | |
| 695 | + * Returns an array describing which fields can be protected, and which actually were removed this request | |
| 696 | + * @since 4.9.74.p | |
| 697 | + * @param $model | |
| 698 | + * @param $results_so_far | |
| 699 | + * @param $protected | |
| 700 | + * @return array results | |
| 701 | + */ | |
| 702 | + protected function addProtectedProperty(EEM_Base $model, $results_so_far, $protected) | |
| 703 | +	{ | |
| 704 | +		if (! $model->hasPassword() || ! $protected) { | |
| 705 | + return $results_so_far; | |
| 706 | + } | |
| 707 | + $password_field = $model->getPasswordField(); | |
| 708 | + $all_protected = array_merge( | |
| 709 | + array($password_field->get_name()), | |
| 710 | + $password_field->protectedFields() | |
| 711 | + ); | |
| 712 | + $fields_included = array_keys($results_so_far); | |
| 713 | + $fields_included = array_intersect( | |
| 714 | + $all_protected, | |
| 715 | + $fields_included | |
| 716 | + ); | |
| 717 | +		foreach ($fields_included as $field_name) { | |
| 718 | + $results_so_far['_protected'][] = $field_name ; | |
| 719 | + } | |
| 720 | + return $results_so_far; | |
| 721 | + } | |
| 722 | + | |
| 723 | + /** | |
| 724 | + * Creates a REST entity array (JSON object we're going to return in the response, but | |
| 725 | + * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry), | |
| 726 | + * from $wpdb->get_row( $sql, ARRAY_A) | |
| 727 | + * | |
| 728 | + * @param EEM_Base $model | |
| 729 | + * @param array $db_row | |
| 730 | + * @return array entity mostly ready for converting to JSON and sending in the response | |
| 731 | + */ | |
| 732 | + protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row) | |
| 733 | +	{ | |
| 734 | + $result = $model->deduce_fields_n_values_from_cols_n_values($db_row); | |
| 735 | + $result = array_intersect_key( | |
| 736 | + $result, | |
| 737 | + $this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) | |
| 738 | + ); | |
| 739 | + // if this is a CPT, we need to set the global $post to it, | |
| 740 | + // otherwise shortcodes etc won't work properly while rendering it | |
| 741 | +		if ($model instanceof \EEM_CPT_Base) { | |
| 742 | + $do_chevy_shuffle = true; | |
| 743 | +		} else { | |
| 744 | + $do_chevy_shuffle = false; | |
| 745 | + } | |
| 746 | +		if ($do_chevy_shuffle) { | |
| 747 | + global $post; | |
| 748 | + $old_post = $post; | |
| 749 | + $post = get_post($result[ $model->primary_key_name() ]); | |
| 750 | +			if (! $post instanceof \WP_Post) { | |
| 751 | + // well that's weird, because $result is what we JUST fetched from the database | |
| 752 | + throw new RestException( | |
| 753 | + 'error_fetching_post_from_database_results', | |
| 754 | + esc_html__( | |
| 755 | + 'An item was retrieved from the database but it\'s not a WP_Post like it should be.', | |
| 756 | + 'event_espresso' | |
| 757 | + ) | |
| 758 | + ); | |
| 759 | + } | |
| 760 | + $model_object_classname = 'EE_' . $model->get_this_model_name(); | |
| 761 | +			$post->{$model_object_classname} = \EE_Registry::instance()->load_class( | |
| 762 | + $model_object_classname, | |
| 763 | + $result, | |
| 764 | + false, | |
| 765 | + false | |
| 766 | + ); | |
| 767 | + } | |
| 768 | +		foreach ($result as $field_name => $field_value) { | |
| 769 | + $field_obj = $model->field_settings_for($field_name); | |
| 770 | +			if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) { | |
| 771 | + unset($result[ $field_name ]); | |
| 772 | + } elseif ($this->isSubclassOfOne( | |
| 773 | + $field_obj, | |
| 774 | + $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat() | |
| 775 | + ) | |
| 776 | +			) { | |
| 777 | + $result[ $field_name ] = array( | |
| 778 | + 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | |
| 779 | + 'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | |
| 780 | + ); | |
| 781 | + } elseif ($this->isSubclassOfOne( | |
| 782 | + $field_obj, | |
| 783 | + $this->getModelVersionInfo()->fieldsThatHavePrettyFormat() | |
| 784 | + ) | |
| 785 | +			) { | |
| 786 | + $result[ $field_name ] = array( | |
| 787 | + 'raw' => $this->prepareFieldObjValueForJson($field_obj, $field_value), | |
| 788 | + 'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'), | |
| 789 | + ); | |
| 790 | +			} elseif ($field_obj instanceof \EE_Datetime_Field) { | |
| 791 | + $field_value = $field_obj->prepare_for_set_from_db($field_value); | |
| 792 | + // if the value is null, but we're not supposed to permit null, then set to the field's default | |
| 793 | +				if (is_null($field_value)) { | |
| 794 | + $field_value = $field_obj->getDefaultDateTimeObj(); | |
| 795 | + } | |
| 796 | +				if (is_null($field_value)) { | |
| 797 | + $gmt_date = $local_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 798 | + $field_obj, | |
| 799 | + $field_value, | |
| 800 | + $this->getModelVersionInfo()->requestedVersion() | |
| 801 | + ); | |
| 802 | +				} else { | |
| 803 | + $timezone = $field_value->getTimezone(); | |
| 804 | +					EEH_DTT_Helper::setTimezone($field_value, new DateTimeZone('UTC')); | |
| 805 | + $gmt_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 806 | + $field_obj, | |
| 807 | + $field_value, | |
| 808 | + $this->getModelVersionInfo()->requestedVersion() | |
| 809 | + ); | |
| 810 | + EEH_DTT_Helper::setTimezone($field_value, $timezone); | |
| 811 | + $local_date = ModelDataTranslator::prepareFieldValuesForJson( | |
| 812 | + $field_obj, | |
| 813 | + $field_value, | |
| 814 | + $this->getModelVersionInfo()->requestedVersion() | |
| 815 | + ); | |
| 816 | + } | |
| 817 | + $result[ $field_name . '_gmt' ] = $gmt_date; | |
| 818 | + $result[ $field_name ] = $local_date; | |
| 819 | +			} else { | |
| 820 | + $result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value); | |
| 821 | + } | |
| 822 | + } | |
| 823 | +		if ($do_chevy_shuffle) { | |
| 824 | + $post = $old_post; | |
| 825 | + } | |
| 826 | + return $result; | |
| 827 | + } | |
| 828 | + | |
| 829 | + | |
| 830 | + /** | |
| 831 | + * Takes a value all the way from the DB representation, to the model object's representation, to the | |
| 832 | + * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB | |
| 833 | + * representation using $field_obj->prepare_for_set_from_db()) | |
| 834 | + * | |
| 835 | + * @param EE_Model_Field_Base $field_obj | |
| 836 | + * @param mixed $value as it's stored on a model object | |
| 837 | + * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj' | |
| 838 | + * @return mixed | |
| 839 | + * @throws ObjectDetectedException if $value contains a PHP object | |
| 840 | + */ | |
| 841 | + protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal') | |
| 842 | +	{ | |
| 843 | + $value = $field_obj->prepare_for_set_from_db($value); | |
| 844 | +		switch ($format) { | |
| 845 | + case 'pretty': | |
| 846 | + $value = $field_obj->prepare_for_pretty_echoing($value); | |
| 847 | + break; | |
| 848 | + case 'normal': | |
| 849 | + default: | |
| 850 | + $value = $field_obj->prepare_for_get($value); | |
| 851 | + break; | |
| 852 | + } | |
| 853 | + return ModelDataTranslator::prepareFieldValuesForJson( | |
| 854 | + $field_obj, | |
| 855 | + $value, | |
| 856 | + $this->getModelVersionInfo()->requestedVersion() | |
| 857 | + ); | |
| 858 | + } | |
| 859 | + | |
| 860 | + | |
| 861 | + /** | |
| 862 | + * Adds a few extra fields to the entity response | |
| 863 | + * | |
| 864 | + * @param EEM_Base $model | |
| 865 | + * @param array $db_row | |
| 866 | + * @param array $entity_array | |
| 867 | + * @return array modified entity | |
| 868 | + */ | |
| 869 | + protected function addExtraFields(EEM_Base $model, $db_row, $entity_array) | |
| 870 | +	{ | |
| 871 | +		if ($model instanceof EEM_CPT_Base) { | |
| 872 | + $entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]); | |
| 873 | + } | |
| 874 | + return $entity_array; | |
| 875 | + } | |
| 876 | + | |
| 877 | + | |
| 878 | + /** | |
| 879 | + * Gets links we want to add to the response | |
| 880 | + * | |
| 881 | + * @global \WP_REST_Server $wp_rest_server | |
| 882 | + * @param EEM_Base $model | |
| 883 | + * @param array $db_row | |
| 884 | + * @param array $entity_array | |
| 885 | + * @return array the _links item in the entity | |
| 886 | + */ | |
| 887 | + protected function getEntityLinks($model, $db_row, $entity_array) | |
| 888 | +	{ | |
| 889 | + // add basic links | |
| 890 | + $links = array(); | |
| 891 | +		if ($model->has_primary_key_field()) { | |
| 892 | + $links['self'] = array( | |
| 893 | + array( | |
| 894 | + 'href' => $this->getVersionedLinkTo( | |
| 895 | + EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 896 | + . '/' | |
| 897 | + . $entity_array[ $model->primary_key_name() ] | |
| 898 | + ), | |
| 899 | + ), | |
| 900 | + ); | |
| 901 | + } | |
| 902 | + $links['collection'] = array( | |
| 903 | + array( | |
| 904 | + 'href' => $this->getVersionedLinkTo( | |
| 905 | + EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 906 | + ), | |
| 907 | + ), | |
| 908 | + ); | |
| 909 | + // add links to related models | |
| 910 | +		if ($model->has_primary_key_field()) { | |
| 911 | +			foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) { | |
| 912 | + $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj); | |
| 913 | + $links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array( | |
| 914 | + array( | |
| 915 | + 'href' => $this->getVersionedLinkTo( | |
| 916 | + EEH_Inflector::pluralize_and_lower($model->get_this_model_name()) | |
| 917 | + . '/' | |
| 918 | + . $entity_array[ $model->primary_key_name() ] | |
| 919 | + . '/' | |
| 920 | + . $related_model_part | |
| 921 | + ), | |
| 922 | + 'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false, | |
| 923 | + ), | |
| 924 | + ); | |
| 925 | + } | |
| 926 | + } | |
| 927 | + return $links; | |
| 928 | + } | |
| 929 | + | |
| 930 | + | |
| 931 | + /** | |
| 932 | + * Adds the included models indicated in the request to the entity provided | |
| 933 | + * | |
| 934 | + * @param EEM_Base $model | |
| 935 | + * @param WP_REST_Request $rest_request | |
| 936 | + * @param array $entity_array | |
| 937 | + * @param array $db_row | |
| 938 | + * @param boolean $included_items_protected if the original item is password protected, don't include any related models. | |
| 939 | + * @return array the modified entity | |
| 940 | + * @throws RestException | |
| 941 | + */ | |
| 942 | + protected function includeRequestedModels( | |
| 943 | + EEM_Base $model, | |
| 944 | + WP_REST_Request $rest_request, | |
| 945 | + $entity_array, | |
| 946 | + $db_row = array(), | |
| 947 | + $included_items_protected = false | |
| 948 | +	) { | |
| 949 | + // if $db_row not included, hope the entity array has what we need | |
| 950 | +		if (! $db_row) { | |
| 951 | + $db_row = $entity_array; | |
| 952 | + } | |
| 953 | + $relation_settings = $this->getModelVersionInfo()->relationSettings($model); | |
| 954 | +		foreach ($relation_settings as $relation_name => $relation_obj) { | |
| 955 | + $related_fields_to_include = $this->explodeAndGetItemsPrefixedWith( | |
| 956 | +				$rest_request->get_param('include'), | |
| 957 | + $relation_name | |
| 958 | + ); | |
| 959 | + $related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith( | |
| 960 | +				$rest_request->get_param('calculate'), | |
| 961 | + $relation_name | |
| 962 | + ); | |
| 963 | + // did they specify they wanted to include a related model, or | |
| 964 | + // specific fields from a related model? | |
| 965 | + // or did they specify to calculate a field from a related model? | |
| 966 | +			if ($related_fields_to_include || $related_fields_to_calculate) { | |
| 967 | + // if so, we should include at least some part of the related model | |
| 968 | + $pretend_related_request = new WP_REST_Request(); | |
| 969 | + $pretend_related_request->set_query_params( | |
| 970 | + array( | |
| 971 | +						'caps'      => $rest_request->get_param('caps'), | |
| 972 | + 'include' => $related_fields_to_include, | |
| 973 | + 'calculate' => $related_fields_to_calculate, | |
| 974 | +						'password' => $rest_request->get_param('password') | |
| 975 | + ) | |
| 976 | + ); | |
| 977 | +				$pretend_related_request->add_header('no_rest_headers', true); | |
| 978 | + $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID( | |
| 979 | + $model->get_index_primary_key_string( | |
| 980 | + $model->deduce_fields_n_values_from_cols_n_values($db_row) | |
| 981 | + ) | |
| 982 | + ); | |
| 983 | +				if (! $included_items_protected) { | |
| 984 | + $related_results = $this->getEntitiesFromRelationUsingModelQueryParams( | |
| 985 | + $primary_model_query_params, | |
| 986 | + $relation_obj, | |
| 987 | + $pretend_related_request | |
| 988 | + ); | |
| 989 | +				} else { | |
| 990 | + // they're protected, hide them. | |
| 991 | + $related_results = $relation_obj instanceof EE_Belongs_To_Relation ? null : array(); | |
| 992 | + $entity_array['_protected'][] = Read::getRelatedEntityName($relation_name, $relation_obj); | |
| 993 | + } | |
| 994 | +				if ($related_results instanceof WP_Error) { | |
| 995 | + $related_results = null; | |
| 996 | + } | |
| 997 | + $entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results; | |
| 998 | + } | |
| 999 | + } | |
| 1000 | + return $entity_array; | |
| 1001 | + } | |
| 1002 | + | |
| 1003 | + /** | |
| 1004 | + * If the user has requested only specific properties (including meta properties like _links or _protected) | |
| 1005 | + * remove everything else. | |
| 1006 | + * @since 4.9.74.p | |
| 1007 | + * @param EEM_Base $model | |
| 1008 | + * @param WP_REST_Request $rest_request | |
| 1009 | + * @param $entity_array | |
| 1010 | + * @return array | |
| 1011 | + * @throws EE_Error | |
| 1012 | + */ | |
| 1013 | + protected function includeOnlyRequestedProperties( | |
| 1014 | + EEM_Base $model, | |
| 1015 | + WP_REST_Request $rest_request, | |
| 1016 | + $entity_array | |
| 1017 | +	) { | |
| 1018 | + | |
| 1019 | +		$includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), ''); | |
| 1020 | + $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model); | |
| 1021 | + // if they passed in * or didn't specify any includes, return everything | |
| 1022 | +		if (! in_array('*', $includes_for_this_model) | |
| 1023 | + && ! empty($includes_for_this_model) | |
| 1024 | +		) { | |
| 1025 | +			if ($model->has_primary_key_field()) { | |
| 1026 | + // always include the primary key. ya just gotta know that at least | |
| 1027 | + $includes_for_this_model[] = $model->primary_key_name(); | |
| 1028 | + } | |
| 1029 | +			if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) { | |
| 1030 | + $includes_for_this_model[] = '_calculated_fields'; | |
| 1031 | + } | |
| 1032 | + $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model)); | |
| 1033 | + } | |
| 1034 | + return $entity_array; | |
| 1035 | + } | |
| 1036 | + | |
| 1037 | + | |
| 1038 | + /** | |
| 1039 | + * Returns a new array with all the names of models removed. Eg | |
| 1040 | + * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' ) | |
| 1041 | + * | |
| 1042 | + * @param array $arr | |
| 1043 | + * @return array | |
| 1044 | + */ | |
| 1045 | + private function removeModelNamesFromArray($arr) | |
| 1046 | +	{ | |
| 1047 | + return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models)); | |
| 1048 | + } | |
| 1049 | + | |
| 1050 | + | |
| 1051 | + /** | |
| 1052 | + * Gets the calculated fields for the response | |
| 1053 | + * | |
| 1054 | + * @param EEM_Base $model | |
| 1055 | + * @param array $wpdb_row | |
| 1056 | + * @param WP_REST_Request $rest_request | |
| 1057 | + * @param boolean $row_is_protected whether this row is password protected or not | |
| 1058 | + * @return \stdClass the _calculations item in the entity | |
| 1059 | + * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we | |
| 1060 | + * did, let's know about it ASAP, so let the exception bubble up) | |
| 1061 | + */ | |
| 1062 | + protected function getEntityCalculations($model, $wpdb_row, $rest_request, $row_is_protected = false) | |
| 1063 | +	{ | |
| 1064 | + $calculated_fields = $this->explodeAndGetItemsPrefixedWith( | |
| 1065 | +			$rest_request->get_param('calculate'), | |
| 1066 | + '' | |
| 1067 | + ); | |
| 1068 | + // note: setting calculate=* doesn't do anything | |
| 1069 | + $calculated_fields_to_return = new \stdClass(); | |
| 1070 | + $protected_fields = array(); | |
| 1071 | +		foreach ($calculated_fields as $field_to_calculate) { | |
| 1072 | +			try { | |
| 1073 | + // it's password protected, so they shouldn't be able to read this. Remove the value | |
| 1074 | + $schema = $this->fields_calculator->getJsonSchemaForModel($model); | |
| 1075 | + if ($row_is_protected | |
| 1076 | + && isset($schema['properties'][ $field_to_calculate ]['protected']) | |
| 1077 | +					&& $schema['properties'][ $field_to_calculate ]['protected']) { | |
| 1078 | + $calculated_value = null; | |
| 1079 | + $protected_fields[] = $field_to_calculate; | |
| 1080 | +					if ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1081 | +						switch ($schema['properties'][ $field_to_calculate ]['type']) { | |
| 1082 | + case 'boolean': | |
| 1083 | + $calculated_value = false; | |
| 1084 | + break; | |
| 1085 | + case 'integer': | |
| 1086 | + $calculated_value = 0; | |
| 1087 | + break; | |
| 1088 | + case 'string': | |
| 1089 | + $calculated_value = ''; | |
| 1090 | + break; | |
| 1091 | + case 'array': | |
| 1092 | + $calculated_value = array(); | |
| 1093 | + break; | |
| 1094 | + case 'object': | |
| 1095 | + $calculated_value = new stdClass(); | |
| 1096 | + break; | |
| 1097 | + } | |
| 1098 | + } | |
| 1099 | +				} else { | |
| 1100 | + $calculated_value = ModelDataTranslator::prepareFieldValueForJson( | |
| 1101 | + null, | |
| 1102 | + $this->fields_calculator->retrieveCalculatedFieldValue( | |
| 1103 | + $model, | |
| 1104 | + $field_to_calculate, | |
| 1105 | + $wpdb_row, | |
| 1106 | + $rest_request, | |
| 1107 | + $this | |
| 1108 | + ), | |
| 1109 | + $this->getModelVersionInfo()->requestedVersion() | |
| 1110 | + ); | |
| 1111 | + } | |
| 1112 | +				$calculated_fields_to_return->{$field_to_calculate} = $calculated_value; | |
| 1113 | +			} catch (RestException $e) { | |
| 1114 | + // if we don't have permission to read it, just leave it out. but let devs know about the problem | |
| 1115 | + $this->setResponseHeader( | |
| 1116 | + 'Notices-Field-Calculation-Errors[' | |
| 1117 | + . $e->getStringCode() | |
| 1118 | + . '][' | |
| 1119 | + . $model->get_this_model_name() | |
| 1120 | + . '][' | |
| 1121 | + . $field_to_calculate | |
| 1122 | + . ']', | |
| 1123 | + $e->getMessage(), | |
| 1124 | + true | |
| 1125 | + ); | |
| 1126 | + } | |
| 1127 | + } | |
| 1128 | + $calculated_fields_to_return->_protected = $protected_fields; | |
| 1129 | + return $calculated_fields_to_return; | |
| 1130 | + } | |
| 1131 | + | |
| 1132 | + | |
| 1133 | + /** | |
| 1134 | + * Gets the full URL to the resource, taking the requested version into account | |
| 1135 | + * | |
| 1136 | + * @param string $link_part_after_version_and_slash eg "events/10/datetimes" | |
| 1137 | + * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes" | |
| 1138 | + */ | |
| 1139 | + public function getVersionedLinkTo($link_part_after_version_and_slash) | |
| 1140 | +	{ | |
| 1141 | + return rest_url( | |
| 1142 | + EED_Core_Rest_Api::get_versioned_route_to( | |
| 1143 | + $link_part_after_version_and_slash, | |
| 1144 | + $this->getModelVersionInfo()->requestedVersion() | |
| 1145 | + ) | |
| 1146 | + ); | |
| 1147 | + } | |
| 1148 | + | |
| 1149 | + | |
| 1150 | + /** | |
| 1151 | + * Gets the correct lowercase name for the relation in the API according | |
| 1152 | + * to the relation's type | |
| 1153 | + * | |
| 1154 | + * @param string $relation_name | |
| 1155 | + * @param \EE_Model_Relation_Base $relation_obj | |
| 1156 | + * @return string | |
| 1157 | + */ | |
| 1158 | + public static function getRelatedEntityName($relation_name, $relation_obj) | |
| 1159 | +	{ | |
| 1160 | +		if ($relation_obj instanceof EE_Belongs_To_Relation) { | |
| 1161 | + return strtolower($relation_name); | |
| 1162 | +		} else { | |
| 1163 | + return EEH_Inflector::pluralize_and_lower($relation_name); | |
| 1164 | + } | |
| 1165 | + } | |
| 1166 | + | |
| 1167 | + | |
| 1168 | + /** | |
| 1169 | + * Gets the one model object with the specified id for the specified model | |
| 1170 | + * | |
| 1171 | + * @param EEM_Base $model | |
| 1172 | + * @param WP_REST_Request $request | |
| 1173 | + * @return array | |
| 1174 | + */ | |
| 1175 | + public function getEntityFromModel($model, $request) | |
| 1176 | +	{ | |
| 1177 | +		$context = $this->validateContext($request->get_param('caps')); | |
| 1178 | + return $this->getOneOrReportPermissionError($model, $request, $context); | |
| 1179 | + } | |
| 1180 | + | |
| 1181 | + | |
| 1182 | + /** | |
| 1183 | + * If a context is provided which isn't valid, maybe it was added in a future | |
| 1184 | + * version so just treat it as a default read | |
| 1185 | + * | |
| 1186 | + * @param string $context | |
| 1187 | + * @return string array key of EEM_Base::cap_contexts_to_cap_action_map() | |
| 1188 | + */ | |
| 1189 | + public function validateContext($context) | |
| 1190 | +	{ | |
| 1191 | +		if (! $context) { | |
| 1192 | + $context = EEM_Base::caps_read; | |
| 1193 | + } | |
| 1194 | + $valid_contexts = EEM_Base::valid_cap_contexts(); | |
| 1195 | +		if (in_array($context, $valid_contexts)) { | |
| 1196 | + return $context; | |
| 1197 | +		} else { | |
| 1198 | + return EEM_Base::caps_read; | |
| 1199 | + } | |
| 1200 | + } | |
| 1201 | + | |
| 1202 | + | |
| 1203 | + /** | |
| 1204 | + * Verifies the passed in value is an allowable default where conditions value. | |
| 1205 | + * | |
| 1206 | + * @param $default_query_params | |
| 1207 | + * @return string | |
| 1208 | + */ | |
| 1209 | + public function validateDefaultQueryParams($default_query_params) | |
| 1210 | +	{ | |
| 1211 | + $valid_default_where_conditions_for_api_calls = array( | |
| 1212 | + EEM_Base::default_where_conditions_all, | |
| 1213 | + EEM_Base::default_where_conditions_minimum_all, | |
| 1214 | + EEM_Base::default_where_conditions_minimum_others, | |
| 1215 | + ); | |
| 1216 | +		if (! $default_query_params) { | |
| 1217 | + $default_query_params = EEM_Base::default_where_conditions_all; | |
| 1218 | + } | |
| 1219 | + if (in_array( | |
| 1220 | + $default_query_params, | |
| 1221 | + $valid_default_where_conditions_for_api_calls, | |
| 1222 | + true | |
| 1223 | +		)) { | |
| 1224 | + return $default_query_params; | |
| 1225 | +		} else { | |
| 1226 | + return EEM_Base::default_where_conditions_all; | |
| 1227 | + } | |
| 1228 | + } | |
| 1229 | + | |
| 1230 | + | |
| 1231 | + /** | |
| 1232 | + * Translates API filter get parameter into model query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions. | |
| 1233 | + * Note: right now the query parameter keys for fields (and related fields) | |
| 1234 | + * can be left as-is, but it's quite possible this will change someday. | |
| 1235 | + * Also, this method's contents might be candidate for moving to Model_Data_Translator | |
| 1236 | + * | |
| 1237 | + * @param EEM_Base $model | |
| 1238 | + * @param array $query_parameters from $_GET parameter @see Read:handle_request_get_all | |
| 1239 | + * @return array model query params (@see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions) | |
| 1240 | + * or FALSE to indicate that absolutely no results should be returned | |
| 1241 | + * @throws EE_Error | |
| 1242 | + * @throws RestException | |
| 1243 | + */ | |
| 1244 | + public function createModelQueryParams($model, $query_params) | |
| 1245 | +	{ | |
| 1246 | + $model_query_params = array(); | |
| 1247 | +		if (isset($query_params['where'])) { | |
| 1248 | + $model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 1249 | + $query_params['where'], | |
| 1250 | + $model, | |
| 1251 | + $this->getModelVersionInfo()->requestedVersion() | |
| 1252 | + ); | |
| 1253 | + } | |
| 1254 | +		if (isset($query_params['order_by'])) { | |
| 1255 | + $order_by = $query_params['order_by']; | |
| 1256 | +		} elseif (isset($query_params['orderby'])) { | |
| 1257 | + $order_by = $query_params['orderby']; | |
| 1258 | +		} else { | |
| 1259 | + $order_by = null; | |
| 1260 | + } | |
| 1261 | +		if ($order_by !== null) { | |
| 1262 | +			if (is_array($order_by)) { | |
| 1263 | + $order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by); | |
| 1264 | +			} else { | |
| 1265 | + // it's a single item | |
| 1266 | + $order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by); | |
| 1267 | + } | |
| 1268 | + $model_query_params['order_by'] = $order_by; | |
| 1269 | + } | |
| 1270 | +		if (isset($query_params['group_by'])) { | |
| 1271 | + $group_by = $query_params['group_by']; | |
| 1272 | +		} elseif (isset($query_params['groupby'])) { | |
| 1273 | + $group_by = $query_params['groupby']; | |
| 1274 | +		} else { | |
| 1275 | + $group_by = array_keys($model->get_combined_primary_key_fields()); | |
| 1276 | + } | |
| 1277 | + // make sure they're all real names | |
| 1278 | +		if (is_array($group_by)) { | |
| 1279 | + $group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by); | |
| 1280 | + } | |
| 1281 | +		if ($group_by !== null) { | |
| 1282 | + $model_query_params['group_by'] = $group_by; | |
| 1283 | + } | |
| 1284 | +		if (isset($query_params['having'])) { | |
| 1285 | + $model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels( | |
| 1286 | + $query_params['having'], | |
| 1287 | + $model, | |
| 1288 | + $this->getModelVersionInfo()->requestedVersion() | |
| 1289 | + ); | |
| 1290 | + } | |
| 1291 | +		if (isset($query_params['order'])) { | |
| 1292 | + $model_query_params['order'] = $query_params['order']; | |
| 1293 | + } | |
| 1294 | +		if (isset($query_params['mine'])) { | |
| 1295 | + $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params); | |
| 1296 | + } | |
| 1297 | +		if (isset($query_params['limit'])) { | |
| 1298 | + // limit should be either a string like '23' or '23,43', or an array with two items in it | |
| 1299 | +			if (! is_array($query_params['limit'])) { | |
| 1300 | +				$limit_array = explode(',', (string) $query_params['limit']); | |
| 1301 | +			} else { | |
| 1302 | + $limit_array = $query_params['limit']; | |
| 1303 | + } | |
| 1304 | + $sanitized_limit = array(); | |
| 1305 | +			foreach ($limit_array as $key => $limit_part) { | |
| 1306 | +				if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) { | |
| 1307 | + throw new EE_Error( | |
| 1308 | + sprintf( | |
| 1309 | + __( | |
| 1310 | + // @codingStandardsIgnoreStart | |
| 1311 | + 'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.', | |
| 1312 | + // @codingStandardsIgnoreEnd | |
| 1313 | + 'event_espresso' | |
| 1314 | + ), | |
| 1315 | + wp_json_encode($query_params['limit']) | |
| 1316 | + ) | |
| 1317 | + ); | |
| 1318 | + } | |
| 1319 | + $sanitized_limit[] = (int) $limit_part; | |
| 1320 | + } | |
| 1321 | +			$model_query_params['limit'] = implode(',', $sanitized_limit); | |
| 1322 | +		} else { | |
| 1323 | + $model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit(); | |
| 1324 | + } | |
| 1325 | +		if (isset($query_params['caps'])) { | |
| 1326 | + $model_query_params['caps'] = $this->validateContext($query_params['caps']); | |
| 1327 | +		} else { | |
| 1328 | + $model_query_params['caps'] = EEM_Base::caps_read; | |
| 1329 | + } | |
| 1330 | +		if (isset($query_params['default_where_conditions'])) { | |
| 1331 | + $model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams( | |
| 1332 | + $query_params['default_where_conditions'] | |
| 1333 | + ); | |
| 1334 | + } | |
| 1335 | + // if this is a model protected by a password on another model, exclude the password protected | |
| 1336 | + // entities by default. But if they passed in a password, try to show them all. If the password is wrong, | |
| 1337 | + // though, they'll get an error (see Read::createEntityFromWpdbResult() which calls Read::checkPassword) | |
| 1338 | + if (! $model->hasPassword() | |
| 1339 | + && $model->restrictedByRelatedModelPassword() | |
| 1340 | +			&& $model_query_params['caps'] === EEM_Base::caps_read) { | |
| 1341 | +			if (empty($query_params['password'])) { | |
| 1342 | + $model_query_params['exclude_protected'] = true; | |
| 1343 | + } | |
| 1344 | + } | |
| 1345 | + | |
| 1346 | +		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_params, $model); | |
| 1347 | + } | |
| 1348 | + | |
| 1349 | + | |
| 1350 | + /** | |
| 1351 | + * Changes the REST-style query params for use in the models | |
| 1352 | + * | |
| 1353 | + * @deprecated | |
| 1354 | + * @param EEM_Base $model | |
| 1355 | + * @param array $query_params sub-array from @see EEM_Base::get_all() | |
| 1356 | + * @return array | |
| 1357 | + */ | |
| 1358 | + public function prepareRestQueryParamsKeyForModels($model, $query_params) | |
| 1359 | +	{ | |
| 1360 | + $model_ready_query_params = array(); | |
| 1361 | +		foreach ($query_params as $key => $value) { | |
| 1362 | +			if (is_array($value)) { | |
| 1363 | + $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value); | |
| 1364 | +			} else { | |
| 1365 | + $model_ready_query_params[ $key ] = $value; | |
| 1366 | + } | |
| 1367 | + } | |
| 1368 | + return $model_ready_query_params; | |
| 1369 | + } | |
| 1370 | + | |
| 1371 | + | |
| 1372 | + /** | |
| 1373 | + * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson() | |
| 1374 | + * @param $model | |
| 1375 | + * @param $query_params | |
| 1376 | + * @return array | |
| 1377 | + */ | |
| 1378 | + public function prepareRestQueryParamsValuesForModels($model, $query_params) | |
| 1379 | +	{ | |
| 1380 | + $model_ready_query_params = array(); | |
| 1381 | +		foreach ($query_params as $key => $value) { | |
| 1382 | +			if (is_array($value)) { | |
| 1383 | + $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value); | |
| 1384 | +			} else { | |
| 1385 | + $model_ready_query_params[ $key ] = $value; | |
| 1386 | + } | |
| 1387 | + } | |
| 1388 | + return $model_ready_query_params; | |
| 1389 | + } | |
| 1390 | + | |
| 1391 | + | |
| 1392 | + /** | |
| 1393 | + * Explodes the string on commas, and only returns items with $prefix followed by a period. | |
| 1394 | + * If no prefix is specified, returns items with no period. | |
| 1395 | + * | |
| 1396 | +	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' ) | |
| 1397 | + * @param string $prefix "Event" or "foobar" | |
| 1398 | + * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified | |
| 1399 | + * we only return strings starting with that and a period; if no prefix was | |
| 1400 | + * specified we return all items containing NO periods | |
| 1401 | + */ | |
| 1402 | + public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix) | |
| 1403 | +	{ | |
| 1404 | +		if (is_string($string_to_explode)) { | |
| 1405 | +			$exploded_contents = explode(',', $string_to_explode); | |
| 1406 | +		} elseif (is_array($string_to_explode)) { | |
| 1407 | + $exploded_contents = $string_to_explode; | |
| 1408 | +		} else { | |
| 1409 | + $exploded_contents = array(); | |
| 1410 | + } | |
| 1411 | + // if the string was empty, we want an empty array | |
| 1412 | + $exploded_contents = array_filter($exploded_contents); | |
| 1413 | + $contents_with_prefix = array(); | |
| 1414 | +		foreach ($exploded_contents as $item) { | |
| 1415 | + $item = trim($item); | |
| 1416 | + // if no prefix was provided, so we look for items with no "." in them | |
| 1417 | +			if (! $prefix) { | |
| 1418 | + // does this item have a period? | |
| 1419 | +				if (strpos($item, '.') === false) { | |
| 1420 | + // if not, then its what we're looking for | |
| 1421 | + $contents_with_prefix[] = $item; | |
| 1422 | + } | |
| 1423 | +			} elseif (strpos($item, $prefix . '.') === 0) { | |
| 1424 | + // this item has the prefix and a period, grab it | |
| 1425 | + $contents_with_prefix[] = substr( | |
| 1426 | + $item, | |
| 1427 | + strpos($item, $prefix . '.') + strlen($prefix . '.') | |
| 1428 | + ); | |
| 1429 | +			} elseif ($item === $prefix) { | |
| 1430 | + // this item is JUST the prefix | |
| 1431 | + // so let's grab everything after, which is a blank string | |
| 1432 | + $contents_with_prefix[] = ''; | |
| 1433 | + } | |
| 1434 | + } | |
| 1435 | + return $contents_with_prefix; | |
| 1436 | + } | |
| 1437 | + | |
| 1438 | + | |
| 1439 | + /** | |
| 1440 | + * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with. | |
| 1441 | + * Deprecated because its return values were really quite confusing- sometimes it returned | |
| 1442 | + * an empty array (when the include string was blank or '*') or sometimes it returned | |
| 1443 | +	 * array('*') (when you provided a model and a model of that kind was found). | |
| 1444 | + * Parses the $include_string so we fetch all the field names relating to THIS model | |
| 1445 | + * (ie have NO period in them), or for the provided model (ie start with the model | |
| 1446 | + * name and then a period). | |
| 1447 | + * @param string $include_string @see Read:handle_request_get_all | |
| 1448 | + * @param string $model_name | |
| 1449 | + * @return array of fields for this model. If $model_name is provided, then | |
| 1450 | + * the fields for that model, with the model's name removed from each. | |
| 1451 | + * If $include_string was blank or '*' returns an empty array | |
| 1452 | + */ | |
| 1453 | + public function extractIncludesForThisModel($include_string, $model_name = null) | |
| 1454 | +	{ | |
| 1455 | +		if (is_array($include_string)) { | |
| 1456 | +			$include_string = implode(',', $include_string); | |
| 1457 | + } | |
| 1458 | +		if ($include_string === '*' || $include_string === '') { | |
| 1459 | + return array(); | |
| 1460 | + } | |
| 1461 | +		$includes = explode(',', $include_string); | |
| 1462 | + $extracted_fields_to_include = array(); | |
| 1463 | +		if ($model_name) { | |
| 1464 | +			foreach ($includes as $field_to_include) { | |
| 1465 | + $field_to_include = trim($field_to_include); | |
| 1466 | +				if (strpos($field_to_include, $model_name . '.') === 0) { | |
| 1467 | + // found the model name at the exact start | |
| 1468 | + $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include); | |
| 1469 | + $extracted_fields_to_include[] = $field_sans_model_name; | |
| 1470 | +				} elseif ($field_to_include == $model_name) { | |
| 1471 | + $extracted_fields_to_include[] = '*'; | |
| 1472 | + } | |
| 1473 | + } | |
| 1474 | +		} else { | |
| 1475 | + // look for ones with no period | |
| 1476 | +			foreach ($includes as $field_to_include) { | |
| 1477 | + $field_to_include = trim($field_to_include); | |
| 1478 | + if (strpos($field_to_include, '.') === false | |
| 1479 | + && ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include) | |
| 1480 | +				) { | |
| 1481 | + $extracted_fields_to_include[] = $field_to_include; | |
| 1482 | + } | |
| 1483 | + } | |
| 1484 | + } | |
| 1485 | + return $extracted_fields_to_include; | |
| 1486 | + } | |
| 1487 | + | |
| 1488 | + | |
| 1489 | + /** | |
| 1490 | + * Gets the single item using the model according to the request in the context given, otherwise | |
| 1491 | + * returns that it's inaccessible to the current user | |
| 1492 | + * | |
| 1493 | + * @param EEM_Base $model | |
| 1494 | + * @param WP_REST_Request $request | |
| 1495 | + * @param null $context | |
| 1496 | + * @return array | |
| 1497 | + * @throws EE_Error | |
| 1498 | + */ | |
| 1499 | + public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null) | |
| 1500 | +	{ | |
| 1501 | +		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1); | |
| 1502 | +		if ($model instanceof EEM_Soft_Delete_Base) { | |
| 1503 | + $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params); | |
| 1504 | + } | |
| 1505 | + $restricted_query_params = $query_params; | |
| 1506 | + $restricted_query_params['caps'] = $context; | |
| 1507 | +		$this->setDebugInfo('model query params', $restricted_query_params); | |
| 1508 | + $model_rows = $model->get_all_wpdb_results($restricted_query_params); | |
| 1509 | +		if (! empty($model_rows)) { | |
| 1510 | + return $this->createEntityFromWpdbResult( | |
| 1511 | + $model, | |
| 1512 | + reset($model_rows), | |
| 1513 | + $request | |
| 1514 | + ); | |
| 1515 | +		} else { | |
| 1516 | + // ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities | |
| 1517 | + $lowercase_model_name = strtolower($model->get_this_model_name()); | |
| 1518 | +			if ($model->exists($query_params)) { | |
| 1519 | + // you got shafted- it existed but we didn't want to tell you! | |
| 1520 | + throw new RestException( | |
| 1521 | + 'rest_user_cannot_' . $context, | |
| 1522 | + sprintf( | |
| 1523 | +						__('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'), | |
| 1524 | + $context, | |
| 1525 | + $lowercase_model_name, | |
| 1526 | + Capabilities::getMissingPermissionsString( | |
| 1527 | + $model, | |
| 1528 | + $context | |
| 1529 | + ) | |
| 1530 | + ), | |
| 1531 | +					array('status' => 403) | |
| 1532 | + ); | |
| 1533 | +			} else { | |
| 1534 | + // it's not you. It just doesn't exist | |
| 1535 | + throw new RestException( | |
| 1536 | +					sprintf('rest_%s_invalid_id', $lowercase_model_name), | |
| 1537 | +					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name), | |
| 1538 | +					array('status' => 404) | |
| 1539 | + ); | |
| 1540 | + } | |
| 1541 | + } | |
| 1542 | + } | |
| 1543 | + | |
| 1544 | + /** | |
| 1545 | + * Checks that if this content requires a password to be read, that it's been provided and is correct. | |
| 1546 | + * @since 4.9.74.p | |
| 1547 | + * @param EEM_Base $model | |
| 1548 | + * @param $model_row | |
| 1549 | + * @param $query_params Adds 'default_where_conditions' => 'minimum' to ensure we don't confuse trashed with | |
| 1550 | + * password protected. | |
| 1551 | + * @param WP_REST_Request $request | |
| 1552 | + * @throws EE_Error | |
| 1553 | + * @throws InvalidArgumentException | |
| 1554 | + * @throws InvalidDataTypeException | |
| 1555 | + * @throws InvalidInterfaceException | |
| 1556 | + * @throws RestPasswordRequiredException | |
| 1557 | + * @throws RestPasswordIncorrectException | |
| 1558 | + * @throws \EventEspresso\core\exceptions\ModelConfigurationException | |
| 1559 | + * @throws ReflectionException | |
| 1560 | + */ | |
| 1561 | + protected function checkPassword(EEM_Base $model, $model_row, $query_params, WP_REST_Request $request) | |
| 1562 | +	{ | |
| 1563 | + $query_params['default_where_conditions'] = 'minimum'; | |
| 1564 | + // stuff is only "protected" for front-end requests. Elsewhere, you either get full permission to access the object | |
| 1565 | + // or you don't. | |
| 1566 | +		$request_caps = $request->get_param('caps'); | |
| 1567 | +		if (isset($request_caps) && $request_caps !== EEM_Base::caps_read) { | |
| 1568 | + return; | |
| 1569 | + } | |
| 1570 | + // if this entity requires a password, they better give it and it better be right! | |
| 1571 | + if ($model->hasPassword() | |
| 1572 | +			&& $model_row[ $model->getPasswordField()->get_qualified_column() ] !== '') { | |
| 1573 | +			if (empty($request['password'])) { | |
| 1574 | + throw new RestPasswordRequiredException(); | |
| 1575 | + } elseif (!hash_equals( | |
| 1576 | + $model_row[ $model->getPasswordField()->get_qualified_column() ], | |
| 1577 | + $request['password'] | |
| 1578 | +			)) { | |
| 1579 | + throw new RestPasswordIncorrectException(); | |
| 1580 | + } | |
| 1581 | + } // wait! maybe this content is password protected | |
| 1582 | + elseif ($model->restrictedByRelatedModelPassword() | |
| 1583 | +			&& $request->get_param('caps') === EEM_Base::caps_read) { | |
| 1584 | +			$password_supplied = $request->get_param('password'); | |
| 1585 | +			if (empty($password_supplied)) { | |
| 1586 | + $query_params['exclude_protected'] = true; | |
| 1587 | +				if (!$model->exists($query_params)) { | |
| 1588 | + throw new RestPasswordRequiredException(); | |
| 1589 | + } | |
| 1590 | +			} else { | |
| 1591 | + $query_params[0][ $model->modelChainAndPassword() ] = $password_supplied; | |
| 1592 | +				if (!$model->exists($query_params)) { | |
| 1593 | + throw new RestPasswordIncorrectException(); | |
| 1594 | + } | |
| 1595 | + } | |
| 1596 | + } | |
| 1597 | + } | |
| 1598 | 1598 | } | 
| @@ -14,2503 +14,2503 @@ | ||
| 14 | 14 | class Transactions_Admin_Page extends EE_Admin_Page | 
| 15 | 15 |  { | 
| 16 | 16 | |
| 17 | - /** | |
| 18 | - * @var EE_Transaction | |
| 19 | - */ | |
| 20 | - private $_transaction; | |
| 21 | - | |
| 22 | - /** | |
| 23 | - * @var EE_Session | |
| 24 | - */ | |
| 25 | - private $_session; | |
| 26 | - | |
| 27 | - /** | |
| 28 | - * @var array $_txn_status | |
| 29 | - */ | |
| 30 | - private static $_txn_status; | |
| 31 | - | |
| 32 | - /** | |
| 33 | - * @var array $_pay_status | |
| 34 | - */ | |
| 35 | - private static $_pay_status; | |
| 36 | - | |
| 37 | - /** | |
| 38 | - * @var array $_existing_reg_payment_REG_IDs | |
| 39 | - */ | |
| 40 | - protected $_existing_reg_payment_REG_IDs = null; | |
| 41 | - | |
| 42 | - | |
| 43 | - /** | |
| 44 | - * @Constructor | |
| 45 | - * @access public | |
| 46 | - * @param bool $routing | |
| 47 | - * @throws EE_Error | |
| 48 | - * @throws InvalidArgumentException | |
| 49 | - * @throws ReflectionException | |
| 50 | - * @throws InvalidDataTypeException | |
| 51 | - * @throws InvalidInterfaceException | |
| 52 | - */ | |
| 53 | - public function __construct($routing = true) | |
| 54 | -    { | |
| 55 | - parent::__construct($routing); | |
| 56 | - } | |
| 57 | - | |
| 58 | - | |
| 59 | - /** | |
| 60 | - * _init_page_props | |
| 61 | - * | |
| 62 | - * @return void | |
| 63 | - */ | |
| 64 | - protected function _init_page_props() | |
| 65 | -    { | |
| 66 | - $this->page_slug = TXN_PG_SLUG; | |
| 67 | -        $this->page_label = esc_html__('Transactions', 'event_espresso'); | |
| 68 | - $this->_admin_base_url = TXN_ADMIN_URL; | |
| 69 | - $this->_admin_base_path = TXN_ADMIN; | |
| 70 | - } | |
| 71 | - | |
| 72 | - | |
| 73 | - /** | |
| 74 | - * _ajax_hooks | |
| 75 | - * | |
| 76 | - * @return void | |
| 77 | - */ | |
| 78 | - protected function _ajax_hooks() | |
| 79 | -    { | |
| 80 | -        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds')); | |
| 81 | -        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds')); | |
| 82 | -        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment')); | |
| 83 | - } | |
| 84 | - | |
| 85 | - | |
| 86 | - /** | |
| 87 | - * _define_page_props | |
| 88 | - * | |
| 89 | - * @return void | |
| 90 | - */ | |
| 91 | - protected function _define_page_props() | |
| 92 | -    { | |
| 93 | - $this->_admin_page_title = $this->page_label; | |
| 94 | - $this->_labels = array( | |
| 95 | - 'buttons' => array( | |
| 96 | -                'add'    => esc_html__('Add New Transaction', 'event_espresso'), | |
| 97 | -                'edit'   => esc_html__('Edit Transaction', 'event_espresso'), | |
| 98 | -                'delete' => esc_html__('Delete Transaction', 'event_espresso'), | |
| 99 | - ), | |
| 100 | - ); | |
| 101 | - } | |
| 102 | - | |
| 103 | - | |
| 104 | - /** | |
| 105 | - * grab url requests and route them | |
| 106 | - * | |
| 107 | - * @access private | |
| 108 | - * @return void | |
| 109 | - * @throws EE_Error | |
| 110 | - * @throws InvalidArgumentException | |
| 111 | - * @throws InvalidDataTypeException | |
| 112 | - * @throws InvalidInterfaceException | |
| 113 | - */ | |
| 114 | - public function _set_page_routes() | |
| 115 | -    { | |
| 116 | - | |
| 117 | - $this->_set_transaction_status_array(); | |
| 118 | - | |
| 119 | - $txn_id = ! empty($this->_req_data['TXN_ID']) | |
| 120 | - && ! is_array($this->_req_data['TXN_ID']) | |
| 121 | - ? $this->_req_data['TXN_ID'] | |
| 122 | - : 0; | |
| 123 | - | |
| 124 | - $this->_page_routes = array( | |
| 125 | - | |
| 126 | - 'default' => array( | |
| 127 | - 'func' => '_transactions_overview_list_table', | |
| 128 | - 'capability' => 'ee_read_transactions', | |
| 129 | - ), | |
| 130 | - | |
| 131 | - 'view_transaction' => array( | |
| 132 | - 'func' => '_transaction_details', | |
| 133 | - 'capability' => 'ee_read_transaction', | |
| 134 | - 'obj_id' => $txn_id, | |
| 135 | - ), | |
| 136 | - | |
| 137 | - 'send_payment_reminder' => array( | |
| 138 | - 'func' => '_send_payment_reminder', | |
| 139 | - 'noheader' => true, | |
| 140 | - 'capability' => 'ee_send_message', | |
| 141 | - ), | |
| 142 | - | |
| 143 | - 'espresso_apply_payment' => array( | |
| 144 | - 'func' => 'apply_payments_or_refunds', | |
| 145 | - 'noheader' => true, | |
| 146 | - 'capability' => 'ee_edit_payments', | |
| 147 | - ), | |
| 148 | - | |
| 149 | - 'espresso_apply_refund' => array( | |
| 150 | - 'func' => 'apply_payments_or_refunds', | |
| 151 | - 'noheader' => true, | |
| 152 | - 'capability' => 'ee_edit_payments', | |
| 153 | - ), | |
| 154 | - | |
| 155 | - 'espresso_delete_payment' => array( | |
| 156 | - 'func' => 'delete_payment', | |
| 157 | - 'noheader' => true, | |
| 158 | - 'capability' => 'ee_delete_payments', | |
| 159 | - ), | |
| 160 | - | |
| 161 | - ); | |
| 162 | - } | |
| 163 | - | |
| 164 | - | |
| 165 | - protected function _set_page_config() | |
| 166 | -    { | |
| 167 | - $this->_page_config = array( | |
| 168 | - 'default' => array( | |
| 169 | - 'nav' => array( | |
| 170 | -                    'label' => esc_html__('Overview', 'event_espresso'), | |
| 171 | - 'order' => 10, | |
| 172 | - ), | |
| 173 | - 'list_table' => 'EE_Admin_Transactions_List_Table', | |
| 174 | - 'help_tabs' => array( | |
| 175 | - 'transactions_overview_help_tab' => array( | |
| 176 | -                        'title'    => esc_html__('Transactions Overview', 'event_espresso'), | |
| 177 | - 'filename' => 'transactions_overview', | |
| 178 | - ), | |
| 179 | - 'transactions_overview_table_column_headings_help_tab' => array( | |
| 180 | -                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'), | |
| 181 | - 'filename' => 'transactions_overview_table_column_headings', | |
| 182 | - ), | |
| 183 | - 'transactions_overview_views_filters_help_tab' => array( | |
| 184 | -                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'), | |
| 185 | - 'filename' => 'transactions_overview_views_filters_search', | |
| 186 | - ), | |
| 187 | - ), | |
| 188 | -                'help_tour'     => array('Transactions_Overview_Help_Tour'), | |
| 189 | - /** | |
| 190 | - * commented out because currently we are not displaying tips for transaction list table status but this | |
| 191 | - * may change in a later iteration so want to keep the code for then. | |
| 192 | - */ | |
| 193 | - // 'qtips' => array( 'Transactions_List_Table_Tips' ), | |
| 194 | - 'require_nonce' => false, | |
| 195 | - ), | |
| 196 | - 'view_transaction' => array( | |
| 197 | - 'nav' => array( | |
| 198 | -                    'label'      => esc_html__('View Transaction', 'event_espresso'), | |
| 199 | - 'order' => 5, | |
| 200 | - 'url' => isset($this->_req_data['TXN_ID']) | |
| 201 | -                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url) | |
| 202 | - : $this->_admin_base_url, | |
| 203 | - 'persistent' => false, | |
| 204 | - ), | |
| 205 | - 'help_tabs' => array( | |
| 206 | - 'transactions_view_transaction_help_tab' => array( | |
| 207 | -                        'title'    => esc_html__('View Transaction', 'event_espresso'), | |
| 208 | - 'filename' => 'transactions_view_transaction', | |
| 209 | - ), | |
| 210 | - 'transactions_view_transaction_transaction_details_table_help_tab' => array( | |
| 211 | -                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'), | |
| 212 | - 'filename' => 'transactions_view_transaction_transaction_details_table', | |
| 213 | - ), | |
| 214 | - 'transactions_view_transaction_attendees_registered_help_tab' => array( | |
| 215 | -                        'title'    => esc_html__('Attendees Registered', 'event_espresso'), | |
| 216 | - 'filename' => 'transactions_view_transaction_attendees_registered', | |
| 217 | - ), | |
| 218 | - 'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array( | |
| 219 | -                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'), | |
| 220 | - 'filename' => 'transactions_view_transaction_primary_registrant_billing_information', | |
| 221 | - ), | |
| 222 | - ), | |
| 223 | -                'qtips'     => array('Transaction_Details_Tips'), | |
| 224 | -                'help_tour' => array('Transaction_Details_Help_Tour'), | |
| 225 | -                'metaboxes' => array('_transaction_details_metaboxes'), | |
| 226 | - | |
| 227 | - 'require_nonce' => false, | |
| 228 | - ), | |
| 229 | - ); | |
| 230 | - } | |
| 231 | - | |
| 232 | - | |
| 233 | - /** | |
| 234 | - * The below methods aren't used by this class currently | |
| 235 | - */ | |
| 236 | - protected function _add_screen_options() | |
| 237 | -    { | |
| 238 | - // noop | |
| 239 | - } | |
| 240 | - | |
| 241 | - protected function _add_feature_pointers() | |
| 242 | -    { | |
| 243 | - // noop | |
| 244 | - } | |
| 245 | - | |
| 246 | - public function admin_init() | |
| 247 | -    { | |
| 248 | - // IF a registration was JUST added via the admin... | |
| 249 | - if (isset( | |
| 250 | - $this->_req_data['redirect_from'], | |
| 251 | - $this->_req_data['EVT_ID'], | |
| 252 | - $this->_req_data['event_name'] | |
| 253 | -        )) { | |
| 254 | - // then set a cookie so that we can block any attempts to use | |
| 255 | - // the back button as a way to enter another registration. | |
| 256 | - setcookie( | |
| 257 | - 'ee_registration_added', | |
| 258 | - $this->_req_data['EVT_ID'], | |
| 259 | - time() + WEEK_IN_SECONDS, | |
| 260 | - '/' | |
| 261 | - ); | |
| 262 | - // and update the global | |
| 263 | - $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID']; | |
| 264 | - } | |
| 265 | - EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__( | |
| 266 | - 'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.', | |
| 267 | - 'event_espresso' | |
| 268 | - ); | |
| 269 | - EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__( | |
| 270 | - 'An error occurred! Please refresh the page and try again.', | |
| 271 | - 'event_espresso' | |
| 272 | - ); | |
| 273 | - EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status; | |
| 274 | - EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status; | |
| 275 | -        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso'); | |
| 276 | - EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__( | |
| 277 | - 'This transaction has been overpaid ! Payments Total', | |
| 278 | - 'event_espresso' | |
| 279 | - ); | |
| 280 | - } | |
| 281 | - | |
| 282 | - public function admin_notices() | |
| 283 | -    { | |
| 284 | - // noop | |
| 285 | - } | |
| 286 | - | |
| 287 | - public function admin_footer_scripts() | |
| 288 | -    { | |
| 289 | - // noop | |
| 290 | - } | |
| 291 | - | |
| 292 | - | |
| 293 | - /** | |
| 294 | - * _set_transaction_status_array | |
| 295 | - * sets list of transaction statuses | |
| 296 | - * | |
| 297 | - * @access private | |
| 298 | - * @return void | |
| 299 | - * @throws EE_Error | |
| 300 | - * @throws InvalidArgumentException | |
| 301 | - * @throws InvalidDataTypeException | |
| 302 | - * @throws InvalidInterfaceException | |
| 303 | - */ | |
| 304 | - private function _set_transaction_status_array() | |
| 305 | -    { | |
| 306 | - self::$_txn_status = EEM_Transaction::instance()->status_array(true); | |
| 307 | - } | |
| 308 | - | |
| 309 | - | |
| 310 | - /** | |
| 311 | - * get_transaction_status_array | |
| 312 | - * return the transaction status array for wp_list_table | |
| 313 | - * | |
| 314 | - * @access public | |
| 315 | - * @return array | |
| 316 | - */ | |
| 317 | - public function get_transaction_status_array() | |
| 318 | -    { | |
| 319 | - return self::$_txn_status; | |
| 320 | - } | |
| 321 | - | |
| 322 | - | |
| 323 | - /** | |
| 324 | - * get list of payment statuses | |
| 325 | - * | |
| 326 | - * @access private | |
| 327 | - * @return void | |
| 328 | - * @throws EE_Error | |
| 329 | - * @throws InvalidArgumentException | |
| 330 | - * @throws InvalidDataTypeException | |
| 331 | - * @throws InvalidInterfaceException | |
| 332 | - */ | |
| 333 | - private function _get_payment_status_array() | |
| 334 | -    { | |
| 335 | - self::$_pay_status = EEM_Payment::instance()->status_array(true); | |
| 336 | - $this->_template_args['payment_status'] = self::$_pay_status; | |
| 337 | - } | |
| 338 | - | |
| 339 | - | |
| 340 | - /** | |
| 341 | - * _add_screen_options_default | |
| 342 | - * | |
| 343 | - * @access protected | |
| 344 | - * @return void | |
| 345 | - * @throws InvalidArgumentException | |
| 346 | - * @throws InvalidDataTypeException | |
| 347 | - * @throws InvalidInterfaceException | |
| 348 | - */ | |
| 349 | - protected function _add_screen_options_default() | |
| 350 | -    { | |
| 351 | - $this->_per_page_screen_option(); | |
| 352 | - } | |
| 353 | - | |
| 354 | - | |
| 355 | - /** | |
| 356 | - * load_scripts_styles | |
| 357 | - * | |
| 358 | - * @access public | |
| 359 | - * @return void | |
| 360 | - */ | |
| 361 | - public function load_scripts_styles() | |
| 362 | -    { | |
| 363 | - // enqueue style | |
| 364 | - wp_register_style( | |
| 365 | - 'espresso_txn', | |
| 366 | - TXN_ASSETS_URL . 'espresso_transactions_admin.css', | |
| 367 | - array(), | |
| 368 | - EVENT_ESPRESSO_VERSION | |
| 369 | - ); | |
| 370 | -        wp_enqueue_style('espresso_txn'); | |
| 371 | - // scripts | |
| 372 | - wp_register_script( | |
| 373 | - 'espresso_txn', | |
| 374 | - TXN_ASSETS_URL . 'espresso_transactions_admin.js', | |
| 375 | - array( | |
| 376 | - 'ee_admin_js', | |
| 377 | - 'ee-datepicker', | |
| 378 | - 'jquery-ui-datepicker', | |
| 379 | - 'jquery-ui-draggable', | |
| 380 | - 'ee-dialog', | |
| 381 | - 'ee-accounting', | |
| 382 | - 'ee-serialize-full-array', | |
| 383 | - ), | |
| 384 | - EVENT_ESPRESSO_VERSION, | |
| 385 | - true | |
| 386 | - ); | |
| 387 | -        wp_enqueue_script('espresso_txn'); | |
| 388 | - } | |
| 389 | - | |
| 390 | - | |
| 391 | - /** | |
| 392 | - * load_scripts_styles_view_transaction | |
| 393 | - * | |
| 394 | - * @access public | |
| 395 | - * @return void | |
| 396 | - */ | |
| 397 | - public function load_scripts_styles_view_transaction() | |
| 398 | -    { | |
| 399 | - // styles | |
| 400 | -        wp_enqueue_style('espresso-ui-theme'); | |
| 401 | - } | |
| 402 | - | |
| 403 | - | |
| 404 | - /** | |
| 405 | - * load_scripts_styles_default | |
| 406 | - * | |
| 407 | - * @access public | |
| 408 | - * @return void | |
| 409 | - */ | |
| 410 | - public function load_scripts_styles_default() | |
| 411 | -    { | |
| 412 | - // styles | |
| 413 | -        wp_enqueue_style('espresso-ui-theme'); | |
| 414 | - } | |
| 415 | - | |
| 416 | - | |
| 417 | - /** | |
| 418 | - * _set_list_table_views_default | |
| 419 | - * | |
| 420 | - * @access protected | |
| 421 | - * @return void | |
| 422 | - */ | |
| 423 | - protected function _set_list_table_views_default() | |
| 424 | -    { | |
| 425 | - $this->_views = array( | |
| 426 | - 'all' => array( | |
| 427 | - 'slug' => 'all', | |
| 428 | -                'label' => esc_html__('View All Transactions', 'event_espresso'), | |
| 429 | - 'count' => 0, | |
| 430 | - ), | |
| 431 | - 'abandoned' => array( | |
| 432 | - 'slug' => 'abandoned', | |
| 433 | -                'label' => esc_html__('Abandoned Transactions', 'event_espresso'), | |
| 434 | - 'count' => 0, | |
| 435 | - ), | |
| 436 | - 'incomplete' => array( | |
| 437 | - 'slug' => 'incomplete', | |
| 438 | -                'label' => esc_html__('Incomplete Transactions', 'event_espresso'), | |
| 439 | - 'count' => 0, | |
| 440 | - ) | |
| 441 | - ); | |
| 442 | - if (/** | |
| 443 | - * Filters whether a link to the "Failed Transactions" list table | |
| 444 | - * appears on the Transactions Admin Page list table. | |
| 445 | - * List display can be turned back on via the following: | |
| 446 | - * add_filter( | |
| 447 | - * 'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list', | |
| 448 | - * '__return_true' | |
| 449 | - * ); | |
| 450 | - * | |
| 451 | - * @since 4.9.70.p | |
| 452 | - * @param boolean $display_failed_txns_list | |
| 453 | - * @param Transactions_Admin_Page $this | |
| 454 | - */ | |
| 455 | - apply_filters( | |
| 456 | - 'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list', | |
| 457 | - false, | |
| 458 | - $this | |
| 459 | - ) | |
| 460 | -        ) { | |
| 461 | - $this->_views['failed'] = array( | |
| 462 | - 'slug' => 'failed', | |
| 463 | -                'label' => esc_html__('Failed Transactions', 'event_espresso'), | |
| 464 | - 'count' => 0, | |
| 465 | - ); | |
| 466 | - } | |
| 467 | - } | |
| 468 | - | |
| 469 | - | |
| 470 | - /** | |
| 471 | - * _set_transaction_object | |
| 472 | - * This sets the _transaction property for the transaction details screen | |
| 473 | - * | |
| 474 | - * @access private | |
| 475 | - * @return void | |
| 476 | - * @throws EE_Error | |
| 477 | - * @throws InvalidArgumentException | |
| 478 | - * @throws RuntimeException | |
| 479 | - * @throws InvalidDataTypeException | |
| 480 | - * @throws InvalidInterfaceException | |
| 481 | - * @throws ReflectionException | |
| 482 | - */ | |
| 483 | - private function _set_transaction_object() | |
| 484 | -    { | |
| 485 | -        if ($this->_transaction instanceof EE_Transaction) { | |
| 486 | - return; | |
| 487 | - } //get out we've already set the object | |
| 488 | - | |
| 489 | - $TXN_ID = ! empty($this->_req_data['TXN_ID']) | |
| 490 | - ? absint($this->_req_data['TXN_ID']) | |
| 491 | - : false; | |
| 492 | - | |
| 493 | - // get transaction object | |
| 494 | - $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID); | |
| 495 | - $this->_session = $this->_transaction instanceof EE_Transaction | |
| 496 | -            ? $this->_transaction->get('TXN_session_data') | |
| 497 | - : null; | |
| 498 | -        if ($this->_transaction instanceof EE_Transaction) { | |
| 499 | - $this->_transaction->verify_abandoned_transaction_status(); | |
| 500 | - } | |
| 501 | - | |
| 502 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 503 | - $error_msg = sprintf( | |
| 504 | - esc_html__( | |
| 505 | - 'An error occurred and the details for the transaction with the ID # %d could not be retrieved.', | |
| 506 | - 'event_espresso' | |
| 507 | - ), | |
| 508 | - $TXN_ID | |
| 509 | - ); | |
| 510 | - EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__); | |
| 511 | - } | |
| 512 | - } | |
| 513 | - | |
| 514 | - | |
| 515 | - /** | |
| 516 | - * _transaction_legend_items | |
| 517 | - * | |
| 518 | - * @access protected | |
| 519 | - * @return array | |
| 520 | - * @throws EE_Error | |
| 521 | - * @throws InvalidArgumentException | |
| 522 | - * @throws ReflectionException | |
| 523 | - * @throws InvalidDataTypeException | |
| 524 | - * @throws InvalidInterfaceException | |
| 525 | - */ | |
| 526 | - protected function _transaction_legend_items() | |
| 527 | -    { | |
| 528 | -        EE_Registry::instance()->load_helper('MSG_Template'); | |
| 529 | - $items = array(); | |
| 530 | - | |
| 531 | - if (EE_Registry::instance()->CAP->current_user_can( | |
| 532 | - 'ee_read_global_messages', | |
| 533 | - 'view_filtered_messages' | |
| 534 | -        )) { | |
| 535 | -            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for'); | |
| 536 | - if (is_array($related_for_icon) | |
| 537 | - && isset($related_for_icon['css_class'], $related_for_icon['label']) | |
| 538 | -            ) { | |
| 539 | - $items['view_related_messages'] = array( | |
| 540 | - 'class' => $related_for_icon['css_class'], | |
| 541 | - 'desc' => $related_for_icon['label'], | |
| 542 | - ); | |
| 543 | - } | |
| 544 | - } | |
| 545 | - | |
| 546 | - $items = apply_filters( | |
| 547 | - 'FHEE__Transactions_Admin_Page___transaction_legend_items__items', | |
| 548 | - array_merge( | |
| 549 | - $items, | |
| 550 | - array( | |
| 551 | - 'view_details' => array( | |
| 552 | - 'class' => 'dashicons dashicons-cart', | |
| 553 | -                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'), | |
| 554 | - ), | |
| 555 | - 'view_invoice' => array( | |
| 556 | - 'class' => 'dashicons dashicons-media-spreadsheet', | |
| 557 | -                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'), | |
| 558 | - ), | |
| 559 | - 'view_receipt' => array( | |
| 560 | - 'class' => 'dashicons dashicons-media-default', | |
| 561 | -                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'), | |
| 562 | - ), | |
| 563 | - 'view_registration' => array( | |
| 564 | - 'class' => 'dashicons dashicons-clipboard', | |
| 565 | -                        'desc'  => esc_html__('View Registration Details', 'event_espresso'), | |
| 566 | - ), | |
| 567 | - 'payment_overview_link' => array( | |
| 568 | - 'class' => 'dashicons dashicons-money', | |
| 569 | -                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'), | |
| 570 | - ), | |
| 571 | - ) | |
| 572 | - ) | |
| 573 | - ); | |
| 574 | - | |
| 575 | - if (EE_Registry::instance()->CAP->current_user_can( | |
| 576 | - 'ee_send_message', | |
| 577 | - 'espresso_transactions_send_payment_reminder' | |
| 578 | -        )) { | |
| 579 | -            if (EEH_MSG_Template::is_mt_active('payment_reminder')) { | |
| 580 | - $items['send_payment_reminder'] = array( | |
| 581 | - 'class' => 'dashicons dashicons-email-alt', | |
| 582 | -                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'), | |
| 583 | - ); | |
| 584 | -            } else { | |
| 585 | - $items['blank*'] = array( | |
| 586 | - 'class' => '', | |
| 587 | - 'desc' => '', | |
| 588 | - ); | |
| 589 | - } | |
| 590 | -        } else { | |
| 591 | - $items['blank*'] = array( | |
| 592 | - 'class' => '', | |
| 593 | - 'desc' => '', | |
| 594 | - ); | |
| 595 | - } | |
| 596 | - $more_items = apply_filters( | |
| 597 | - 'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items', | |
| 598 | - array( | |
| 599 | - 'overpaid' => array( | |
| 600 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code, | |
| 601 | - 'desc' => EEH_Template::pretty_status( | |
| 602 | - EEM_Transaction::overpaid_status_code, | |
| 603 | - false, | |
| 604 | - 'sentence' | |
| 605 | - ), | |
| 606 | - ), | |
| 607 | - 'complete' => array( | |
| 608 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code, | |
| 609 | - 'desc' => EEH_Template::pretty_status( | |
| 610 | - EEM_Transaction::complete_status_code, | |
| 611 | - false, | |
| 612 | - 'sentence' | |
| 613 | - ), | |
| 614 | - ), | |
| 615 | - 'incomplete' => array( | |
| 616 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code, | |
| 617 | - 'desc' => EEH_Template::pretty_status( | |
| 618 | - EEM_Transaction::incomplete_status_code, | |
| 619 | - false, | |
| 620 | - 'sentence' | |
| 621 | - ), | |
| 622 | - ), | |
| 623 | - 'abandoned' => array( | |
| 624 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code, | |
| 625 | - 'desc' => EEH_Template::pretty_status( | |
| 626 | - EEM_Transaction::abandoned_status_code, | |
| 627 | - false, | |
| 628 | - 'sentence' | |
| 629 | - ), | |
| 630 | - ), | |
| 631 | - 'failed' => array( | |
| 632 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code, | |
| 633 | - 'desc' => EEH_Template::pretty_status( | |
| 634 | - EEM_Transaction::failed_status_code, | |
| 635 | - false, | |
| 636 | - 'sentence' | |
| 637 | - ), | |
| 638 | - ), | |
| 639 | - ) | |
| 640 | - ); | |
| 641 | - | |
| 642 | - return array_merge($items, $more_items); | |
| 643 | - } | |
| 644 | - | |
| 645 | - | |
| 646 | - /** | |
| 647 | - * _transactions_overview_list_table | |
| 648 | - * | |
| 649 | - * @access protected | |
| 650 | - * @return void | |
| 651 | - * @throws DomainException | |
| 652 | - * @throws EE_Error | |
| 653 | - * @throws InvalidArgumentException | |
| 654 | - * @throws InvalidDataTypeException | |
| 655 | - * @throws InvalidInterfaceException | |
| 656 | - * @throws ReflectionException | |
| 657 | - */ | |
| 658 | - protected function _transactions_overview_list_table() | |
| 659 | -    { | |
| 660 | -        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso'); | |
| 661 | - $event = isset($this->_req_data['EVT_ID']) | |
| 662 | - ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']) | |
| 663 | - : null; | |
| 664 | - $this->_template_args['admin_page_header'] = $event instanceof EE_Event | |
| 665 | - ? sprintf( | |
| 666 | - esc_html__( | |
| 667 | - '%sViewing Transactions for the Event: %s%s', | |
| 668 | - 'event_espresso' | |
| 669 | - ), | |
| 670 | - '<h3>', | |
| 671 | - '<a href="' | |
| 672 | - . EE_Admin_Page::add_query_args_and_nonce( | |
| 673 | -                    array('action' => 'edit', 'post' => $event->ID()), | |
| 674 | - EVENTS_ADMIN_URL | |
| 675 | - ) | |
| 676 | - . '" title="' | |
| 677 | - . esc_attr__( | |
| 678 | - 'Click to Edit event', | |
| 679 | - 'event_espresso' | |
| 680 | - ) | |
| 681 | -                . '">' . $event->get('EVT_name') . '</a>', | |
| 682 | - '</h3>' | |
| 683 | - ) | |
| 684 | - : ''; | |
| 685 | - $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items()); | |
| 686 | - $this->display_admin_list_table_page_with_no_sidebar(); | |
| 687 | - } | |
| 688 | - | |
| 689 | - | |
| 690 | - /** | |
| 691 | - * _transaction_details | |
| 692 | - * generates HTML for the View Transaction Details Admin page | |
| 693 | - * | |
| 694 | - * @access protected | |
| 695 | - * @return void | |
| 696 | - * @throws DomainException | |
| 697 | - * @throws EE_Error | |
| 698 | - * @throws InvalidArgumentException | |
| 699 | - * @throws InvalidDataTypeException | |
| 700 | - * @throws InvalidInterfaceException | |
| 701 | - * @throws RuntimeException | |
| 702 | - * @throws ReflectionException | |
| 703 | - */ | |
| 704 | - protected function _transaction_details() | |
| 705 | -    { | |
| 706 | -        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction); | |
| 707 | - | |
| 708 | - $this->_set_transaction_status_array(); | |
| 709 | - | |
| 710 | - $this->_template_args = array(); | |
| 711 | - $this->_template_args['transactions_page'] = $this->_wp_page_slug; | |
| 712 | - | |
| 713 | - $this->_set_transaction_object(); | |
| 714 | - | |
| 715 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 716 | - return; | |
| 717 | - } | |
| 718 | - $primary_registration = $this->_transaction->primary_registration(); | |
| 719 | - $attendee = $primary_registration instanceof EE_Registration | |
| 720 | - ? $primary_registration->attendee() | |
| 721 | - : null; | |
| 722 | - | |
| 723 | - $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID(); | |
| 724 | -        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso'); | |
| 725 | - | |
| 726 | -        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp'); | |
| 727 | -        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso'); | |
| 728 | - | |
| 729 | -        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ]; | |
| 730 | -        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso'); | |
| 731 | -        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID'); | |
| 732 | - | |
| 733 | -        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total'); | |
| 734 | -        $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid'); | |
| 735 | - | |
| 736 | -        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid'); | |
| 737 | - $this->_template_args['amount_due'] = EEH_Template::format_currency( | |
| 738 | - $amount_due, | |
| 739 | - true | |
| 740 | - ); | |
| 741 | -        if (EE_Registry::instance()->CFG->currency->sign_b4) { | |
| 742 | - $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign | |
| 743 | - . $this->_template_args['amount_due']; | |
| 744 | -        } else { | |
| 745 | - $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign; | |
| 746 | - } | |
| 747 | - $this->_template_args['amount_due_class'] = ''; | |
| 748 | - | |
| 749 | -        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) { | |
| 750 | - // paid in full | |
| 751 | - $this->_template_args['amount_due'] = false; | |
| 752 | -        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) { | |
| 753 | - // overpaid | |
| 754 | - $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn'; | |
| 755 | -        } elseif ($this->_transaction->get('TXN_total') > 0 | |
| 756 | -                  && $this->_transaction->get('TXN_paid') > 0 | |
| 757 | -        ) { | |
| 758 | - // monies owing | |
| 759 | - $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn'; | |
| 760 | -        } elseif ($this->_transaction->get('TXN_total') > 0 | |
| 761 | -                  && $this->_transaction->get('TXN_paid') == 0 | |
| 762 | -        ) { | |
| 763 | - // no payments made yet | |
| 764 | - $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn'; | |
| 765 | -        } elseif ($this->_transaction->get('TXN_total') == 0) { | |
| 766 | - // free event | |
| 767 | - $this->_template_args['amount_due'] = false; | |
| 768 | - } | |
| 769 | - | |
| 770 | - $payment_method = $this->_transaction->payment_method(); | |
| 771 | - | |
| 772 | - $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method | |
| 773 | - ? $payment_method->admin_name() | |
| 774 | -            : esc_html__('Unknown', 'event_espresso'); | |
| 775 | - | |
| 776 | - $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign; | |
| 777 | - // link back to overview | |
| 778 | - $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER']) | |
| 779 | - ? $_SERVER['HTTP_REFERER'] | |
| 780 | - : TXN_ADMIN_URL; | |
| 781 | - | |
| 782 | - | |
| 783 | - // next link | |
| 784 | - $next_txn = $this->_transaction->next( | |
| 785 | - null, | |
| 786 | -            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))), | |
| 787 | - 'TXN_ID' | |
| 788 | - ); | |
| 789 | - $this->_template_args['next_transaction'] = $next_txn | |
| 790 | - ? $this->_next_link( | |
| 791 | - EE_Admin_Page::add_query_args_and_nonce( | |
| 792 | -                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']), | |
| 793 | - TXN_ADMIN_URL | |
| 794 | - ), | |
| 795 | - 'dashicons dashicons-arrow-right ee-icon-size-22' | |
| 796 | - ) | |
| 797 | - : ''; | |
| 798 | - // previous link | |
| 799 | - $previous_txn = $this->_transaction->previous( | |
| 800 | - null, | |
| 801 | -            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))), | |
| 802 | - 'TXN_ID' | |
| 803 | - ); | |
| 804 | - $this->_template_args['previous_transaction'] = $previous_txn | |
| 805 | - ? $this->_previous_link( | |
| 806 | - EE_Admin_Page::add_query_args_and_nonce( | |
| 807 | -                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']), | |
| 808 | - TXN_ADMIN_URL | |
| 809 | - ), | |
| 810 | - 'dashicons dashicons-arrow-left ee-icon-size-22' | |
| 811 | - ) | |
| 812 | - : ''; | |
| 813 | - | |
| 814 | - // were we just redirected here after adding a new registration ??? | |
| 815 | - if (isset( | |
| 816 | - $this->_req_data['redirect_from'], | |
| 817 | - $this->_req_data['EVT_ID'], | |
| 818 | - $this->_req_data['event_name'] | |
| 819 | -        )) { | |
| 820 | - if (EE_Registry::instance()->CAP->current_user_can( | |
| 821 | - 'ee_edit_registrations', | |
| 822 | - 'espresso_registrations_new_registration', | |
| 823 | - $this->_req_data['EVT_ID'] | |
| 824 | -            )) { | |
| 825 | - $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="'; | |
| 826 | - $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce( | |
| 827 | - array( | |
| 828 | - 'page' => 'espresso_registrations', | |
| 829 | - 'action' => 'new_registration', | |
| 830 | - 'return' => 'default', | |
| 831 | - 'TXN_ID' => $this->_transaction->ID(), | |
| 832 | - 'event_id' => $this->_req_data['EVT_ID'], | |
| 833 | - ), | |
| 834 | - REG_ADMIN_URL | |
| 835 | - ); | |
| 836 | - $this->_admin_page_title .= '">'; | |
| 837 | - | |
| 838 | - $this->_admin_page_title .= sprintf( | |
| 839 | -                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'), | |
| 840 | - htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8') | |
| 841 | - ); | |
| 842 | - $this->_admin_page_title .= '</a>'; | |
| 843 | - } | |
| 844 | - EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__); | |
| 845 | - } | |
| 846 | - // grab messages at the last second | |
| 847 | - $this->_template_args['notices'] = EE_Error::get_notices(); | |
| 848 | - // path to template | |
| 849 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php'; | |
| 850 | - $this->_template_args['admin_page_header'] = EEH_Template::display_template( | |
| 851 | - $template_path, | |
| 852 | - $this->_template_args, | |
| 853 | - true | |
| 854 | - ); | |
| 855 | - | |
| 856 | - // the details template wrapper | |
| 857 | - $this->display_admin_page_with_sidebar(); | |
| 858 | - } | |
| 859 | - | |
| 860 | - | |
| 861 | - /** | |
| 862 | - * _transaction_details_metaboxes | |
| 863 | - * | |
| 864 | - * @access protected | |
| 865 | - * @return void | |
| 866 | - * @throws EE_Error | |
| 867 | - * @throws InvalidArgumentException | |
| 868 | - * @throws InvalidDataTypeException | |
| 869 | - * @throws InvalidInterfaceException | |
| 870 | - * @throws RuntimeException | |
| 871 | - * @throws ReflectionException | |
| 872 | - */ | |
| 873 | - protected function _transaction_details_metaboxes() | |
| 874 | -    { | |
| 875 | - | |
| 876 | - $this->_set_transaction_object(); | |
| 877 | - | |
| 878 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 879 | - return; | |
| 880 | - } | |
| 881 | - add_meta_box( | |
| 882 | - 'edit-txn-details-mbox', | |
| 883 | -            esc_html__('Transaction Details', 'event_espresso'), | |
| 884 | - array($this, 'txn_details_meta_box'), | |
| 885 | - $this->_wp_page_slug, | |
| 886 | - 'normal', | |
| 887 | - 'high' | |
| 888 | - ); | |
| 889 | - add_meta_box( | |
| 890 | - 'edit-txn-attendees-mbox', | |
| 891 | -            esc_html__('Attendees Registered in this Transaction', 'event_espresso'), | |
| 892 | - array($this, 'txn_attendees_meta_box'), | |
| 893 | - $this->_wp_page_slug, | |
| 894 | - 'normal', | |
| 895 | - 'high', | |
| 896 | -            array('TXN_ID' => $this->_transaction->ID()) | |
| 897 | - ); | |
| 898 | - add_meta_box( | |
| 899 | - 'edit-txn-registrant-mbox', | |
| 900 | -            esc_html__('Primary Contact', 'event_espresso'), | |
| 901 | - array($this, 'txn_registrant_side_meta_box'), | |
| 902 | - $this->_wp_page_slug, | |
| 903 | - 'side', | |
| 904 | - 'high' | |
| 905 | - ); | |
| 906 | - add_meta_box( | |
| 907 | - 'edit-txn-billing-info-mbox', | |
| 908 | -            esc_html__('Billing Information', 'event_espresso'), | |
| 909 | - array($this, 'txn_billing_info_side_meta_box'), | |
| 910 | - $this->_wp_page_slug, | |
| 911 | - 'side', | |
| 912 | - 'high' | |
| 913 | - ); | |
| 914 | - } | |
| 915 | - | |
| 916 | - | |
| 917 | - /** | |
| 918 | - * Callback for transaction actions metabox. | |
| 919 | - * | |
| 920 | - * @param EE_Transaction|null $transaction | |
| 921 | - * @throws DomainException | |
| 922 | - * @throws EE_Error | |
| 923 | - * @throws InvalidArgumentException | |
| 924 | - * @throws InvalidDataTypeException | |
| 925 | - * @throws InvalidInterfaceException | |
| 926 | - * @throws ReflectionException | |
| 927 | - * @throws RuntimeException | |
| 928 | - */ | |
| 929 | - public function getActionButtons(EE_Transaction $transaction = null) | |
| 930 | -    { | |
| 931 | - $content = ''; | |
| 932 | - $actions = array(); | |
| 933 | -        if (! $transaction instanceof EE_Transaction) { | |
| 934 | - return $content; | |
| 935 | - } | |
| 936 | - /** @var EE_Registration $primary_registration */ | |
| 937 | - $primary_registration = $transaction->primary_registration(); | |
| 938 | - $attendee = $primary_registration instanceof EE_Registration | |
| 939 | - ? $primary_registration->attendee() | |
| 940 | - : null; | |
| 941 | - | |
| 942 | - if ($attendee instanceof EE_Attendee | |
| 943 | - && EE_Registry::instance()->CAP->current_user_can( | |
| 944 | - 'ee_send_message', | |
| 945 | - 'espresso_transactions_send_payment_reminder' | |
| 946 | - ) | |
| 947 | -        ) { | |
| 948 | - $actions['payment_reminder'] = | |
| 949 | -                EEH_MSG_Template::is_mt_active('payment_reminder') | |
| 950 | -                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code | |
| 951 | -                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code | |
| 952 | - ? EEH_Template::get_button_or_link( | |
| 953 | - EE_Admin_Page::add_query_args_and_nonce( | |
| 954 | - array( | |
| 955 | - 'action' => 'send_payment_reminder', | |
| 956 | - 'TXN_ID' => $this->_transaction->ID(), | |
| 957 | - 'redirect_to' => 'view_transaction', | |
| 958 | - ), | |
| 959 | - TXN_ADMIN_URL | |
| 960 | - ), | |
| 961 | -                        esc_html__(' Send Payment Reminder', 'event_espresso'), | |
| 962 | - 'button secondary-button', | |
| 963 | - 'dashicons dashicons-email-alt' | |
| 964 | - ) | |
| 965 | - : ''; | |
| 966 | - } | |
| 967 | - | |
| 968 | - if ($primary_registration instanceof EE_Registration | |
| 969 | -            && EEH_MSG_Template::is_mt_active('receipt') | |
| 970 | -        ) { | |
| 971 | - $actions['receipt'] = EEH_Template::get_button_or_link( | |
| 972 | - $primary_registration->receipt_url(), | |
| 973 | -                esc_html__('View Receipt', 'event_espresso'), | |
| 974 | - 'button secondary-button', | |
| 975 | - 'dashicons dashicons-media-default' | |
| 976 | - ); | |
| 977 | - } | |
| 978 | - | |
| 979 | - if ($primary_registration instanceof EE_Registration | |
| 980 | -            && EEH_MSG_Template::is_mt_active('invoice') | |
| 981 | -        ) { | |
| 982 | - $actions['invoice'] = EEH_Template::get_button_or_link( | |
| 983 | - $primary_registration->invoice_url(), | |
| 984 | -                esc_html__('View Invoice', 'event_espresso'), | |
| 985 | - 'button secondary-button', | |
| 986 | - 'dashicons dashicons-media-spreadsheet' | |
| 987 | - ); | |
| 988 | - } | |
| 989 | - $actions = array_filter( | |
| 990 | -            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction) | |
| 991 | - ); | |
| 992 | -        if ($actions) { | |
| 993 | - $content = '<ul>'; | |
| 994 | -            $content .= '<li>' . implode('</li><li>', $actions) . '</li>'; | |
| 995 | - $content .= '</uL>'; | |
| 996 | - } | |
| 997 | - return $content; | |
| 998 | - } | |
| 999 | - | |
| 1000 | - | |
| 1001 | - /** | |
| 1002 | - * txn_details_meta_box | |
| 1003 | - * generates HTML for the Transaction main meta box | |
| 1004 | - * | |
| 1005 | - * @return void | |
| 1006 | - * @throws DomainException | |
| 1007 | - * @throws EE_Error | |
| 1008 | - * @throws InvalidArgumentException | |
| 1009 | - * @throws InvalidDataTypeException | |
| 1010 | - * @throws InvalidInterfaceException | |
| 1011 | - * @throws RuntimeException | |
| 1012 | - * @throws ReflectionException | |
| 1013 | - */ | |
| 1014 | - public function txn_details_meta_box() | |
| 1015 | -    { | |
| 1016 | - $this->_set_transaction_object(); | |
| 1017 | - $this->_template_args['TXN_ID'] = $this->_transaction->ID(); | |
| 1018 | - $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration | |
| 1019 | - ? $this->_transaction->primary_registration()->attendee() | |
| 1020 | - : null; | |
| 1021 | - $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can( | |
| 1022 | - 'ee_edit_payments', | |
| 1023 | - 'apply_payment_or_refund_from_registration_details' | |
| 1024 | - ); | |
| 1025 | - $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can( | |
| 1026 | - 'ee_delete_payments', | |
| 1027 | - 'delete_payment_from_registration_details' | |
| 1028 | - ); | |
| 1029 | - | |
| 1030 | - // get line table | |
| 1031 | - EEH_Autoloader::register_line_item_display_autoloaders(); | |
| 1032 | - $Line_Item_Display = new EE_Line_Item_Display( | |
| 1033 | - 'admin_table', | |
| 1034 | - 'EE_Admin_Table_Line_Item_Display_Strategy' | |
| 1035 | - ); | |
| 1036 | - $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item( | |
| 1037 | - $this->_transaction->total_line_item() | |
| 1038 | - ); | |
| 1039 | -        $this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration') | |
| 1040 | -                                                               ->get('REG_code'); | |
| 1041 | - | |
| 1042 | - // process taxes | |
| 1043 | - $taxes = $this->_transaction->get_many_related( | |
| 1044 | - 'Line_Item', | |
| 1045 | -            array(array('LIN_type' => EEM_Line_Item::type_tax)) | |
| 1046 | - ); | |
| 1047 | - $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false; | |
| 1048 | - | |
| 1049 | - $this->_template_args['grand_total'] = EEH_Template::format_currency( | |
| 1050 | -            $this->_transaction->get('TXN_total'), | |
| 1051 | - false, | |
| 1052 | - false | |
| 1053 | - ); | |
| 1054 | -        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total'); | |
| 1055 | -        $this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID'); | |
| 1056 | - | |
| 1057 | - // process payment details | |
| 1058 | -        $payments = $this->_transaction->get_many_related('Payment'); | |
| 1059 | -        if (! empty($payments)) { | |
| 1060 | - $this->_template_args['payments'] = $payments; | |
| 1061 | - $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments); | |
| 1062 | -        } else { | |
| 1063 | - $this->_template_args['payments'] = false; | |
| 1064 | - $this->_template_args['existing_reg_payments'] = array(); | |
| 1065 | - } | |
| 1066 | - | |
| 1067 | -        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL); | |
| 1068 | - $this->_template_args['delete_payment_url'] = add_query_arg( | |
| 1069 | -            array('action' => 'espresso_delete_payment'), | |
| 1070 | - TXN_ADMIN_URL | |
| 1071 | - ); | |
| 1072 | - | |
| 1073 | -        if (isset($txn_details['invoice_number'])) { | |
| 1074 | - $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code']; | |
| 1075 | - $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__( | |
| 1076 | - 'Invoice Number', | |
| 1077 | - 'event_espresso' | |
| 1078 | - ); | |
| 1079 | - } | |
| 1080 | - | |
| 1081 | - $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction | |
| 1082 | -            ->get_first_related('Registration') | |
| 1083 | -            ->get('REG_session'); | |
| 1084 | - $this->_template_args['txn_details']['registration_session']['label'] = esc_html__( | |
| 1085 | - 'Registration Session', | |
| 1086 | - 'event_espresso' | |
| 1087 | - ); | |
| 1088 | - | |
| 1089 | - $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address']) | |
| 1090 | - ? $this->_session['ip_address'] | |
| 1091 | - : ''; | |
| 1092 | - $this->_template_args['txn_details']['ip_address']['label'] = esc_html__( | |
| 1093 | - 'Transaction placed from IP', | |
| 1094 | - 'event_espresso' | |
| 1095 | - ); | |
| 1096 | - | |
| 1097 | - $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent']) | |
| 1098 | - ? $this->_session['user_agent'] | |
| 1099 | - : ''; | |
| 1100 | - $this->_template_args['txn_details']['user_agent']['label'] = esc_html__( | |
| 1101 | - 'Registrant User Agent', | |
| 1102 | - 'event_espresso' | |
| 1103 | - ); | |
| 1104 | - | |
| 1105 | - $reg_steps = '<ul>'; | |
| 1106 | -        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) { | |
| 1107 | -            if ($reg_step_status === true) { | |
| 1108 | - $reg_steps .= '<li style="color:#70cc50">' | |
| 1109 | - . sprintf( | |
| 1110 | -                                  esc_html__('%1$s : Completed', 'event_espresso'), | |
| 1111 | -                                  ucwords(str_replace('_', ' ', $reg_step)) | |
| 1112 | - ) | |
| 1113 | - . '</li>'; | |
| 1114 | -            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) { | |
| 1115 | - $reg_steps .= '<li style="color:#2EA2CC">' | |
| 1116 | - . sprintf( | |
| 1117 | -                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'), | |
| 1118 | -                                  ucwords(str_replace('_', ' ', $reg_step)), | |
| 1119 | - date( | |
| 1120 | -                                      get_option('date_format') . ' ' . get_option('time_format'), | |
| 1121 | -                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)) | |
| 1122 | - ) | |
| 1123 | - ) | |
| 1124 | - . '</li>'; | |
| 1125 | -            } else { | |
| 1126 | - $reg_steps .= '<li style="color:#E76700">' | |
| 1127 | - . sprintf( | |
| 1128 | -                                  esc_html__('%1$s : Never Initiated', 'event_espresso'), | |
| 1129 | -                                  ucwords(str_replace('_', ' ', $reg_step)) | |
| 1130 | - ) | |
| 1131 | - . '</li>'; | |
| 1132 | - } | |
| 1133 | - } | |
| 1134 | - $reg_steps .= '</ul>'; | |
| 1135 | - $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps; | |
| 1136 | - $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__( | |
| 1137 | - 'Registration Step Progress', | |
| 1138 | - 'event_espresso' | |
| 1139 | - ); | |
| 1140 | - | |
| 1141 | - | |
| 1142 | - $this->_get_registrations_to_apply_payment_to(); | |
| 1143 | - $this->_get_payment_methods($payments); | |
| 1144 | - $this->_get_payment_status_array(); | |
| 1145 | - $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction. | |
| 1146 | - | |
| 1147 | - $this->_template_args['transaction_form_url'] = add_query_arg( | |
| 1148 | - array( | |
| 1149 | - 'action' => 'edit_transaction', | |
| 1150 | - 'process' => 'transaction', | |
| 1151 | - ), | |
| 1152 | - TXN_ADMIN_URL | |
| 1153 | - ); | |
| 1154 | - $this->_template_args['apply_payment_form_url'] = add_query_arg( | |
| 1155 | - array( | |
| 1156 | - 'page' => 'espresso_transactions', | |
| 1157 | - 'action' => 'espresso_apply_payment', | |
| 1158 | - ), | |
| 1159 | - WP_AJAX_URL | |
| 1160 | - ); | |
| 1161 | - $this->_template_args['delete_payment_form_url'] = add_query_arg( | |
| 1162 | - array( | |
| 1163 | - 'page' => 'espresso_transactions', | |
| 1164 | - 'action' => 'espresso_delete_payment', | |
| 1165 | - ), | |
| 1166 | - WP_AJAX_URL | |
| 1167 | - ); | |
| 1168 | - | |
| 1169 | - $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction); | |
| 1170 | - | |
| 1171 | - // 'espresso_delete_payment_nonce' | |
| 1172 | - | |
| 1173 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php'; | |
| 1174 | - echo EEH_Template::display_template($template_path, $this->_template_args, true); | |
| 1175 | - } | |
| 1176 | - | |
| 1177 | - | |
| 1178 | - /** | |
| 1179 | - * _get_registration_payment_IDs | |
| 1180 | - * generates an array of Payment IDs and their corresponding Registration IDs | |
| 1181 | - * | |
| 1182 | - * @access protected | |
| 1183 | - * @param EE_Payment[] $payments | |
| 1184 | - * @return array | |
| 1185 | - * @throws EE_Error | |
| 1186 | - * @throws InvalidArgumentException | |
| 1187 | - * @throws InvalidDataTypeException | |
| 1188 | - * @throws InvalidInterfaceException | |
| 1189 | - * @throws ReflectionException | |
| 1190 | - */ | |
| 1191 | - protected function _get_registration_payment_IDs($payments = array()) | |
| 1192 | -    { | |
| 1193 | - $existing_reg_payments = array(); | |
| 1194 | - // get all reg payments for these payments | |
| 1195 | - $reg_payments = EEM_Registration_Payment::instance()->get_all( | |
| 1196 | - array( | |
| 1197 | - array( | |
| 1198 | - 'PAY_ID' => array( | |
| 1199 | - 'IN', | |
| 1200 | - array_keys($payments), | |
| 1201 | - ), | |
| 1202 | - ), | |
| 1203 | - ) | |
| 1204 | - ); | |
| 1205 | -        if (! empty($reg_payments)) { | |
| 1206 | -            foreach ($payments as $payment) { | |
| 1207 | -                if (! $payment instanceof EE_Payment) { | |
| 1208 | - continue; | |
| 1209 | -                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) { | |
| 1210 | - $existing_reg_payments[ $payment->ID() ] = array(); | |
| 1211 | - } | |
| 1212 | -                foreach ($reg_payments as $reg_payment) { | |
| 1213 | - if ($reg_payment instanceof EE_Registration_Payment | |
| 1214 | - && $reg_payment->payment_ID() === $payment->ID() | |
| 1215 | -                    ) { | |
| 1216 | - $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID(); | |
| 1217 | - } | |
| 1218 | - } | |
| 1219 | - } | |
| 1220 | - } | |
| 1221 | - | |
| 1222 | - return $existing_reg_payments; | |
| 1223 | - } | |
| 1224 | - | |
| 1225 | - | |
| 1226 | - /** | |
| 1227 | - * _get_registrations_to_apply_payment_to | |
| 1228 | - * generates HTML for displaying a series of checkboxes in the admin payment modal window | |
| 1229 | - * which allows the admin to only apply the payment to the specific registrations | |
| 1230 | - * | |
| 1231 | - * @access protected | |
| 1232 | - * @return void | |
| 1233 | - * @throws \EE_Error | |
| 1234 | - */ | |
| 1235 | - protected function _get_registrations_to_apply_payment_to() | |
| 1236 | -    { | |
| 1237 | - // we want any registration with an active status (ie: not deleted or cancelled) | |
| 1238 | - $query_params = array( | |
| 1239 | - array( | |
| 1240 | - 'STS_ID' => array( | |
| 1241 | - 'IN', | |
| 1242 | - array( | |
| 1243 | - EEM_Registration::status_id_approved, | |
| 1244 | - EEM_Registration::status_id_pending_payment, | |
| 1245 | - EEM_Registration::status_id_not_approved, | |
| 1246 | - ), | |
| 1247 | - ), | |
| 1248 | - ), | |
| 1249 | - ); | |
| 1250 | - $registrations_to_apply_payment_to = EEH_HTML::br() | |
| 1251 | - . EEH_HTML::div( | |
| 1252 | - '', | |
| 1253 | - 'txn-admin-apply-payment-to-registrations-dv', | |
| 1254 | - '', | |
| 1255 | - 'clear: both; margin: 1.5em 0 0; display: none;' | |
| 1256 | - ); | |
| 1257 | -        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap'); | |
| 1258 | -        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl'); | |
| 1259 | - $registrations_to_apply_payment_to .= EEH_HTML::thead( | |
| 1260 | - EEH_HTML::tr( | |
| 1261 | -                EEH_HTML::th(esc_html__('ID', 'event_espresso')) . | |
| 1262 | -                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) . | |
| 1263 | -                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) . | |
| 1264 | -                EEH_HTML::th(esc_html__('Event', 'event_espresso')) . | |
| 1265 | -                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1266 | -                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1267 | -                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr') | |
| 1268 | - ) | |
| 1269 | - ); | |
| 1270 | - $registrations_to_apply_payment_to .= EEH_HTML::tbody(); | |
| 1271 | - // get registrations for TXN | |
| 1272 | - $registrations = $this->_transaction->registrations($query_params); | |
| 1273 | - $existing_reg_payments = $this->_template_args['existing_reg_payments']; | |
| 1274 | -        foreach ($registrations as $registration) { | |
| 1275 | -            if ($registration instanceof EE_Registration) { | |
| 1276 | - $attendee_name = $registration->attendee() instanceof EE_Attendee | |
| 1277 | - ? $registration->attendee()->full_name() | |
| 1278 | -                    : esc_html__('Unknown Attendee', 'event_espresso'); | |
| 1279 | - $owing = $registration->final_price() - $registration->paid(); | |
| 1280 | - $taxable = $registration->ticket()->taxable() | |
| 1281 | -                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>' | |
| 1282 | - : ''; | |
| 1283 | - $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments) | |
| 1284 | - ? ' checked="checked"' | |
| 1285 | - : ''; | |
| 1286 | - $disabled = $registration->final_price() > 0 ? '' : ' disabled'; | |
| 1287 | - $registrations_to_apply_payment_to .= EEH_HTML::tr( | |
| 1288 | - EEH_HTML::td($registration->ID()) . | |
| 1289 | - EEH_HTML::td($attendee_name) . | |
| 1290 | - EEH_HTML::td( | |
| 1291 | - $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable | |
| 1292 | - ) . | |
| 1293 | - EEH_HTML::td($registration->event_name()) . | |
| 1294 | - EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1295 | - EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1296 | - EEH_HTML::td( | |
| 1297 | - '<input type="checkbox" value="' . $registration->ID() | |
| 1298 | - . '" name="txn_admin_payment[registrations]"' | |
| 1299 | - . $checked . $disabled . '>', | |
| 1300 | - '', | |
| 1301 | - 'jst-cntr' | |
| 1302 | - ), | |
| 1303 | - 'apply-payment-registration-row-' . $registration->ID() | |
| 1304 | - ); | |
| 1305 | - } | |
| 1306 | - } | |
| 1307 | - $registrations_to_apply_payment_to .= EEH_HTML::tbodyx(); | |
| 1308 | - $registrations_to_apply_payment_to .= EEH_HTML::tablex(); | |
| 1309 | - $registrations_to_apply_payment_to .= EEH_HTML::divx(); | |
| 1310 | - $registrations_to_apply_payment_to .= EEH_HTML::p( | |
| 1311 | - esc_html__( | |
| 1312 | - 'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.', | |
| 1313 | - 'event_espresso' | |
| 1314 | - ), | |
| 1315 | - '', | |
| 1316 | - 'clear description' | |
| 1317 | - ); | |
| 1318 | - $registrations_to_apply_payment_to .= EEH_HTML::divx(); | |
| 1319 | - $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to; | |
| 1320 | - } | |
| 1321 | - | |
| 1322 | - | |
| 1323 | - /** | |
| 1324 | - * _get_reg_status_selection | |
| 1325 | - * | |
| 1326 | - * @todo this will need to be adjusted either once MER comes along OR we move default reg status to tickets | |
| 1327 | - * instead of events. | |
| 1328 | - * @access protected | |
| 1329 | - * @return void | |
| 1330 | - * @throws EE_Error | |
| 1331 | - */ | |
| 1332 | - protected function _get_reg_status_selection() | |
| 1333 | -    { | |
| 1334 | - // first get all possible statuses | |
| 1335 | - $statuses = EEM_Registration::reg_status_array(array(), true); | |
| 1336 | - // let's add a "don't change" option. | |
| 1337 | -        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso'); | |
| 1338 | - $status_array = array_merge($status_array, $statuses); | |
| 1339 | - $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input( | |
| 1340 | - 'txn_reg_status_change[reg_status]', | |
| 1341 | - $status_array, | |
| 1342 | - 'NAN', | |
| 1343 | - 'id="txn-admin-payment-reg-status-inp"', | |
| 1344 | - 'txn-reg-status-change-reg-status' | |
| 1345 | - ); | |
| 1346 | - $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input( | |
| 1347 | - 'delete_txn_reg_status_change[reg_status]', | |
| 1348 | - $status_array, | |
| 1349 | - 'NAN', | |
| 1350 | - 'delete-txn-admin-payment-reg-status-inp', | |
| 1351 | - 'delete-txn-reg-status-change-reg-status' | |
| 1352 | - ); | |
| 1353 | - } | |
| 1354 | - | |
| 1355 | - | |
| 1356 | - /** | |
| 1357 | - * _get_payment_methods | |
| 1358 | - * Gets all the payment methods available generally, or the ones that are already | |
| 1359 | - * selected on these payments (in case their payment methods are no longer active). | |
| 1360 | - * Has the side-effect of updating the template args' payment_methods item | |
| 1361 | - * | |
| 1362 | - * @access private | |
| 1363 | - * @param EE_Payment[] to show on this page | |
| 1364 | - * @return void | |
| 1365 | - * @throws EE_Error | |
| 1366 | - * @throws InvalidArgumentException | |
| 1367 | - * @throws InvalidDataTypeException | |
| 1368 | - * @throws InvalidInterfaceException | |
| 1369 | - * @throws ReflectionException | |
| 1370 | - */ | |
| 1371 | - private function _get_payment_methods($payments = array()) | |
| 1372 | -    { | |
| 1373 | - $payment_methods_of_payments = array(); | |
| 1374 | -        foreach ($payments as $payment) { | |
| 1375 | -            if ($payment instanceof EE_Payment) { | |
| 1376 | -                $payment_methods_of_payments[] = $payment->get('PMD_ID'); | |
| 1377 | - } | |
| 1378 | - } | |
| 1379 | -        if ($payment_methods_of_payments) { | |
| 1380 | - $query_args = array( | |
| 1381 | - array( | |
| 1382 | - 'OR*payment_method_for_payment' => array( | |
| 1383 | -                        'PMD_ID'    => array('IN', $payment_methods_of_payments), | |
| 1384 | -                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'), | |
| 1385 | - ), | |
| 1386 | - ), | |
| 1387 | - ); | |
| 1388 | -        } else { | |
| 1389 | -            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'))); | |
| 1390 | - } | |
| 1391 | - $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args); | |
| 1392 | - } | |
| 1393 | - | |
| 1394 | - | |
| 1395 | - /** | |
| 1396 | - * txn_attendees_meta_box | |
| 1397 | - * generates HTML for the Attendees Transaction main meta box | |
| 1398 | - * | |
| 1399 | - * @access public | |
| 1400 | - * @param WP_Post $post | |
| 1401 | - * @param array $metabox | |
| 1402 | - * @return void | |
| 1403 | - * @throws DomainException | |
| 1404 | - * @throws EE_Error | |
| 1405 | - */ | |
| 1406 | -    public function txn_attendees_meta_box($post, $metabox = array('args' => array())) | |
| 1407 | -    { | |
| 1408 | - | |
| 1409 | - /** @noinspection NonSecureExtractUsageInspection */ | |
| 1410 | - extract($metabox['args']); | |
| 1411 | - $this->_template_args['post'] = $post; | |
| 1412 | - $this->_template_args['event_attendees'] = array(); | |
| 1413 | - // process items in cart | |
| 1414 | - $line_items = $this->_transaction->get_many_related( | |
| 1415 | - 'Line_Item', | |
| 1416 | -            array(array('LIN_type' => 'line-item')) | |
| 1417 | - ); | |
| 1418 | -        if (! empty($line_items)) { | |
| 1419 | -            foreach ($line_items as $item) { | |
| 1420 | -                if ($item instanceof EE_Line_Item) { | |
| 1421 | -                    switch ($item->OBJ_type()) { | |
| 1422 | - case 'Event': | |
| 1423 | - break; | |
| 1424 | - case 'Ticket': | |
| 1425 | - $ticket = $item->ticket(); | |
| 1426 | - // right now we're only handling tickets here. | |
| 1427 | - // Cause its expected that only tickets will have attendees right? | |
| 1428 | -                            if (! $ticket instanceof EE_Ticket) { | |
| 1429 | - break; | |
| 1430 | - } | |
| 1431 | -                            try { | |
| 1432 | - $event_name = $ticket->get_event_name(); | |
| 1433 | -                            } catch (Exception $e) { | |
| 1434 | - EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 1435 | -                                $event_name = esc_html__('Unknown Event', 'event_espresso'); | |
| 1436 | - } | |
| 1437 | -                            $event_name .= ' - ' . $item->get('LIN_name'); | |
| 1438 | -                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price')); | |
| 1439 | - // now get all of the registrations for this transaction that use this ticket | |
| 1440 | - $registrations = $ticket->get_many_related( | |
| 1441 | - 'Registration', | |
| 1442 | -                                array(array('TXN_ID' => $this->_transaction->ID())) | |
| 1443 | - ); | |
| 1444 | -                            foreach ($registrations as $registration) { | |
| 1445 | -                                if (! $registration instanceof EE_Registration) { | |
| 1446 | - break; | |
| 1447 | - } | |
| 1448 | - $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID'] | |
| 1449 | - = $registration->status_ID(); | |
| 1450 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_num'] | |
| 1451 | - = $registration->count(); | |
| 1452 | - $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name'] | |
| 1453 | - = $event_name; | |
| 1454 | - $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price'] | |
| 1455 | - = $ticket_price; | |
| 1456 | - // attendee info | |
| 1457 | -                                $attendee = $registration->get_first_related('Attendee'); | |
| 1458 | -                                if ($attendee instanceof EE_Attendee) { | |
| 1459 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] | |
| 1460 | - = $attendee->ID(); | |
| 1461 | - $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] | |
| 1462 | - = $attendee->full_name(); | |
| 1463 | - $this->_template_args['event_attendees'][ $registration->ID() ]['email'] | |
| 1464 | - = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name | |
| 1465 | - . esc_html__( | |
| 1466 | - ' Event', | |
| 1467 | - 'event_espresso' | |
| 1468 | - ) | |
| 1469 | - . '">' . $attendee->email() . '</a>'; | |
| 1470 | - $this->_template_args['event_attendees'][ $registration->ID() ]['address'] | |
| 1471 | - = EEH_Address::format($attendee, 'inline', false, false); | |
| 1472 | -                                } else { | |
| 1473 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = ''; | |
| 1474 | - $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = ''; | |
| 1475 | - $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = ''; | |
| 1476 | - $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = ''; | |
| 1477 | - } | |
| 1478 | - } | |
| 1479 | - break; | |
| 1480 | - } | |
| 1481 | - } | |
| 1482 | - } | |
| 1483 | - | |
| 1484 | - $this->_template_args['transaction_form_url'] = add_query_arg( | |
| 1485 | - array( | |
| 1486 | - 'action' => 'edit_transaction', | |
| 1487 | - 'process' => 'attendees', | |
| 1488 | - ), | |
| 1489 | - TXN_ADMIN_URL | |
| 1490 | - ); | |
| 1491 | - echo EEH_Template::display_template( | |
| 1492 | - TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php', | |
| 1493 | - $this->_template_args, | |
| 1494 | - true | |
| 1495 | - ); | |
| 1496 | -        } else { | |
| 1497 | - echo sprintf( | |
| 1498 | - esc_html__( | |
| 1499 | - '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s', | |
| 1500 | - 'event_espresso' | |
| 1501 | - ), | |
| 1502 | - '<p class="important-notice">', | |
| 1503 | - '</p>' | |
| 1504 | - ); | |
| 1505 | - } | |
| 1506 | - } | |
| 1507 | - | |
| 1508 | - | |
| 1509 | - /** | |
| 1510 | - * txn_registrant_side_meta_box | |
| 1511 | - * generates HTML for the Edit Transaction side meta box | |
| 1512 | - * | |
| 1513 | - * @access public | |
| 1514 | - * @return void | |
| 1515 | - * @throws DomainException | |
| 1516 | - * @throws EE_Error | |
| 1517 | - * @throws InvalidArgumentException | |
| 1518 | - * @throws InvalidDataTypeException | |
| 1519 | - * @throws InvalidInterfaceException | |
| 1520 | - * @throws ReflectionException | |
| 1521 | - */ | |
| 1522 | - public function txn_registrant_side_meta_box() | |
| 1523 | -    { | |
| 1524 | - $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration | |
| 1525 | -            ? $this->_transaction->primary_registration()->get_first_related('Attendee') | |
| 1526 | - : null; | |
| 1527 | -        if (! $primary_att instanceof EE_Attendee) { | |
| 1528 | - $this->_template_args['no_attendee_message'] = esc_html__( | |
| 1529 | - 'There is no attached contact for this transaction. The transaction either failed due to an error or was abandoned.', | |
| 1530 | - 'event_espresso' | |
| 1531 | - ); | |
| 1532 | - $primary_att = EEM_Attendee::instance()->create_default_object(); | |
| 1533 | - } | |
| 1534 | - $this->_template_args['ATT_ID'] = $primary_att->ID(); | |
| 1535 | - $this->_template_args['prime_reg_fname'] = $primary_att->fname(); | |
| 1536 | - $this->_template_args['prime_reg_lname'] = $primary_att->lname(); | |
| 1537 | - $this->_template_args['prime_reg_email'] = $primary_att->email(); | |
| 1538 | - $this->_template_args['prime_reg_phone'] = $primary_att->phone(); | |
| 1539 | - $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce( | |
| 1540 | - array( | |
| 1541 | - 'action' => 'edit_attendee', | |
| 1542 | - 'post' => $primary_att->ID(), | |
| 1543 | - ), | |
| 1544 | - REG_ADMIN_URL | |
| 1545 | - ); | |
| 1546 | - // get formatted address for registrant | |
| 1547 | - $this->_template_args['formatted_address'] = EEH_Address::format($primary_att); | |
| 1548 | - echo EEH_Template::display_template( | |
| 1549 | - TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php', | |
| 1550 | - $this->_template_args, | |
| 1551 | - true | |
| 1552 | - ); | |
| 1553 | - } | |
| 1554 | - | |
| 1555 | - | |
| 1556 | - /** | |
| 1557 | - * txn_billing_info_side_meta_box | |
| 1558 | - * generates HTML for the Edit Transaction side meta box | |
| 1559 | - * | |
| 1560 | - * @access public | |
| 1561 | - * @return void | |
| 1562 | - * @throws DomainException | |
| 1563 | - * @throws EE_Error | |
| 1564 | - */ | |
| 1565 | - public function txn_billing_info_side_meta_box() | |
| 1566 | -    { | |
| 1567 | - | |
| 1568 | - $this->_template_args['billing_form'] = $this->_transaction->billing_info(); | |
| 1569 | - $this->_template_args['billing_form_url'] = add_query_arg( | |
| 1570 | -            array('action' => 'edit_transaction', 'process' => 'billing'), | |
| 1571 | - TXN_ADMIN_URL | |
| 1572 | - ); | |
| 1573 | - | |
| 1574 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php'; | |
| 1575 | - echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/ | |
| 1576 | - } | |
| 1577 | - | |
| 1578 | - | |
| 1579 | - /** | |
| 1580 | - * apply_payments_or_refunds | |
| 1581 | - * registers a payment or refund made towards a transaction | |
| 1582 | - * | |
| 1583 | - * @access public | |
| 1584 | - * @return void | |
| 1585 | - * @throws EE_Error | |
| 1586 | - * @throws InvalidArgumentException | |
| 1587 | - * @throws ReflectionException | |
| 1588 | - * @throws RuntimeException | |
| 1589 | - * @throws InvalidDataTypeException | |
| 1590 | - * @throws InvalidInterfaceException | |
| 1591 | - */ | |
| 1592 | - public function apply_payments_or_refunds() | |
| 1593 | -    { | |
| 1594 | -        $json_response_data = array('return_data' => false); | |
| 1595 | - $valid_data = $this->_validate_payment_request_data(); | |
| 1596 | - $has_access = EE_Registry::instance()->CAP->current_user_can( | |
| 1597 | - 'ee_edit_payments', | |
| 1598 | - 'apply_payment_or_refund_from_registration_details' | |
| 1599 | - ); | |
| 1600 | -        if (! empty($valid_data) && $has_access) { | |
| 1601 | - $PAY_ID = $valid_data['PAY_ID']; | |
| 1602 | - // save the new payment | |
| 1603 | - $payment = $this->_create_payment_from_request_data($valid_data); | |
| 1604 | - // get the TXN for this payment | |
| 1605 | - $transaction = $payment->transaction(); | |
| 1606 | - // verify transaction | |
| 1607 | -            if ($transaction instanceof EE_Transaction) { | |
| 1608 | - // calculate_total_payments_and_update_status | |
| 1609 | - $this->_process_transaction_payments($transaction); | |
| 1610 | - $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment); | |
| 1611 | - $this->_remove_existing_registration_payments($payment, $PAY_ID); | |
| 1612 | - // apply payment to registrations (if applicable) | |
| 1613 | -                if (! empty($REG_IDs)) { | |
| 1614 | - $this->_update_registration_payments($transaction, $payment, $REG_IDs); | |
| 1615 | - $this->_maybe_send_notifications(); | |
| 1616 | - // now process status changes for the same registrations | |
| 1617 | - $this->_process_registration_status_change($transaction, $REG_IDs); | |
| 1618 | - } | |
| 1619 | - $this->_maybe_send_notifications($payment); | |
| 1620 | - // prepare to render page | |
| 1621 | - $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs); | |
| 1622 | - do_action( | |
| 1623 | - 'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording', | |
| 1624 | - $transaction, | |
| 1625 | - $payment | |
| 1626 | - ); | |
| 1627 | -            } else { | |
| 1628 | - EE_Error::add_error( | |
| 1629 | - esc_html__( | |
| 1630 | - 'A valid Transaction for this payment could not be retrieved.', | |
| 1631 | - 'event_espresso' | |
| 1632 | - ), | |
| 1633 | - __FILE__, | |
| 1634 | - __FUNCTION__, | |
| 1635 | - __LINE__ | |
| 1636 | - ); | |
| 1637 | - } | |
| 1638 | -        } else { | |
| 1639 | -            if ($has_access) { | |
| 1640 | - EE_Error::add_error( | |
| 1641 | - esc_html__( | |
| 1642 | - 'The payment form data could not be processed. Please try again.', | |
| 1643 | - 'event_espresso' | |
| 1644 | - ), | |
| 1645 | - __FILE__, | |
| 1646 | - __FUNCTION__, | |
| 1647 | - __LINE__ | |
| 1648 | - ); | |
| 1649 | -            } else { | |
| 1650 | - EE_Error::add_error( | |
| 1651 | - esc_html__( | |
| 1652 | - 'You do not have access to apply payments or refunds to a registration.', | |
| 1653 | - 'event_espresso' | |
| 1654 | - ), | |
| 1655 | - __FILE__, | |
| 1656 | - __FUNCTION__, | |
| 1657 | - __LINE__ | |
| 1658 | - ); | |
| 1659 | - } | |
| 1660 | - } | |
| 1661 | - $notices = EE_Error::get_notices( | |
| 1662 | - false, | |
| 1663 | - false, | |
| 1664 | - false | |
| 1665 | - ); | |
| 1666 | - $this->_template_args = array( | |
| 1667 | - 'data' => $json_response_data, | |
| 1668 | - 'error' => $notices['errors'], | |
| 1669 | - 'success' => $notices['success'], | |
| 1670 | - ); | |
| 1671 | - $this->_return_json(); | |
| 1672 | - } | |
| 1673 | - | |
| 1674 | - | |
| 1675 | - /** | |
| 1676 | - * _validate_payment_request_data | |
| 1677 | - * | |
| 1678 | - * @return array | |
| 1679 | - * @throws EE_Error | |
| 1680 | - */ | |
| 1681 | - protected function _validate_payment_request_data() | |
| 1682 | -    { | |
| 1683 | -        if (! isset($this->_req_data['txn_admin_payment'])) { | |
| 1684 | - return false; | |
| 1685 | - } | |
| 1686 | - $payment_form = $this->_generate_payment_form_section(); | |
| 1687 | -        try { | |
| 1688 | -            if ($payment_form->was_submitted()) { | |
| 1689 | - $payment_form->receive_form_submission(); | |
| 1690 | -                if (! $payment_form->is_valid()) { | |
| 1691 | - $submission_error_messages = array(); | |
| 1692 | -                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) { | |
| 1693 | -                        if ($validation_error instanceof EE_Validation_Error) { | |
| 1694 | - $submission_error_messages[] = sprintf( | |
| 1695 | -                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'), | |
| 1696 | - $validation_error->get_form_section()->html_label_text(), | |
| 1697 | - $validation_error->getMessage() | |
| 1698 | - ); | |
| 1699 | - } | |
| 1700 | - } | |
| 1701 | - EE_Error::add_error( | |
| 1702 | -                        implode('<br />', $submission_error_messages), | |
| 1703 | - __FILE__, | |
| 1704 | - __FUNCTION__, | |
| 1705 | - __LINE__ | |
| 1706 | - ); | |
| 1707 | - | |
| 1708 | - return array(); | |
| 1709 | - } | |
| 1710 | - } | |
| 1711 | -        } catch (EE_Error $e) { | |
| 1712 | - EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 1713 | - | |
| 1714 | - return array(); | |
| 1715 | - } | |
| 1716 | - | |
| 1717 | - return $payment_form->valid_data(); | |
| 1718 | - } | |
| 1719 | - | |
| 1720 | - | |
| 1721 | - /** | |
| 1722 | - * _generate_payment_form_section | |
| 1723 | - * | |
| 1724 | - * @return EE_Form_Section_Proper | |
| 1725 | - * @throws EE_Error | |
| 1726 | - */ | |
| 1727 | - protected function _generate_payment_form_section() | |
| 1728 | -    { | |
| 1729 | - return new EE_Form_Section_Proper( | |
| 1730 | - array( | |
| 1731 | - 'name' => 'txn_admin_payment', | |
| 1732 | - 'subsections' => array( | |
| 1733 | - 'PAY_ID' => new EE_Text_Input( | |
| 1734 | - array( | |
| 1735 | - 'default' => 0, | |
| 1736 | - 'required' => false, | |
| 1737 | -                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'), | |
| 1738 | - 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1739 | - ) | |
| 1740 | - ), | |
| 1741 | - 'TXN_ID' => new EE_Text_Input( | |
| 1742 | - array( | |
| 1743 | - 'default' => 0, | |
| 1744 | - 'required' => true, | |
| 1745 | -                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'), | |
| 1746 | - 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1747 | - ) | |
| 1748 | - ), | |
| 1749 | - 'type' => new EE_Text_Input( | |
| 1750 | - array( | |
| 1751 | - 'default' => 1, | |
| 1752 | - 'required' => true, | |
| 1753 | -                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'), | |
| 1754 | - 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1755 | - ) | |
| 1756 | - ), | |
| 1757 | - 'amount' => new EE_Text_Input( | |
| 1758 | - array( | |
| 1759 | - 'default' => 0, | |
| 1760 | - 'required' => true, | |
| 1761 | -                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'), | |
| 1762 | - 'validation_strategies' => array(new EE_Float_Normalization()), | |
| 1763 | - ) | |
| 1764 | - ), | |
| 1765 | - 'status' => new EE_Text_Input( | |
| 1766 | - array( | |
| 1767 | - 'default' => EEM_Payment::status_id_approved, | |
| 1768 | - 'required' => true, | |
| 1769 | -                            'html_label_text' => esc_html__('Payment status', 'event_espresso'), | |
| 1770 | - ) | |
| 1771 | - ), | |
| 1772 | - 'PMD_ID' => new EE_Text_Input( | |
| 1773 | - array( | |
| 1774 | - 'default' => 2, | |
| 1775 | - 'required' => true, | |
| 1776 | -                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'), | |
| 1777 | - 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1778 | - ) | |
| 1779 | - ), | |
| 1780 | - 'date' => new EE_Text_Input( | |
| 1781 | - array( | |
| 1782 | - 'default' => time(), | |
| 1783 | - 'required' => true, | |
| 1784 | -                            'html_label_text' => esc_html__('Payment date', 'event_espresso'), | |
| 1785 | - ) | |
| 1786 | - ), | |
| 1787 | - 'txn_id_chq_nmbr' => new EE_Text_Input( | |
| 1788 | - array( | |
| 1789 | - 'default' => '', | |
| 1790 | - 'required' => false, | |
| 1791 | -                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'), | |
| 1792 | - 'validation_strategies' => array( | |
| 1793 | - new EE_Max_Length_Validation_Strategy( | |
| 1794 | -                                    esc_html__('Input too long', 'event_espresso'), | |
| 1795 | - 100 | |
| 1796 | - ), | |
| 1797 | - ), | |
| 1798 | - ) | |
| 1799 | - ), | |
| 1800 | - 'po_number' => new EE_Text_Input( | |
| 1801 | - array( | |
| 1802 | - 'default' => '', | |
| 1803 | - 'required' => false, | |
| 1804 | -                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'), | |
| 1805 | - 'validation_strategies' => array( | |
| 1806 | - new EE_Max_Length_Validation_Strategy( | |
| 1807 | -                                    esc_html__('Input too long', 'event_espresso'), | |
| 1808 | - 100 | |
| 1809 | - ), | |
| 1810 | - ), | |
| 1811 | - ) | |
| 1812 | - ), | |
| 1813 | - 'accounting' => new EE_Text_Input( | |
| 1814 | - array( | |
| 1815 | - 'default' => '', | |
| 1816 | - 'required' => false, | |
| 1817 | -                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'), | |
| 1818 | - 'validation_strategies' => array( | |
| 1819 | - new EE_Max_Length_Validation_Strategy( | |
| 1820 | -                                    esc_html__('Input too long', 'event_espresso'), | |
| 1821 | - 100 | |
| 1822 | - ), | |
| 1823 | - ), | |
| 1824 | - ) | |
| 1825 | - ), | |
| 1826 | - ), | |
| 1827 | - ) | |
| 1828 | - ); | |
| 1829 | - } | |
| 1830 | - | |
| 1831 | - | |
| 1832 | - /** | |
| 1833 | - * _create_payment_from_request_data | |
| 1834 | - * | |
| 1835 | - * @param array $valid_data | |
| 1836 | - * @return EE_Payment | |
| 1837 | - * @throws EE_Error | |
| 1838 | - */ | |
| 1839 | - protected function _create_payment_from_request_data($valid_data) | |
| 1840 | -    { | |
| 1841 | - $PAY_ID = $valid_data['PAY_ID']; | |
| 1842 | - // get payment amount | |
| 1843 | - $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0; | |
| 1844 | - // payments have a type value of 1 and refunds have a type value of -1 | |
| 1845 | - // so multiplying amount by type will give a positive value for payments, and negative values for refunds | |
| 1846 | - $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount; | |
| 1847 | - // for some reason the date string coming in has extra spaces between the date and time. This fixes that. | |
| 1848 | - $date = $valid_data['date'] | |
| 1849 | -            ? preg_replace('/\s+/', ' ', $valid_data['date']) | |
| 1850 | -            : date('Y-m-d g:i a', current_time('timestamp')); | |
| 1851 | - $payment = EE_Payment::new_instance( | |
| 1852 | - array( | |
| 1853 | - 'TXN_ID' => $valid_data['TXN_ID'], | |
| 1854 | - 'STS_ID' => $valid_data['status'], | |
| 1855 | - 'PAY_timestamp' => $date, | |
| 1856 | - 'PAY_source' => EEM_Payment_Method::scope_admin, | |
| 1857 | - 'PMD_ID' => $valid_data['PMD_ID'], | |
| 1858 | - 'PAY_amount' => $amount, | |
| 1859 | - 'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'], | |
| 1860 | - 'PAY_po_number' => $valid_data['po_number'], | |
| 1861 | - 'PAY_extra_accntng' => $valid_data['accounting'], | |
| 1862 | - 'PAY_details' => $valid_data, | |
| 1863 | - 'PAY_ID' => $PAY_ID, | |
| 1864 | - ), | |
| 1865 | - '', | |
| 1866 | -            array('Y-m-d', 'g:i a') | |
| 1867 | - ); | |
| 1868 | - | |
| 1869 | -        if (! $payment->save()) { | |
| 1870 | - EE_Error::add_error( | |
| 1871 | - sprintf( | |
| 1872 | -                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'), | |
| 1873 | - $payment->ID() | |
| 1874 | - ), | |
| 1875 | - __FILE__, | |
| 1876 | - __FUNCTION__, | |
| 1877 | - __LINE__ | |
| 1878 | - ); | |
| 1879 | - } | |
| 1880 | - | |
| 1881 | - return $payment; | |
| 1882 | - } | |
| 1883 | - | |
| 1884 | - | |
| 1885 | - /** | |
| 1886 | - * _process_transaction_payments | |
| 1887 | - * | |
| 1888 | - * @param \EE_Transaction $transaction | |
| 1889 | - * @return void | |
| 1890 | - * @throws EE_Error | |
| 1891 | - * @throws InvalidArgumentException | |
| 1892 | - * @throws ReflectionException | |
| 1893 | - * @throws InvalidDataTypeException | |
| 1894 | - * @throws InvalidInterfaceException | |
| 1895 | - */ | |
| 1896 | - protected function _process_transaction_payments(EE_Transaction $transaction) | |
| 1897 | -    { | |
| 1898 | - /** @type EE_Transaction_Payments $transaction_payments */ | |
| 1899 | -        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 1900 | - // update the transaction with this payment | |
| 1901 | -        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) { | |
| 1902 | - EE_Error::add_success( | |
| 1903 | - esc_html__( | |
| 1904 | - 'The payment has been processed successfully.', | |
| 1905 | - 'event_espresso' | |
| 1906 | - ), | |
| 1907 | - __FILE__, | |
| 1908 | - __FUNCTION__, | |
| 1909 | - __LINE__ | |
| 1910 | - ); | |
| 1911 | -        } else { | |
| 1912 | - EE_Error::add_error( | |
| 1913 | - esc_html__( | |
| 1914 | - 'The payment was processed successfully but the amount paid for the transaction was not updated.', | |
| 1915 | - 'event_espresso' | |
| 1916 | - ), | |
| 1917 | - __FILE__, | |
| 1918 | - __FUNCTION__, | |
| 1919 | - __LINE__ | |
| 1920 | - ); | |
| 1921 | - } | |
| 1922 | - } | |
| 1923 | - | |
| 1924 | - | |
| 1925 | - /** | |
| 1926 | - * _get_REG_IDs_to_apply_payment_to | |
| 1927 | - * returns a list of registration IDs that the payment will apply to | |
| 1928 | - * | |
| 1929 | - * @param \EE_Payment $payment | |
| 1930 | - * @return array | |
| 1931 | - * @throws EE_Error | |
| 1932 | - */ | |
| 1933 | - protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment) | |
| 1934 | -    { | |
| 1935 | - $REG_IDs = array(); | |
| 1936 | - // grab array of IDs for specific registrations to apply changes to | |
| 1937 | -        if (isset($this->_req_data['txn_admin_payment']['registrations'])) { | |
| 1938 | - $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations']; | |
| 1939 | - } | |
| 1940 | - // nothing specified ? then get all reg IDs | |
| 1941 | -        if (empty($REG_IDs)) { | |
| 1942 | - $registrations = $payment->transaction()->registrations(); | |
| 1943 | - $REG_IDs = ! empty($registrations) | |
| 1944 | - ? array_keys($registrations) | |
| 1945 | - : $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 1946 | - } | |
| 1947 | - | |
| 1948 | - // ensure that REG_IDs are integers and NOT strings | |
| 1949 | -        return array_map('intval', $REG_IDs); | |
| 1950 | - } | |
| 1951 | - | |
| 1952 | - | |
| 1953 | - /** | |
| 1954 | - * @return array | |
| 1955 | - */ | |
| 1956 | - public function existing_reg_payment_REG_IDs() | |
| 1957 | -    { | |
| 1958 | - return $this->_existing_reg_payment_REG_IDs; | |
| 1959 | - } | |
| 1960 | - | |
| 1961 | - | |
| 1962 | - /** | |
| 1963 | - * @param array $existing_reg_payment_REG_IDs | |
| 1964 | - */ | |
| 1965 | - public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null) | |
| 1966 | -    { | |
| 1967 | - $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs; | |
| 1968 | - } | |
| 1969 | - | |
| 1970 | - | |
| 1971 | - /** | |
| 1972 | - * _get_existing_reg_payment_REG_IDs | |
| 1973 | - * returns a list of registration IDs that the payment is currently related to | |
| 1974 | - * as recorded in the database | |
| 1975 | - * | |
| 1976 | - * @param \EE_Payment $payment | |
| 1977 | - * @return array | |
| 1978 | - * @throws EE_Error | |
| 1979 | - */ | |
| 1980 | - protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment) | |
| 1981 | -    { | |
| 1982 | -        if ($this->existing_reg_payment_REG_IDs() === null) { | |
| 1983 | - // let's get any existing reg payment records for this payment | |
| 1984 | -            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration'); | |
| 1985 | - // but we only want the REG IDs, so grab the array keys | |
| 1986 | - $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs) | |
| 1987 | - ? array_keys($existing_reg_payment_REG_IDs) | |
| 1988 | - : array(); | |
| 1989 | - $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs); | |
| 1990 | - } | |
| 1991 | - | |
| 1992 | - return $this->existing_reg_payment_REG_IDs(); | |
| 1993 | - } | |
| 1994 | - | |
| 1995 | - | |
| 1996 | - /** | |
| 1997 | - * _remove_existing_registration_payments | |
| 1998 | - * this calculates the difference between existing relations | |
| 1999 | - * to the supplied payment and the new list registration IDs, | |
| 2000 | - * removes any related registrations that no longer apply, | |
| 2001 | - * and then updates the registration paid fields | |
| 2002 | - * | |
| 2003 | - * @param \EE_Payment $payment | |
| 2004 | - * @param int $PAY_ID | |
| 2005 | - * @return bool; | |
| 2006 | - * @throws EE_Error | |
| 2007 | - * @throws InvalidArgumentException | |
| 2008 | - * @throws ReflectionException | |
| 2009 | - * @throws InvalidDataTypeException | |
| 2010 | - * @throws InvalidInterfaceException | |
| 2011 | - */ | |
| 2012 | - protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0) | |
| 2013 | -    { | |
| 2014 | - // newly created payments will have nothing recorded for $PAY_ID | |
| 2015 | -        if ($PAY_ID == 0) { | |
| 2016 | - return false; | |
| 2017 | - } | |
| 2018 | - $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 2019 | -        if (empty($existing_reg_payment_REG_IDs)) { | |
| 2020 | - return false; | |
| 2021 | - } | |
| 2022 | - /** @type EE_Transaction_Payments $transaction_payments */ | |
| 2023 | -        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 2024 | - | |
| 2025 | - return $transaction_payments->delete_registration_payments_and_update_registrations( | |
| 2026 | - $payment, | |
| 2027 | - array( | |
| 2028 | - array( | |
| 2029 | - 'PAY_ID' => $payment->ID(), | |
| 2030 | -                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs), | |
| 2031 | - ), | |
| 2032 | - ) | |
| 2033 | - ); | |
| 2034 | - } | |
| 2035 | - | |
| 2036 | - | |
| 2037 | - /** | |
| 2038 | - * _update_registration_payments | |
| 2039 | - * this applies the payments to the selected registrations | |
| 2040 | - * but only if they have not already been paid for | |
| 2041 | - * | |
| 2042 | - * @param EE_Transaction $transaction | |
| 2043 | - * @param \EE_Payment $payment | |
| 2044 | - * @param array $REG_IDs | |
| 2045 | - * @return void | |
| 2046 | - * @throws EE_Error | |
| 2047 | - * @throws InvalidArgumentException | |
| 2048 | - * @throws ReflectionException | |
| 2049 | - * @throws RuntimeException | |
| 2050 | - * @throws InvalidDataTypeException | |
| 2051 | - * @throws InvalidInterfaceException | |
| 2052 | - */ | |
| 2053 | - protected function _update_registration_payments( | |
| 2054 | - EE_Transaction $transaction, | |
| 2055 | - EE_Payment $payment, | |
| 2056 | - $REG_IDs = array() | |
| 2057 | -    ) { | |
| 2058 | - // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments() | |
| 2059 | - // so let's do that using our set of REG_IDs from the form | |
| 2060 | - $registration_query_where_params = array( | |
| 2061 | -            'REG_ID' => array('IN', $REG_IDs), | |
| 2062 | - ); | |
| 2063 | - // but add in some conditions regarding payment, | |
| 2064 | - // so that we don't apply payments to registrations that are free or have already been paid for | |
| 2065 | - // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative ) | |
| 2066 | -        if (! $payment->is_a_refund()) { | |
| 2067 | -            $registration_query_where_params['REG_final_price'] = array('!=', 0); | |
| 2068 | -            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true); | |
| 2069 | - } | |
| 2070 | - $registrations = $transaction->registrations(array($registration_query_where_params)); | |
| 2071 | -        if (! empty($registrations)) { | |
| 2072 | - /** @type EE_Payment_Processor $payment_processor */ | |
| 2073 | -            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor'); | |
| 2074 | - $payment_processor->process_registration_payments($transaction, $payment, $registrations); | |
| 2075 | - } | |
| 2076 | - } | |
| 2077 | - | |
| 2078 | - | |
| 2079 | - /** | |
| 2080 | - * _process_registration_status_change | |
| 2081 | - * This processes requested registration status changes for all the registrations | |
| 2082 | - * on a given transaction and (optionally) sends out notifications for the changes. | |
| 2083 | - * | |
| 2084 | - * @param EE_Transaction $transaction | |
| 2085 | - * @param array $REG_IDs | |
| 2086 | - * @return bool | |
| 2087 | - * @throws EE_Error | |
| 2088 | - * @throws InvalidArgumentException | |
| 2089 | - * @throws ReflectionException | |
| 2090 | - * @throws InvalidDataTypeException | |
| 2091 | - * @throws InvalidInterfaceException | |
| 2092 | - */ | |
| 2093 | - protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array()) | |
| 2094 | -    { | |
| 2095 | - // first if there is no change in status then we get out. | |
| 2096 | - if (! isset($this->_req_data['txn_reg_status_change']['reg_status']) | |
| 2097 | - || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN' | |
| 2098 | -        ) { | |
| 2099 | - // no error message, no change requested, just nothing to do man. | |
| 2100 | - return false; | |
| 2101 | - } | |
| 2102 | - /** @type EE_Transaction_Processor $transaction_processor */ | |
| 2103 | -        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor'); | |
| 2104 | - | |
| 2105 | - // made it here dude? Oh WOW. K, let's take care of changing the statuses | |
| 2106 | - return $transaction_processor->manually_update_registration_statuses( | |
| 2107 | - $transaction, | |
| 2108 | - sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']), | |
| 2109 | -            array(array('REG_ID' => array('IN', $REG_IDs))) | |
| 2110 | - ); | |
| 2111 | - } | |
| 2112 | - | |
| 2113 | - | |
| 2114 | - /** | |
| 2115 | - * _build_payment_json_response | |
| 2116 | - * | |
| 2117 | - * @access public | |
| 2118 | - * @param \EE_Payment $payment | |
| 2119 | - * @param array $REG_IDs | |
| 2120 | - * @param bool | null $delete_txn_reg_status_change | |
| 2121 | - * @return array | |
| 2122 | - * @throws EE_Error | |
| 2123 | - * @throws InvalidArgumentException | |
| 2124 | - * @throws InvalidDataTypeException | |
| 2125 | - * @throws InvalidInterfaceException | |
| 2126 | - * @throws ReflectionException | |
| 2127 | - */ | |
| 2128 | - protected function _build_payment_json_response( | |
| 2129 | - EE_Payment $payment, | |
| 2130 | - $REG_IDs = array(), | |
| 2131 | - $delete_txn_reg_status_change = null | |
| 2132 | -    ) { | |
| 2133 | - // was the payment deleted ? | |
| 2134 | -        if (is_bool($delete_txn_reg_status_change)) { | |
| 2135 | - return array( | |
| 2136 | - 'PAY_ID' => $payment->ID(), | |
| 2137 | - 'amount' => $payment->amount(), | |
| 2138 | - 'total_paid' => $payment->transaction()->paid(), | |
| 2139 | - 'txn_status' => $payment->transaction()->status_ID(), | |
| 2140 | - 'pay_status' => $payment->STS_ID(), | |
| 2141 | - 'registrations' => $this->_registration_payment_data_array($REG_IDs), | |
| 2142 | - 'delete_txn_reg_status_change' => $delete_txn_reg_status_change, | |
| 2143 | - ); | |
| 2144 | -        } else { | |
| 2145 | - $this->_get_payment_status_array(); | |
| 2146 | - | |
| 2147 | - return array( | |
| 2148 | - 'amount' => $payment->amount(), | |
| 2149 | - 'total_paid' => $payment->transaction()->paid(), | |
| 2150 | - 'txn_status' => $payment->transaction()->status_ID(), | |
| 2151 | - 'pay_status' => $payment->STS_ID(), | |
| 2152 | - 'PAY_ID' => $payment->ID(), | |
| 2153 | - 'STS_ID' => $payment->STS_ID(), | |
| 2154 | - 'status' => self::$_pay_status[ $payment->STS_ID() ], | |
| 2155 | -                'date'             => $payment->timestamp('Y-m-d', 'h:i a'), | |
| 2156 | - 'method' => strtoupper($payment->source()), | |
| 2157 | - 'PM_ID' => $payment->payment_method() ? $payment->payment_method()->ID() : 1, | |
| 2158 | - 'gateway' => $payment->payment_method() | |
| 2159 | - ? $payment->payment_method()->admin_name() | |
| 2160 | -                    : esc_html__("Unknown", 'event_espresso'), | |
| 2161 | - 'gateway_response' => $payment->gateway_response(), | |
| 2162 | - 'txn_id_chq_nmbr' => $payment->txn_id_chq_nmbr(), | |
| 2163 | - 'po_number' => $payment->po_number(), | |
| 2164 | - 'extra_accntng' => $payment->extra_accntng(), | |
| 2165 | - 'registrations' => $this->_registration_payment_data_array($REG_IDs), | |
| 2166 | - ); | |
| 2167 | - } | |
| 2168 | - } | |
| 2169 | - | |
| 2170 | - | |
| 2171 | - /** | |
| 2172 | - * delete_payment | |
| 2173 | - * delete a payment or refund made towards a transaction | |
| 2174 | - * | |
| 2175 | - * @access public | |
| 2176 | - * @return void | |
| 2177 | - * @throws EE_Error | |
| 2178 | - * @throws InvalidArgumentException | |
| 2179 | - * @throws ReflectionException | |
| 2180 | - * @throws InvalidDataTypeException | |
| 2181 | - * @throws InvalidInterfaceException | |
| 2182 | - */ | |
| 2183 | - public function delete_payment() | |
| 2184 | -    { | |
| 2185 | -        $json_response_data = array('return_data' => false); | |
| 2186 | - $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID']) | |
| 2187 | - ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID']) | |
| 2188 | - : 0; | |
| 2189 | - $can_delete = EE_Registry::instance()->CAP->current_user_can( | |
| 2190 | - 'ee_delete_payments', | |
| 2191 | - 'delete_payment_from_registration_details' | |
| 2192 | - ); | |
| 2193 | -        if ($PAY_ID && $can_delete) { | |
| 2194 | - $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change']) | |
| 2195 | - ? $this->_req_data['delete_txn_reg_status_change'] | |
| 2196 | - : false; | |
| 2197 | - $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID); | |
| 2198 | -            if ($payment instanceof EE_Payment) { | |
| 2199 | - $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 2200 | - /** @type EE_Transaction_Payments $transaction_payments */ | |
| 2201 | -                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 2202 | -                if ($transaction_payments->delete_payment_and_update_transaction($payment)) { | |
| 2203 | - $json_response_data['return_data'] = $this->_build_payment_json_response( | |
| 2204 | - $payment, | |
| 2205 | - $REG_IDs, | |
| 2206 | - $delete_txn_reg_status_change | |
| 2207 | - ); | |
| 2208 | -                    if ($delete_txn_reg_status_change) { | |
| 2209 | - $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change; | |
| 2210 | - // MAKE sure we also add the delete_txn_req_status_change to the | |
| 2211 | - // $_REQUEST global because that's how messages will be looking for it. | |
| 2212 | - $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change; | |
| 2213 | - $this->_maybe_send_notifications(); | |
| 2214 | - $this->_process_registration_status_change($payment->transaction(), $REG_IDs); | |
| 2215 | - } | |
| 2216 | - } | |
| 2217 | -            } else { | |
| 2218 | - EE_Error::add_error( | |
| 2219 | -                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'), | |
| 2220 | - __FILE__, | |
| 2221 | - __FUNCTION__, | |
| 2222 | - __LINE__ | |
| 2223 | - ); | |
| 2224 | - } | |
| 2225 | -        } else { | |
| 2226 | -            if ($can_delete) { | |
| 2227 | - EE_Error::add_error( | |
| 2228 | - esc_html__( | |
| 2229 | - 'A valid Payment ID was not received, therefore payment form data could not be loaded.', | |
| 2230 | - 'event_espresso' | |
| 2231 | - ), | |
| 2232 | - __FILE__, | |
| 2233 | - __FUNCTION__, | |
| 2234 | - __LINE__ | |
| 2235 | - ); | |
| 2236 | -            } else { | |
| 2237 | - EE_Error::add_error( | |
| 2238 | - esc_html__( | |
| 2239 | - 'You do not have access to delete a payment.', | |
| 2240 | - 'event_espresso' | |
| 2241 | - ), | |
| 2242 | - __FILE__, | |
| 2243 | - __FUNCTION__, | |
| 2244 | - __LINE__ | |
| 2245 | - ); | |
| 2246 | - } | |
| 2247 | - } | |
| 2248 | - $notices = EE_Error::get_notices(false, false, false); | |
| 2249 | - $this->_template_args = array( | |
| 2250 | - 'data' => $json_response_data, | |
| 2251 | - 'success' => $notices['success'], | |
| 2252 | - 'error' => $notices['errors'], | |
| 2253 | - 'attention' => $notices['attention'], | |
| 2254 | - ); | |
| 2255 | - $this->_return_json(); | |
| 2256 | - } | |
| 2257 | - | |
| 2258 | - | |
| 2259 | - /** | |
| 2260 | - * _registration_payment_data_array | |
| 2261 | - * adds info for 'owing' and 'paid' for each registration to the json response | |
| 2262 | - * | |
| 2263 | - * @access protected | |
| 2264 | - * @param array $REG_IDs | |
| 2265 | - * @return array | |
| 2266 | - * @throws EE_Error | |
| 2267 | - * @throws InvalidArgumentException | |
| 2268 | - * @throws InvalidDataTypeException | |
| 2269 | - * @throws InvalidInterfaceException | |
| 2270 | - * @throws ReflectionException | |
| 2271 | - */ | |
| 2272 | - protected function _registration_payment_data_array($REG_IDs) | |
| 2273 | -    { | |
| 2274 | - $registration_payment_data = array(); | |
| 2275 | - // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows. | |
| 2276 | -        if (! empty($REG_IDs)) { | |
| 2277 | -            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs)))); | |
| 2278 | -            foreach ($registrations as $registration) { | |
| 2279 | -                if ($registration instanceof EE_Registration) { | |
| 2280 | - $registration_payment_data[ $registration->ID() ] = array( | |
| 2281 | - 'paid' => $registration->pretty_paid(), | |
| 2282 | - 'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()), | |
| 2283 | - ); | |
| 2284 | - } | |
| 2285 | - } | |
| 2286 | - } | |
| 2287 | - | |
| 2288 | - return $registration_payment_data; | |
| 2289 | - } | |
| 2290 | - | |
| 2291 | - | |
| 2292 | - /** | |
| 2293 | - * _maybe_send_notifications | |
| 2294 | - * determines whether or not the admin has indicated that notifications should be sent. | |
| 2295 | - * If so, will toggle a filter switch for delivering registration notices. | |
| 2296 | - * If passed an EE_Payment object, then it will trigger payment notifications instead. | |
| 2297 | - * | |
| 2298 | - * @access protected | |
| 2299 | - * @param \EE_Payment | null $payment | |
| 2300 | - */ | |
| 2301 | - protected function _maybe_send_notifications($payment = null) | |
| 2302 | -    { | |
| 2303 | -        switch ($payment instanceof EE_Payment) { | |
| 2304 | - // payment notifications | |
| 2305 | - case true: | |
| 2306 | - if (isset( | |
| 2307 | - $this->_req_data['txn_payments'], | |
| 2308 | - $this->_req_data['txn_payments']['send_notifications'] | |
| 2309 | - ) | |
| 2310 | - && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN) | |
| 2311 | -                ) { | |
| 2312 | - $this->_process_payment_notification($payment); | |
| 2313 | - } | |
| 2314 | - break; | |
| 2315 | - // registration notifications | |
| 2316 | - case false: | |
| 2317 | - if (isset( | |
| 2318 | - $this->_req_data['txn_reg_status_change'], | |
| 2319 | - $this->_req_data['txn_reg_status_change']['send_notifications'] | |
| 2320 | - ) | |
| 2321 | - && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN) | |
| 2322 | -                ) { | |
| 2323 | -                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true'); | |
| 2324 | - } | |
| 2325 | - break; | |
| 2326 | - } | |
| 2327 | - } | |
| 2328 | - | |
| 2329 | - | |
| 2330 | - /** | |
| 2331 | - * _send_payment_reminder | |
| 2332 | - * generates HTML for the View Transaction Details Admin page | |
| 2333 | - * | |
| 2334 | - * @access protected | |
| 2335 | - * @return void | |
| 2336 | - * @throws EE_Error | |
| 2337 | - * @throws InvalidArgumentException | |
| 2338 | - * @throws InvalidDataTypeException | |
| 2339 | - * @throws InvalidInterfaceException | |
| 2340 | - */ | |
| 2341 | - protected function _send_payment_reminder() | |
| 2342 | -    { | |
| 2343 | - $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false; | |
| 2344 | - $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID); | |
| 2345 | - $query_args = isset($this->_req_data['redirect_to']) ? array( | |
| 2346 | - 'action' => $this->_req_data['redirect_to'], | |
| 2347 | - 'TXN_ID' => $this->_req_data['TXN_ID'], | |
| 2348 | - ) : array(); | |
| 2349 | - do_action( | |
| 2350 | - 'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder', | |
| 2351 | - $transaction | |
| 2352 | - ); | |
| 2353 | - $this->_redirect_after_action( | |
| 2354 | - false, | |
| 2355 | -            esc_html__('payment reminder', 'event_espresso'), | |
| 2356 | -            esc_html__('sent', 'event_espresso'), | |
| 2357 | - $query_args, | |
| 2358 | - true | |
| 2359 | - ); | |
| 2360 | - } | |
| 2361 | - | |
| 2362 | - | |
| 2363 | - /** | |
| 2364 | - * get_transactions | |
| 2365 | - * get transactions for given parameters (used by list table) | |
| 2366 | - * | |
| 2367 | - * @param int $perpage how many transactions displayed per page | |
| 2368 | - * @param boolean $count return the count or objects | |
| 2369 | - * @param string $view | |
| 2370 | - * @return mixed int = count || array of transaction objects | |
| 2371 | - * @throws EE_Error | |
| 2372 | - * @throws InvalidArgumentException | |
| 2373 | - * @throws InvalidDataTypeException | |
| 2374 | - * @throws InvalidInterfaceException | |
| 2375 | - */ | |
| 2376 | - public function get_transactions($perpage, $count = false, $view = '') | |
| 2377 | -    { | |
| 2378 | - | |
| 2379 | - $TXN = EEM_Transaction::instance(); | |
| 2380 | - | |
| 2381 | - $start_date = isset($this->_req_data['txn-filter-start-date']) | |
| 2382 | - ? wp_strip_all_tags($this->_req_data['txn-filter-start-date']) | |
| 2383 | - : date( | |
| 2384 | - 'm/d/Y', | |
| 2385 | -                strtotime('-10 year') | |
| 2386 | - ); | |
| 2387 | - $end_date = isset($this->_req_data['txn-filter-end-date']) | |
| 2388 | - ? wp_strip_all_tags($this->_req_data['txn-filter-end-date']) | |
| 2389 | -            : date('m/d/Y'); | |
| 2390 | - | |
| 2391 | - // make sure our timestamps start and end right at the boundaries for each day | |
| 2392 | -        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00'; | |
| 2393 | -        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59'; | |
| 2394 | - | |
| 2395 | - | |
| 2396 | - // convert to timestamps | |
| 2397 | - $start_date = strtotime($start_date); | |
| 2398 | - $end_date = strtotime($end_date); | |
| 2399 | - | |
| 2400 | - // makes sure start date is the lowest value and vice versa | |
| 2401 | - $start_date = min($start_date, $end_date); | |
| 2402 | - $end_date = max($start_date, $end_date); | |
| 2403 | - | |
| 2404 | - // convert to correct format for query | |
| 2405 | - $start_date = EEM_Transaction::instance()->convert_datetime_for_query( | |
| 2406 | - 'TXN_timestamp', | |
| 2407 | -            date('Y-m-d H:i:s', $start_date), | |
| 2408 | - 'Y-m-d H:i:s' | |
| 2409 | - ); | |
| 2410 | - $end_date = EEM_Transaction::instance()->convert_datetime_for_query( | |
| 2411 | - 'TXN_timestamp', | |
| 2412 | -            date('Y-m-d H:i:s', $end_date), | |
| 2413 | - 'Y-m-d H:i:s' | |
| 2414 | - ); | |
| 2415 | - | |
| 2416 | - | |
| 2417 | - // set orderby | |
| 2418 | - $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : ''; | |
| 2419 | - | |
| 2420 | -        switch ($this->_req_data['orderby']) { | |
| 2421 | - case 'TXN_ID': | |
| 2422 | - $orderby = 'TXN_ID'; | |
| 2423 | - break; | |
| 2424 | - case 'ATT_fname': | |
| 2425 | - $orderby = 'Registration.Attendee.ATT_fname'; | |
| 2426 | - break; | |
| 2427 | - case 'event_name': | |
| 2428 | - $orderby = 'Registration.Event.EVT_name'; | |
| 2429 | - break; | |
| 2430 | - default: // 'TXN_timestamp' | |
| 2431 | - $orderby = 'TXN_timestamp'; | |
| 2432 | - } | |
| 2433 | - | |
| 2434 | - $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC'; | |
| 2435 | - $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1; | |
| 2436 | - $per_page = ! empty($perpage) ? $perpage : 10; | |
| 2437 | - $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page; | |
| 2438 | - | |
| 2439 | - $offset = ($current_page - 1) * $per_page; | |
| 2440 | - $limit = array($offset, $per_page); | |
| 2441 | - | |
| 2442 | - $_where = array( | |
| 2443 | -            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)), | |
| 2444 | - 'Registration.REG_count' => 1, | |
| 2445 | - ); | |
| 2446 | - | |
| 2447 | -        if (isset($this->_req_data['EVT_ID'])) { | |
| 2448 | - $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID']; | |
| 2449 | - } | |
| 2450 | - | |
| 2451 | -        if (isset($this->_req_data['s'])) { | |
| 2452 | - $search_string = '%' . $this->_req_data['s'] . '%'; | |
| 2453 | - $_where['OR'] = array( | |
| 2454 | -                'Registration.Event.EVT_name'         => array('LIKE', $search_string), | |
| 2455 | -                'Registration.Event.EVT_desc'         => array('LIKE', $search_string), | |
| 2456 | -                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string), | |
| 2457 | -                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string), | |
| 2458 | -                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string), | |
| 2459 | -                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string), | |
| 2460 | -                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string), | |
| 2461 | -                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string), | |
| 2462 | -                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string), | |
| 2463 | -                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string), | |
| 2464 | -                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string), | |
| 2465 | -                'Registration.REG_final_price'        => array('LIKE', $search_string), | |
| 2466 | -                'Registration.REG_code'               => array('LIKE', $search_string), | |
| 2467 | -                'Registration.REG_count'              => array('LIKE', $search_string), | |
| 2468 | -                'Registration.REG_group_size'         => array('LIKE', $search_string), | |
| 2469 | -                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string), | |
| 2470 | -                'Registration.Ticket.TKT_description' => array('LIKE', $search_string), | |
| 2471 | -                'Payment.PAY_source'                  => array('LIKE', $search_string), | |
| 2472 | -                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string), | |
| 2473 | -                'TXN_session_data'                    => array('LIKE', $search_string), | |
| 2474 | -                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string), | |
| 2475 | - ); | |
| 2476 | - } | |
| 2477 | - | |
| 2478 | - // failed transactions | |
| 2479 | - $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count) | |
| 2480 | - || ($count && $view === 'failed'); | |
| 2481 | - $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count) | |
| 2482 | - || ($count && $view === 'abandoned'); | |
| 2483 | - $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count) | |
| 2484 | - || ($count && $view === 'incomplete'); | |
| 2485 | - | |
| 2486 | -        if ($failed) { | |
| 2487 | - $_where['STS_ID'] = EEM_Transaction::failed_status_code; | |
| 2488 | -        } elseif ($abandoned) { | |
| 2489 | - $_where['STS_ID'] = EEM_Transaction::abandoned_status_code; | |
| 2490 | -        } elseif ($incomplete) { | |
| 2491 | - $_where['STS_ID'] = EEM_Transaction::incomplete_status_code; | |
| 2492 | -        } else { | |
| 2493 | -            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code); | |
| 2494 | -            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code); | |
| 2495 | - } | |
| 2496 | - | |
| 2497 | - $query_params = apply_filters( | |
| 2498 | - 'FHEE__Transactions_Admin_Page___get_transactions_query_params', | |
| 2499 | - array( | |
| 2500 | - $_where, | |
| 2501 | - 'order_by' => array($orderby => $sort), | |
| 2502 | - 'limit' => $limit, | |
| 2503 | - 'default_where_conditions' => EEM_Base::default_where_conditions_this_only, | |
| 2504 | - ), | |
| 2505 | - $this->_req_data, | |
| 2506 | - $view, | |
| 2507 | - $count | |
| 2508 | - ); | |
| 2509 | - | |
| 2510 | - $transactions = $count | |
| 2511 | - ? $TXN->count(array($query_params[0]), 'TXN_ID', true) | |
| 2512 | - : $TXN->get_all($query_params); | |
| 2513 | - | |
| 2514 | - return $transactions; | |
| 2515 | - } | |
| 17 | + /** | |
| 18 | + * @var EE_Transaction | |
| 19 | + */ | |
| 20 | + private $_transaction; | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * @var EE_Session | |
| 24 | + */ | |
| 25 | + private $_session; | |
| 26 | + | |
| 27 | + /** | |
| 28 | + * @var array $_txn_status | |
| 29 | + */ | |
| 30 | + private static $_txn_status; | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * @var array $_pay_status | |
| 34 | + */ | |
| 35 | + private static $_pay_status; | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * @var array $_existing_reg_payment_REG_IDs | |
| 39 | + */ | |
| 40 | + protected $_existing_reg_payment_REG_IDs = null; | |
| 41 | + | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * @Constructor | |
| 45 | + * @access public | |
| 46 | + * @param bool $routing | |
| 47 | + * @throws EE_Error | |
| 48 | + * @throws InvalidArgumentException | |
| 49 | + * @throws ReflectionException | |
| 50 | + * @throws InvalidDataTypeException | |
| 51 | + * @throws InvalidInterfaceException | |
| 52 | + */ | |
| 53 | + public function __construct($routing = true) | |
| 54 | +	{ | |
| 55 | + parent::__construct($routing); | |
| 56 | + } | |
| 57 | + | |
| 58 | + | |
| 59 | + /** | |
| 60 | + * _init_page_props | |
| 61 | + * | |
| 62 | + * @return void | |
| 63 | + */ | |
| 64 | + protected function _init_page_props() | |
| 65 | +	{ | |
| 66 | + $this->page_slug = TXN_PG_SLUG; | |
| 67 | +		$this->page_label = esc_html__('Transactions', 'event_espresso'); | |
| 68 | + $this->_admin_base_url = TXN_ADMIN_URL; | |
| 69 | + $this->_admin_base_path = TXN_ADMIN; | |
| 70 | + } | |
| 71 | + | |
| 72 | + | |
| 73 | + /** | |
| 74 | + * _ajax_hooks | |
| 75 | + * | |
| 76 | + * @return void | |
| 77 | + */ | |
| 78 | + protected function _ajax_hooks() | |
| 79 | +	{ | |
| 80 | +		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds')); | |
| 81 | +		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds')); | |
| 82 | +		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment')); | |
| 83 | + } | |
| 84 | + | |
| 85 | + | |
| 86 | + /** | |
| 87 | + * _define_page_props | |
| 88 | + * | |
| 89 | + * @return void | |
| 90 | + */ | |
| 91 | + protected function _define_page_props() | |
| 92 | +	{ | |
| 93 | + $this->_admin_page_title = $this->page_label; | |
| 94 | + $this->_labels = array( | |
| 95 | + 'buttons' => array( | |
| 96 | +				'add'    => esc_html__('Add New Transaction', 'event_espresso'), | |
| 97 | +				'edit'   => esc_html__('Edit Transaction', 'event_espresso'), | |
| 98 | +				'delete' => esc_html__('Delete Transaction', 'event_espresso'), | |
| 99 | + ), | |
| 100 | + ); | |
| 101 | + } | |
| 102 | + | |
| 103 | + | |
| 104 | + /** | |
| 105 | + * grab url requests and route them | |
| 106 | + * | |
| 107 | + * @access private | |
| 108 | + * @return void | |
| 109 | + * @throws EE_Error | |
| 110 | + * @throws InvalidArgumentException | |
| 111 | + * @throws InvalidDataTypeException | |
| 112 | + * @throws InvalidInterfaceException | |
| 113 | + */ | |
| 114 | + public function _set_page_routes() | |
| 115 | +	{ | |
| 116 | + | |
| 117 | + $this->_set_transaction_status_array(); | |
| 118 | + | |
| 119 | + $txn_id = ! empty($this->_req_data['TXN_ID']) | |
| 120 | + && ! is_array($this->_req_data['TXN_ID']) | |
| 121 | + ? $this->_req_data['TXN_ID'] | |
| 122 | + : 0; | |
| 123 | + | |
| 124 | + $this->_page_routes = array( | |
| 125 | + | |
| 126 | + 'default' => array( | |
| 127 | + 'func' => '_transactions_overview_list_table', | |
| 128 | + 'capability' => 'ee_read_transactions', | |
| 129 | + ), | |
| 130 | + | |
| 131 | + 'view_transaction' => array( | |
| 132 | + 'func' => '_transaction_details', | |
| 133 | + 'capability' => 'ee_read_transaction', | |
| 134 | + 'obj_id' => $txn_id, | |
| 135 | + ), | |
| 136 | + | |
| 137 | + 'send_payment_reminder' => array( | |
| 138 | + 'func' => '_send_payment_reminder', | |
| 139 | + 'noheader' => true, | |
| 140 | + 'capability' => 'ee_send_message', | |
| 141 | + ), | |
| 142 | + | |
| 143 | + 'espresso_apply_payment' => array( | |
| 144 | + 'func' => 'apply_payments_or_refunds', | |
| 145 | + 'noheader' => true, | |
| 146 | + 'capability' => 'ee_edit_payments', | |
| 147 | + ), | |
| 148 | + | |
| 149 | + 'espresso_apply_refund' => array( | |
| 150 | + 'func' => 'apply_payments_or_refunds', | |
| 151 | + 'noheader' => true, | |
| 152 | + 'capability' => 'ee_edit_payments', | |
| 153 | + ), | |
| 154 | + | |
| 155 | + 'espresso_delete_payment' => array( | |
| 156 | + 'func' => 'delete_payment', | |
| 157 | + 'noheader' => true, | |
| 158 | + 'capability' => 'ee_delete_payments', | |
| 159 | + ), | |
| 160 | + | |
| 161 | + ); | |
| 162 | + } | |
| 163 | + | |
| 164 | + | |
| 165 | + protected function _set_page_config() | |
| 166 | +	{ | |
| 167 | + $this->_page_config = array( | |
| 168 | + 'default' => array( | |
| 169 | + 'nav' => array( | |
| 170 | +					'label' => esc_html__('Overview', 'event_espresso'), | |
| 171 | + 'order' => 10, | |
| 172 | + ), | |
| 173 | + 'list_table' => 'EE_Admin_Transactions_List_Table', | |
| 174 | + 'help_tabs' => array( | |
| 175 | + 'transactions_overview_help_tab' => array( | |
| 176 | +						'title'    => esc_html__('Transactions Overview', 'event_espresso'), | |
| 177 | + 'filename' => 'transactions_overview', | |
| 178 | + ), | |
| 179 | + 'transactions_overview_table_column_headings_help_tab' => array( | |
| 180 | +						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'), | |
| 181 | + 'filename' => 'transactions_overview_table_column_headings', | |
| 182 | + ), | |
| 183 | + 'transactions_overview_views_filters_help_tab' => array( | |
| 184 | +						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'), | |
| 185 | + 'filename' => 'transactions_overview_views_filters_search', | |
| 186 | + ), | |
| 187 | + ), | |
| 188 | +				'help_tour'     => array('Transactions_Overview_Help_Tour'), | |
| 189 | + /** | |
| 190 | + * commented out because currently we are not displaying tips for transaction list table status but this | |
| 191 | + * may change in a later iteration so want to keep the code for then. | |
| 192 | + */ | |
| 193 | + // 'qtips' => array( 'Transactions_List_Table_Tips' ), | |
| 194 | + 'require_nonce' => false, | |
| 195 | + ), | |
| 196 | + 'view_transaction' => array( | |
| 197 | + 'nav' => array( | |
| 198 | +					'label'      => esc_html__('View Transaction', 'event_espresso'), | |
| 199 | + 'order' => 5, | |
| 200 | + 'url' => isset($this->_req_data['TXN_ID']) | |
| 201 | +						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url) | |
| 202 | + : $this->_admin_base_url, | |
| 203 | + 'persistent' => false, | |
| 204 | + ), | |
| 205 | + 'help_tabs' => array( | |
| 206 | + 'transactions_view_transaction_help_tab' => array( | |
| 207 | +						'title'    => esc_html__('View Transaction', 'event_espresso'), | |
| 208 | + 'filename' => 'transactions_view_transaction', | |
| 209 | + ), | |
| 210 | + 'transactions_view_transaction_transaction_details_table_help_tab' => array( | |
| 211 | +						'title'    => esc_html__('Transaction Details Table', 'event_espresso'), | |
| 212 | + 'filename' => 'transactions_view_transaction_transaction_details_table', | |
| 213 | + ), | |
| 214 | + 'transactions_view_transaction_attendees_registered_help_tab' => array( | |
| 215 | +						'title'    => esc_html__('Attendees Registered', 'event_espresso'), | |
| 216 | + 'filename' => 'transactions_view_transaction_attendees_registered', | |
| 217 | + ), | |
| 218 | + 'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array( | |
| 219 | +						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'), | |
| 220 | + 'filename' => 'transactions_view_transaction_primary_registrant_billing_information', | |
| 221 | + ), | |
| 222 | + ), | |
| 223 | +				'qtips'     => array('Transaction_Details_Tips'), | |
| 224 | +				'help_tour' => array('Transaction_Details_Help_Tour'), | |
| 225 | +				'metaboxes' => array('_transaction_details_metaboxes'), | |
| 226 | + | |
| 227 | + 'require_nonce' => false, | |
| 228 | + ), | |
| 229 | + ); | |
| 230 | + } | |
| 231 | + | |
| 232 | + | |
| 233 | + /** | |
| 234 | + * The below methods aren't used by this class currently | |
| 235 | + */ | |
| 236 | + protected function _add_screen_options() | |
| 237 | +	{ | |
| 238 | + // noop | |
| 239 | + } | |
| 240 | + | |
| 241 | + protected function _add_feature_pointers() | |
| 242 | +	{ | |
| 243 | + // noop | |
| 244 | + } | |
| 245 | + | |
| 246 | + public function admin_init() | |
| 247 | +	{ | |
| 248 | + // IF a registration was JUST added via the admin... | |
| 249 | + if (isset( | |
| 250 | + $this->_req_data['redirect_from'], | |
| 251 | + $this->_req_data['EVT_ID'], | |
| 252 | + $this->_req_data['event_name'] | |
| 253 | +		)) { | |
| 254 | + // then set a cookie so that we can block any attempts to use | |
| 255 | + // the back button as a way to enter another registration. | |
| 256 | + setcookie( | |
| 257 | + 'ee_registration_added', | |
| 258 | + $this->_req_data['EVT_ID'], | |
| 259 | + time() + WEEK_IN_SECONDS, | |
| 260 | + '/' | |
| 261 | + ); | |
| 262 | + // and update the global | |
| 263 | + $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID']; | |
| 264 | + } | |
| 265 | + EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__( | |
| 266 | + 'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.', | |
| 267 | + 'event_espresso' | |
| 268 | + ); | |
| 269 | + EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__( | |
| 270 | + 'An error occurred! Please refresh the page and try again.', | |
| 271 | + 'event_espresso' | |
| 272 | + ); | |
| 273 | + EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status; | |
| 274 | + EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status; | |
| 275 | +		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso'); | |
| 276 | + EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__( | |
| 277 | + 'This transaction has been overpaid ! Payments Total', | |
| 278 | + 'event_espresso' | |
| 279 | + ); | |
| 280 | + } | |
| 281 | + | |
| 282 | + public function admin_notices() | |
| 283 | +	{ | |
| 284 | + // noop | |
| 285 | + } | |
| 286 | + | |
| 287 | + public function admin_footer_scripts() | |
| 288 | +	{ | |
| 289 | + // noop | |
| 290 | + } | |
| 291 | + | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * _set_transaction_status_array | |
| 295 | + * sets list of transaction statuses | |
| 296 | + * | |
| 297 | + * @access private | |
| 298 | + * @return void | |
| 299 | + * @throws EE_Error | |
| 300 | + * @throws InvalidArgumentException | |
| 301 | + * @throws InvalidDataTypeException | |
| 302 | + * @throws InvalidInterfaceException | |
| 303 | + */ | |
| 304 | + private function _set_transaction_status_array() | |
| 305 | +	{ | |
| 306 | + self::$_txn_status = EEM_Transaction::instance()->status_array(true); | |
| 307 | + } | |
| 308 | + | |
| 309 | + | |
| 310 | + /** | |
| 311 | + * get_transaction_status_array | |
| 312 | + * return the transaction status array for wp_list_table | |
| 313 | + * | |
| 314 | + * @access public | |
| 315 | + * @return array | |
| 316 | + */ | |
| 317 | + public function get_transaction_status_array() | |
| 318 | +	{ | |
| 319 | + return self::$_txn_status; | |
| 320 | + } | |
| 321 | + | |
| 322 | + | |
| 323 | + /** | |
| 324 | + * get list of payment statuses | |
| 325 | + * | |
| 326 | + * @access private | |
| 327 | + * @return void | |
| 328 | + * @throws EE_Error | |
| 329 | + * @throws InvalidArgumentException | |
| 330 | + * @throws InvalidDataTypeException | |
| 331 | + * @throws InvalidInterfaceException | |
| 332 | + */ | |
| 333 | + private function _get_payment_status_array() | |
| 334 | +	{ | |
| 335 | + self::$_pay_status = EEM_Payment::instance()->status_array(true); | |
| 336 | + $this->_template_args['payment_status'] = self::$_pay_status; | |
| 337 | + } | |
| 338 | + | |
| 339 | + | |
| 340 | + /** | |
| 341 | + * _add_screen_options_default | |
| 342 | + * | |
| 343 | + * @access protected | |
| 344 | + * @return void | |
| 345 | + * @throws InvalidArgumentException | |
| 346 | + * @throws InvalidDataTypeException | |
| 347 | + * @throws InvalidInterfaceException | |
| 348 | + */ | |
| 349 | + protected function _add_screen_options_default() | |
| 350 | +	{ | |
| 351 | + $this->_per_page_screen_option(); | |
| 352 | + } | |
| 353 | + | |
| 354 | + | |
| 355 | + /** | |
| 356 | + * load_scripts_styles | |
| 357 | + * | |
| 358 | + * @access public | |
| 359 | + * @return void | |
| 360 | + */ | |
| 361 | + public function load_scripts_styles() | |
| 362 | +	{ | |
| 363 | + // enqueue style | |
| 364 | + wp_register_style( | |
| 365 | + 'espresso_txn', | |
| 366 | + TXN_ASSETS_URL . 'espresso_transactions_admin.css', | |
| 367 | + array(), | |
| 368 | + EVENT_ESPRESSO_VERSION | |
| 369 | + ); | |
| 370 | +		wp_enqueue_style('espresso_txn'); | |
| 371 | + // scripts | |
| 372 | + wp_register_script( | |
| 373 | + 'espresso_txn', | |
| 374 | + TXN_ASSETS_URL . 'espresso_transactions_admin.js', | |
| 375 | + array( | |
| 376 | + 'ee_admin_js', | |
| 377 | + 'ee-datepicker', | |
| 378 | + 'jquery-ui-datepicker', | |
| 379 | + 'jquery-ui-draggable', | |
| 380 | + 'ee-dialog', | |
| 381 | + 'ee-accounting', | |
| 382 | + 'ee-serialize-full-array', | |
| 383 | + ), | |
| 384 | + EVENT_ESPRESSO_VERSION, | |
| 385 | + true | |
| 386 | + ); | |
| 387 | +		wp_enqueue_script('espresso_txn'); | |
| 388 | + } | |
| 389 | + | |
| 390 | + | |
| 391 | + /** | |
| 392 | + * load_scripts_styles_view_transaction | |
| 393 | + * | |
| 394 | + * @access public | |
| 395 | + * @return void | |
| 396 | + */ | |
| 397 | + public function load_scripts_styles_view_transaction() | |
| 398 | +	{ | |
| 399 | + // styles | |
| 400 | +		wp_enqueue_style('espresso-ui-theme'); | |
| 401 | + } | |
| 402 | + | |
| 403 | + | |
| 404 | + /** | |
| 405 | + * load_scripts_styles_default | |
| 406 | + * | |
| 407 | + * @access public | |
| 408 | + * @return void | |
| 409 | + */ | |
| 410 | + public function load_scripts_styles_default() | |
| 411 | +	{ | |
| 412 | + // styles | |
| 413 | +		wp_enqueue_style('espresso-ui-theme'); | |
| 414 | + } | |
| 415 | + | |
| 416 | + | |
| 417 | + /** | |
| 418 | + * _set_list_table_views_default | |
| 419 | + * | |
| 420 | + * @access protected | |
| 421 | + * @return void | |
| 422 | + */ | |
| 423 | + protected function _set_list_table_views_default() | |
| 424 | +	{ | |
| 425 | + $this->_views = array( | |
| 426 | + 'all' => array( | |
| 427 | + 'slug' => 'all', | |
| 428 | +				'label' => esc_html__('View All Transactions', 'event_espresso'), | |
| 429 | + 'count' => 0, | |
| 430 | + ), | |
| 431 | + 'abandoned' => array( | |
| 432 | + 'slug' => 'abandoned', | |
| 433 | +				'label' => esc_html__('Abandoned Transactions', 'event_espresso'), | |
| 434 | + 'count' => 0, | |
| 435 | + ), | |
| 436 | + 'incomplete' => array( | |
| 437 | + 'slug' => 'incomplete', | |
| 438 | +				'label' => esc_html__('Incomplete Transactions', 'event_espresso'), | |
| 439 | + 'count' => 0, | |
| 440 | + ) | |
| 441 | + ); | |
| 442 | + if (/** | |
| 443 | + * Filters whether a link to the "Failed Transactions" list table | |
| 444 | + * appears on the Transactions Admin Page list table. | |
| 445 | + * List display can be turned back on via the following: | |
| 446 | + * add_filter( | |
| 447 | + * 'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list', | |
| 448 | + * '__return_true' | |
| 449 | + * ); | |
| 450 | + * | |
| 451 | + * @since 4.9.70.p | |
| 452 | + * @param boolean $display_failed_txns_list | |
| 453 | + * @param Transactions_Admin_Page $this | |
| 454 | + */ | |
| 455 | + apply_filters( | |
| 456 | + 'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list', | |
| 457 | + false, | |
| 458 | + $this | |
| 459 | + ) | |
| 460 | +		) { | |
| 461 | + $this->_views['failed'] = array( | |
| 462 | + 'slug' => 'failed', | |
| 463 | +				'label' => esc_html__('Failed Transactions', 'event_espresso'), | |
| 464 | + 'count' => 0, | |
| 465 | + ); | |
| 466 | + } | |
| 467 | + } | |
| 468 | + | |
| 469 | + | |
| 470 | + /** | |
| 471 | + * _set_transaction_object | |
| 472 | + * This sets the _transaction property for the transaction details screen | |
| 473 | + * | |
| 474 | + * @access private | |
| 475 | + * @return void | |
| 476 | + * @throws EE_Error | |
| 477 | + * @throws InvalidArgumentException | |
| 478 | + * @throws RuntimeException | |
| 479 | + * @throws InvalidDataTypeException | |
| 480 | + * @throws InvalidInterfaceException | |
| 481 | + * @throws ReflectionException | |
| 482 | + */ | |
| 483 | + private function _set_transaction_object() | |
| 484 | +	{ | |
| 485 | +		if ($this->_transaction instanceof EE_Transaction) { | |
| 486 | + return; | |
| 487 | + } //get out we've already set the object | |
| 488 | + | |
| 489 | + $TXN_ID = ! empty($this->_req_data['TXN_ID']) | |
| 490 | + ? absint($this->_req_data['TXN_ID']) | |
| 491 | + : false; | |
| 492 | + | |
| 493 | + // get transaction object | |
| 494 | + $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID); | |
| 495 | + $this->_session = $this->_transaction instanceof EE_Transaction | |
| 496 | +			? $this->_transaction->get('TXN_session_data') | |
| 497 | + : null; | |
| 498 | +		if ($this->_transaction instanceof EE_Transaction) { | |
| 499 | + $this->_transaction->verify_abandoned_transaction_status(); | |
| 500 | + } | |
| 501 | + | |
| 502 | +		if (! $this->_transaction instanceof EE_Transaction) { | |
| 503 | + $error_msg = sprintf( | |
| 504 | + esc_html__( | |
| 505 | + 'An error occurred and the details for the transaction with the ID # %d could not be retrieved.', | |
| 506 | + 'event_espresso' | |
| 507 | + ), | |
| 508 | + $TXN_ID | |
| 509 | + ); | |
| 510 | + EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__); | |
| 511 | + } | |
| 512 | + } | |
| 513 | + | |
| 514 | + | |
| 515 | + /** | |
| 516 | + * _transaction_legend_items | |
| 517 | + * | |
| 518 | + * @access protected | |
| 519 | + * @return array | |
| 520 | + * @throws EE_Error | |
| 521 | + * @throws InvalidArgumentException | |
| 522 | + * @throws ReflectionException | |
| 523 | + * @throws InvalidDataTypeException | |
| 524 | + * @throws InvalidInterfaceException | |
| 525 | + */ | |
| 526 | + protected function _transaction_legend_items() | |
| 527 | +	{ | |
| 528 | +		EE_Registry::instance()->load_helper('MSG_Template'); | |
| 529 | + $items = array(); | |
| 530 | + | |
| 531 | + if (EE_Registry::instance()->CAP->current_user_can( | |
| 532 | + 'ee_read_global_messages', | |
| 533 | + 'view_filtered_messages' | |
| 534 | +		)) { | |
| 535 | +			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for'); | |
| 536 | + if (is_array($related_for_icon) | |
| 537 | + && isset($related_for_icon['css_class'], $related_for_icon['label']) | |
| 538 | +			) { | |
| 539 | + $items['view_related_messages'] = array( | |
| 540 | + 'class' => $related_for_icon['css_class'], | |
| 541 | + 'desc' => $related_for_icon['label'], | |
| 542 | + ); | |
| 543 | + } | |
| 544 | + } | |
| 545 | + | |
| 546 | + $items = apply_filters( | |
| 547 | + 'FHEE__Transactions_Admin_Page___transaction_legend_items__items', | |
| 548 | + array_merge( | |
| 549 | + $items, | |
| 550 | + array( | |
| 551 | + 'view_details' => array( | |
| 552 | + 'class' => 'dashicons dashicons-cart', | |
| 553 | +						'desc'  => esc_html__('View Transaction Details', 'event_espresso'), | |
| 554 | + ), | |
| 555 | + 'view_invoice' => array( | |
| 556 | + 'class' => 'dashicons dashicons-media-spreadsheet', | |
| 557 | +						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'), | |
| 558 | + ), | |
| 559 | + 'view_receipt' => array( | |
| 560 | + 'class' => 'dashicons dashicons-media-default', | |
| 561 | +						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'), | |
| 562 | + ), | |
| 563 | + 'view_registration' => array( | |
| 564 | + 'class' => 'dashicons dashicons-clipboard', | |
| 565 | +						'desc'  => esc_html__('View Registration Details', 'event_espresso'), | |
| 566 | + ), | |
| 567 | + 'payment_overview_link' => array( | |
| 568 | + 'class' => 'dashicons dashicons-money', | |
| 569 | +						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'), | |
| 570 | + ), | |
| 571 | + ) | |
| 572 | + ) | |
| 573 | + ); | |
| 574 | + | |
| 575 | + if (EE_Registry::instance()->CAP->current_user_can( | |
| 576 | + 'ee_send_message', | |
| 577 | + 'espresso_transactions_send_payment_reminder' | |
| 578 | +		)) { | |
| 579 | +			if (EEH_MSG_Template::is_mt_active('payment_reminder')) { | |
| 580 | + $items['send_payment_reminder'] = array( | |
| 581 | + 'class' => 'dashicons dashicons-email-alt', | |
| 582 | +					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'), | |
| 583 | + ); | |
| 584 | +			} else { | |
| 585 | + $items['blank*'] = array( | |
| 586 | + 'class' => '', | |
| 587 | + 'desc' => '', | |
| 588 | + ); | |
| 589 | + } | |
| 590 | +		} else { | |
| 591 | + $items['blank*'] = array( | |
| 592 | + 'class' => '', | |
| 593 | + 'desc' => '', | |
| 594 | + ); | |
| 595 | + } | |
| 596 | + $more_items = apply_filters( | |
| 597 | + 'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items', | |
| 598 | + array( | |
| 599 | + 'overpaid' => array( | |
| 600 | + 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code, | |
| 601 | + 'desc' => EEH_Template::pretty_status( | |
| 602 | + EEM_Transaction::overpaid_status_code, | |
| 603 | + false, | |
| 604 | + 'sentence' | |
| 605 | + ), | |
| 606 | + ), | |
| 607 | + 'complete' => array( | |
| 608 | + 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code, | |
| 609 | + 'desc' => EEH_Template::pretty_status( | |
| 610 | + EEM_Transaction::complete_status_code, | |
| 611 | + false, | |
| 612 | + 'sentence' | |
| 613 | + ), | |
| 614 | + ), | |
| 615 | + 'incomplete' => array( | |
| 616 | + 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code, | |
| 617 | + 'desc' => EEH_Template::pretty_status( | |
| 618 | + EEM_Transaction::incomplete_status_code, | |
| 619 | + false, | |
| 620 | + 'sentence' | |
| 621 | + ), | |
| 622 | + ), | |
| 623 | + 'abandoned' => array( | |
| 624 | + 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code, | |
| 625 | + 'desc' => EEH_Template::pretty_status( | |
| 626 | + EEM_Transaction::abandoned_status_code, | |
| 627 | + false, | |
| 628 | + 'sentence' | |
| 629 | + ), | |
| 630 | + ), | |
| 631 | + 'failed' => array( | |
| 632 | + 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code, | |
| 633 | + 'desc' => EEH_Template::pretty_status( | |
| 634 | + EEM_Transaction::failed_status_code, | |
| 635 | + false, | |
| 636 | + 'sentence' | |
| 637 | + ), | |
| 638 | + ), | |
| 639 | + ) | |
| 640 | + ); | |
| 641 | + | |
| 642 | + return array_merge($items, $more_items); | |
| 643 | + } | |
| 644 | + | |
| 645 | + | |
| 646 | + /** | |
| 647 | + * _transactions_overview_list_table | |
| 648 | + * | |
| 649 | + * @access protected | |
| 650 | + * @return void | |
| 651 | + * @throws DomainException | |
| 652 | + * @throws EE_Error | |
| 653 | + * @throws InvalidArgumentException | |
| 654 | + * @throws InvalidDataTypeException | |
| 655 | + * @throws InvalidInterfaceException | |
| 656 | + * @throws ReflectionException | |
| 657 | + */ | |
| 658 | + protected function _transactions_overview_list_table() | |
| 659 | +	{ | |
| 660 | +		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso'); | |
| 661 | + $event = isset($this->_req_data['EVT_ID']) | |
| 662 | + ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']) | |
| 663 | + : null; | |
| 664 | + $this->_template_args['admin_page_header'] = $event instanceof EE_Event | |
| 665 | + ? sprintf( | |
| 666 | + esc_html__( | |
| 667 | + '%sViewing Transactions for the Event: %s%s', | |
| 668 | + 'event_espresso' | |
| 669 | + ), | |
| 670 | + '<h3>', | |
| 671 | + '<a href="' | |
| 672 | + . EE_Admin_Page::add_query_args_and_nonce( | |
| 673 | +					array('action' => 'edit', 'post' => $event->ID()), | |
| 674 | + EVENTS_ADMIN_URL | |
| 675 | + ) | |
| 676 | + . '" title="' | |
| 677 | + . esc_attr__( | |
| 678 | + 'Click to Edit event', | |
| 679 | + 'event_espresso' | |
| 680 | + ) | |
| 681 | +				. '">' . $event->get('EVT_name') . '</a>', | |
| 682 | + '</h3>' | |
| 683 | + ) | |
| 684 | + : ''; | |
| 685 | + $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items()); | |
| 686 | + $this->display_admin_list_table_page_with_no_sidebar(); | |
| 687 | + } | |
| 688 | + | |
| 689 | + | |
| 690 | + /** | |
| 691 | + * _transaction_details | |
| 692 | + * generates HTML for the View Transaction Details Admin page | |
| 693 | + * | |
| 694 | + * @access protected | |
| 695 | + * @return void | |
| 696 | + * @throws DomainException | |
| 697 | + * @throws EE_Error | |
| 698 | + * @throws InvalidArgumentException | |
| 699 | + * @throws InvalidDataTypeException | |
| 700 | + * @throws InvalidInterfaceException | |
| 701 | + * @throws RuntimeException | |
| 702 | + * @throws ReflectionException | |
| 703 | + */ | |
| 704 | + protected function _transaction_details() | |
| 705 | +	{ | |
| 706 | +		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction); | |
| 707 | + | |
| 708 | + $this->_set_transaction_status_array(); | |
| 709 | + | |
| 710 | + $this->_template_args = array(); | |
| 711 | + $this->_template_args['transactions_page'] = $this->_wp_page_slug; | |
| 712 | + | |
| 713 | + $this->_set_transaction_object(); | |
| 714 | + | |
| 715 | +		if (! $this->_transaction instanceof EE_Transaction) { | |
| 716 | + return; | |
| 717 | + } | |
| 718 | + $primary_registration = $this->_transaction->primary_registration(); | |
| 719 | + $attendee = $primary_registration instanceof EE_Registration | |
| 720 | + ? $primary_registration->attendee() | |
| 721 | + : null; | |
| 722 | + | |
| 723 | + $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID(); | |
| 724 | +		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso'); | |
| 725 | + | |
| 726 | +		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp'); | |
| 727 | +		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso'); | |
| 728 | + | |
| 729 | +		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ]; | |
| 730 | +		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso'); | |
| 731 | +		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID'); | |
| 732 | + | |
| 733 | +		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total'); | |
| 734 | +		$this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid'); | |
| 735 | + | |
| 736 | +		$amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid'); | |
| 737 | + $this->_template_args['amount_due'] = EEH_Template::format_currency( | |
| 738 | + $amount_due, | |
| 739 | + true | |
| 740 | + ); | |
| 741 | +		if (EE_Registry::instance()->CFG->currency->sign_b4) { | |
| 742 | + $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign | |
| 743 | + . $this->_template_args['amount_due']; | |
| 744 | +		} else { | |
| 745 | + $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign; | |
| 746 | + } | |
| 747 | + $this->_template_args['amount_due_class'] = ''; | |
| 748 | + | |
| 749 | +		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) { | |
| 750 | + // paid in full | |
| 751 | + $this->_template_args['amount_due'] = false; | |
| 752 | +		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) { | |
| 753 | + // overpaid | |
| 754 | + $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn'; | |
| 755 | +		} elseif ($this->_transaction->get('TXN_total') > 0 | |
| 756 | +				  && $this->_transaction->get('TXN_paid') > 0 | |
| 757 | +		) { | |
| 758 | + // monies owing | |
| 759 | + $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn'; | |
| 760 | +		} elseif ($this->_transaction->get('TXN_total') > 0 | |
| 761 | +				  && $this->_transaction->get('TXN_paid') == 0 | |
| 762 | +		) { | |
| 763 | + // no payments made yet | |
| 764 | + $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn'; | |
| 765 | +		} elseif ($this->_transaction->get('TXN_total') == 0) { | |
| 766 | + // free event | |
| 767 | + $this->_template_args['amount_due'] = false; | |
| 768 | + } | |
| 769 | + | |
| 770 | + $payment_method = $this->_transaction->payment_method(); | |
| 771 | + | |
| 772 | + $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method | |
| 773 | + ? $payment_method->admin_name() | |
| 774 | +			: esc_html__('Unknown', 'event_espresso'); | |
| 775 | + | |
| 776 | + $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign; | |
| 777 | + // link back to overview | |
| 778 | + $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER']) | |
| 779 | + ? $_SERVER['HTTP_REFERER'] | |
| 780 | + : TXN_ADMIN_URL; | |
| 781 | + | |
| 782 | + | |
| 783 | + // next link | |
| 784 | + $next_txn = $this->_transaction->next( | |
| 785 | + null, | |
| 786 | +			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))), | |
| 787 | + 'TXN_ID' | |
| 788 | + ); | |
| 789 | + $this->_template_args['next_transaction'] = $next_txn | |
| 790 | + ? $this->_next_link( | |
| 791 | + EE_Admin_Page::add_query_args_and_nonce( | |
| 792 | +					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']), | |
| 793 | + TXN_ADMIN_URL | |
| 794 | + ), | |
| 795 | + 'dashicons dashicons-arrow-right ee-icon-size-22' | |
| 796 | + ) | |
| 797 | + : ''; | |
| 798 | + // previous link | |
| 799 | + $previous_txn = $this->_transaction->previous( | |
| 800 | + null, | |
| 801 | +			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))), | |
| 802 | + 'TXN_ID' | |
| 803 | + ); | |
| 804 | + $this->_template_args['previous_transaction'] = $previous_txn | |
| 805 | + ? $this->_previous_link( | |
| 806 | + EE_Admin_Page::add_query_args_and_nonce( | |
| 807 | +					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']), | |
| 808 | + TXN_ADMIN_URL | |
| 809 | + ), | |
| 810 | + 'dashicons dashicons-arrow-left ee-icon-size-22' | |
| 811 | + ) | |
| 812 | + : ''; | |
| 813 | + | |
| 814 | + // were we just redirected here after adding a new registration ??? | |
| 815 | + if (isset( | |
| 816 | + $this->_req_data['redirect_from'], | |
| 817 | + $this->_req_data['EVT_ID'], | |
| 818 | + $this->_req_data['event_name'] | |
| 819 | +		)) { | |
| 820 | + if (EE_Registry::instance()->CAP->current_user_can( | |
| 821 | + 'ee_edit_registrations', | |
| 822 | + 'espresso_registrations_new_registration', | |
| 823 | + $this->_req_data['EVT_ID'] | |
| 824 | +			)) { | |
| 825 | + $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="'; | |
| 826 | + $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce( | |
| 827 | + array( | |
| 828 | + 'page' => 'espresso_registrations', | |
| 829 | + 'action' => 'new_registration', | |
| 830 | + 'return' => 'default', | |
| 831 | + 'TXN_ID' => $this->_transaction->ID(), | |
| 832 | + 'event_id' => $this->_req_data['EVT_ID'], | |
| 833 | + ), | |
| 834 | + REG_ADMIN_URL | |
| 835 | + ); | |
| 836 | + $this->_admin_page_title .= '">'; | |
| 837 | + | |
| 838 | + $this->_admin_page_title .= sprintf( | |
| 839 | +					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'), | |
| 840 | + htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8') | |
| 841 | + ); | |
| 842 | + $this->_admin_page_title .= '</a>'; | |
| 843 | + } | |
| 844 | + EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__); | |
| 845 | + } | |
| 846 | + // grab messages at the last second | |
| 847 | + $this->_template_args['notices'] = EE_Error::get_notices(); | |
| 848 | + // path to template | |
| 849 | + $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php'; | |
| 850 | + $this->_template_args['admin_page_header'] = EEH_Template::display_template( | |
| 851 | + $template_path, | |
| 852 | + $this->_template_args, | |
| 853 | + true | |
| 854 | + ); | |
| 855 | + | |
| 856 | + // the details template wrapper | |
| 857 | + $this->display_admin_page_with_sidebar(); | |
| 858 | + } | |
| 859 | + | |
| 860 | + | |
| 861 | + /** | |
| 862 | + * _transaction_details_metaboxes | |
| 863 | + * | |
| 864 | + * @access protected | |
| 865 | + * @return void | |
| 866 | + * @throws EE_Error | |
| 867 | + * @throws InvalidArgumentException | |
| 868 | + * @throws InvalidDataTypeException | |
| 869 | + * @throws InvalidInterfaceException | |
| 870 | + * @throws RuntimeException | |
| 871 | + * @throws ReflectionException | |
| 872 | + */ | |
| 873 | + protected function _transaction_details_metaboxes() | |
| 874 | +	{ | |
| 875 | + | |
| 876 | + $this->_set_transaction_object(); | |
| 877 | + | |
| 878 | +		if (! $this->_transaction instanceof EE_Transaction) { | |
| 879 | + return; | |
| 880 | + } | |
| 881 | + add_meta_box( | |
| 882 | + 'edit-txn-details-mbox', | |
| 883 | +			esc_html__('Transaction Details', 'event_espresso'), | |
| 884 | + array($this, 'txn_details_meta_box'), | |
| 885 | + $this->_wp_page_slug, | |
| 886 | + 'normal', | |
| 887 | + 'high' | |
| 888 | + ); | |
| 889 | + add_meta_box( | |
| 890 | + 'edit-txn-attendees-mbox', | |
| 891 | +			esc_html__('Attendees Registered in this Transaction', 'event_espresso'), | |
| 892 | + array($this, 'txn_attendees_meta_box'), | |
| 893 | + $this->_wp_page_slug, | |
| 894 | + 'normal', | |
| 895 | + 'high', | |
| 896 | +			array('TXN_ID' => $this->_transaction->ID()) | |
| 897 | + ); | |
| 898 | + add_meta_box( | |
| 899 | + 'edit-txn-registrant-mbox', | |
| 900 | +			esc_html__('Primary Contact', 'event_espresso'), | |
| 901 | + array($this, 'txn_registrant_side_meta_box'), | |
| 902 | + $this->_wp_page_slug, | |
| 903 | + 'side', | |
| 904 | + 'high' | |
| 905 | + ); | |
| 906 | + add_meta_box( | |
| 907 | + 'edit-txn-billing-info-mbox', | |
| 908 | +			esc_html__('Billing Information', 'event_espresso'), | |
| 909 | + array($this, 'txn_billing_info_side_meta_box'), | |
| 910 | + $this->_wp_page_slug, | |
| 911 | + 'side', | |
| 912 | + 'high' | |
| 913 | + ); | |
| 914 | + } | |
| 915 | + | |
| 916 | + | |
| 917 | + /** | |
| 918 | + * Callback for transaction actions metabox. | |
| 919 | + * | |
| 920 | + * @param EE_Transaction|null $transaction | |
| 921 | + * @throws DomainException | |
| 922 | + * @throws EE_Error | |
| 923 | + * @throws InvalidArgumentException | |
| 924 | + * @throws InvalidDataTypeException | |
| 925 | + * @throws InvalidInterfaceException | |
| 926 | + * @throws ReflectionException | |
| 927 | + * @throws RuntimeException | |
| 928 | + */ | |
| 929 | + public function getActionButtons(EE_Transaction $transaction = null) | |
| 930 | +	{ | |
| 931 | + $content = ''; | |
| 932 | + $actions = array(); | |
| 933 | +		if (! $transaction instanceof EE_Transaction) { | |
| 934 | + return $content; | |
| 935 | + } | |
| 936 | + /** @var EE_Registration $primary_registration */ | |
| 937 | + $primary_registration = $transaction->primary_registration(); | |
| 938 | + $attendee = $primary_registration instanceof EE_Registration | |
| 939 | + ? $primary_registration->attendee() | |
| 940 | + : null; | |
| 941 | + | |
| 942 | + if ($attendee instanceof EE_Attendee | |
| 943 | + && EE_Registry::instance()->CAP->current_user_can( | |
| 944 | + 'ee_send_message', | |
| 945 | + 'espresso_transactions_send_payment_reminder' | |
| 946 | + ) | |
| 947 | +		) { | |
| 948 | + $actions['payment_reminder'] = | |
| 949 | +				EEH_MSG_Template::is_mt_active('payment_reminder') | |
| 950 | +				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code | |
| 951 | +				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code | |
| 952 | + ? EEH_Template::get_button_or_link( | |
| 953 | + EE_Admin_Page::add_query_args_and_nonce( | |
| 954 | + array( | |
| 955 | + 'action' => 'send_payment_reminder', | |
| 956 | + 'TXN_ID' => $this->_transaction->ID(), | |
| 957 | + 'redirect_to' => 'view_transaction', | |
| 958 | + ), | |
| 959 | + TXN_ADMIN_URL | |
| 960 | + ), | |
| 961 | +						esc_html__(' Send Payment Reminder', 'event_espresso'), | |
| 962 | + 'button secondary-button', | |
| 963 | + 'dashicons dashicons-email-alt' | |
| 964 | + ) | |
| 965 | + : ''; | |
| 966 | + } | |
| 967 | + | |
| 968 | + if ($primary_registration instanceof EE_Registration | |
| 969 | +			&& EEH_MSG_Template::is_mt_active('receipt') | |
| 970 | +		) { | |
| 971 | + $actions['receipt'] = EEH_Template::get_button_or_link( | |
| 972 | + $primary_registration->receipt_url(), | |
| 973 | +				esc_html__('View Receipt', 'event_espresso'), | |
| 974 | + 'button secondary-button', | |
| 975 | + 'dashicons dashicons-media-default' | |
| 976 | + ); | |
| 977 | + } | |
| 978 | + | |
| 979 | + if ($primary_registration instanceof EE_Registration | |
| 980 | +			&& EEH_MSG_Template::is_mt_active('invoice') | |
| 981 | +		) { | |
| 982 | + $actions['invoice'] = EEH_Template::get_button_or_link( | |
| 983 | + $primary_registration->invoice_url(), | |
| 984 | +				esc_html__('View Invoice', 'event_espresso'), | |
| 985 | + 'button secondary-button', | |
| 986 | + 'dashicons dashicons-media-spreadsheet' | |
| 987 | + ); | |
| 988 | + } | |
| 989 | + $actions = array_filter( | |
| 990 | +			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction) | |
| 991 | + ); | |
| 992 | +		if ($actions) { | |
| 993 | + $content = '<ul>'; | |
| 994 | +			$content .= '<li>' . implode('</li><li>', $actions) . '</li>'; | |
| 995 | + $content .= '</uL>'; | |
| 996 | + } | |
| 997 | + return $content; | |
| 998 | + } | |
| 999 | + | |
| 1000 | + | |
| 1001 | + /** | |
| 1002 | + * txn_details_meta_box | |
| 1003 | + * generates HTML for the Transaction main meta box | |
| 1004 | + * | |
| 1005 | + * @return void | |
| 1006 | + * @throws DomainException | |
| 1007 | + * @throws EE_Error | |
| 1008 | + * @throws InvalidArgumentException | |
| 1009 | + * @throws InvalidDataTypeException | |
| 1010 | + * @throws InvalidInterfaceException | |
| 1011 | + * @throws RuntimeException | |
| 1012 | + * @throws ReflectionException | |
| 1013 | + */ | |
| 1014 | + public function txn_details_meta_box() | |
| 1015 | +	{ | |
| 1016 | + $this->_set_transaction_object(); | |
| 1017 | + $this->_template_args['TXN_ID'] = $this->_transaction->ID(); | |
| 1018 | + $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration | |
| 1019 | + ? $this->_transaction->primary_registration()->attendee() | |
| 1020 | + : null; | |
| 1021 | + $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can( | |
| 1022 | + 'ee_edit_payments', | |
| 1023 | + 'apply_payment_or_refund_from_registration_details' | |
| 1024 | + ); | |
| 1025 | + $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can( | |
| 1026 | + 'ee_delete_payments', | |
| 1027 | + 'delete_payment_from_registration_details' | |
| 1028 | + ); | |
| 1029 | + | |
| 1030 | + // get line table | |
| 1031 | + EEH_Autoloader::register_line_item_display_autoloaders(); | |
| 1032 | + $Line_Item_Display = new EE_Line_Item_Display( | |
| 1033 | + 'admin_table', | |
| 1034 | + 'EE_Admin_Table_Line_Item_Display_Strategy' | |
| 1035 | + ); | |
| 1036 | + $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item( | |
| 1037 | + $this->_transaction->total_line_item() | |
| 1038 | + ); | |
| 1039 | +		$this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration') | |
| 1040 | +															   ->get('REG_code'); | |
| 1041 | + | |
| 1042 | + // process taxes | |
| 1043 | + $taxes = $this->_transaction->get_many_related( | |
| 1044 | + 'Line_Item', | |
| 1045 | +			array(array('LIN_type' => EEM_Line_Item::type_tax)) | |
| 1046 | + ); | |
| 1047 | + $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false; | |
| 1048 | + | |
| 1049 | + $this->_template_args['grand_total'] = EEH_Template::format_currency( | |
| 1050 | +			$this->_transaction->get('TXN_total'), | |
| 1051 | + false, | |
| 1052 | + false | |
| 1053 | + ); | |
| 1054 | +		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total'); | |
| 1055 | +		$this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID'); | |
| 1056 | + | |
| 1057 | + // process payment details | |
| 1058 | +		$payments = $this->_transaction->get_many_related('Payment'); | |
| 1059 | +		if (! empty($payments)) { | |
| 1060 | + $this->_template_args['payments'] = $payments; | |
| 1061 | + $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments); | |
| 1062 | +		} else { | |
| 1063 | + $this->_template_args['payments'] = false; | |
| 1064 | + $this->_template_args['existing_reg_payments'] = array(); | |
| 1065 | + } | |
| 1066 | + | |
| 1067 | +		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL); | |
| 1068 | + $this->_template_args['delete_payment_url'] = add_query_arg( | |
| 1069 | +			array('action' => 'espresso_delete_payment'), | |
| 1070 | + TXN_ADMIN_URL | |
| 1071 | + ); | |
| 1072 | + | |
| 1073 | +		if (isset($txn_details['invoice_number'])) { | |
| 1074 | + $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code']; | |
| 1075 | + $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__( | |
| 1076 | + 'Invoice Number', | |
| 1077 | + 'event_espresso' | |
| 1078 | + ); | |
| 1079 | + } | |
| 1080 | + | |
| 1081 | + $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction | |
| 1082 | +			->get_first_related('Registration') | |
| 1083 | +			->get('REG_session'); | |
| 1084 | + $this->_template_args['txn_details']['registration_session']['label'] = esc_html__( | |
| 1085 | + 'Registration Session', | |
| 1086 | + 'event_espresso' | |
| 1087 | + ); | |
| 1088 | + | |
| 1089 | + $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address']) | |
| 1090 | + ? $this->_session['ip_address'] | |
| 1091 | + : ''; | |
| 1092 | + $this->_template_args['txn_details']['ip_address']['label'] = esc_html__( | |
| 1093 | + 'Transaction placed from IP', | |
| 1094 | + 'event_espresso' | |
| 1095 | + ); | |
| 1096 | + | |
| 1097 | + $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent']) | |
| 1098 | + ? $this->_session['user_agent'] | |
| 1099 | + : ''; | |
| 1100 | + $this->_template_args['txn_details']['user_agent']['label'] = esc_html__( | |
| 1101 | + 'Registrant User Agent', | |
| 1102 | + 'event_espresso' | |
| 1103 | + ); | |
| 1104 | + | |
| 1105 | + $reg_steps = '<ul>'; | |
| 1106 | +		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) { | |
| 1107 | +			if ($reg_step_status === true) { | |
| 1108 | + $reg_steps .= '<li style="color:#70cc50">' | |
| 1109 | + . sprintf( | |
| 1110 | +								  esc_html__('%1$s : Completed', 'event_espresso'), | |
| 1111 | +								  ucwords(str_replace('_', ' ', $reg_step)) | |
| 1112 | + ) | |
| 1113 | + . '</li>'; | |
| 1114 | +			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) { | |
| 1115 | + $reg_steps .= '<li style="color:#2EA2CC">' | |
| 1116 | + . sprintf( | |
| 1117 | +								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'), | |
| 1118 | +								  ucwords(str_replace('_', ' ', $reg_step)), | |
| 1119 | + date( | |
| 1120 | +									  get_option('date_format') . ' ' . get_option('time_format'), | |
| 1121 | +									  ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)) | |
| 1122 | + ) | |
| 1123 | + ) | |
| 1124 | + . '</li>'; | |
| 1125 | +			} else { | |
| 1126 | + $reg_steps .= '<li style="color:#E76700">' | |
| 1127 | + . sprintf( | |
| 1128 | +								  esc_html__('%1$s : Never Initiated', 'event_espresso'), | |
| 1129 | +								  ucwords(str_replace('_', ' ', $reg_step)) | |
| 1130 | + ) | |
| 1131 | + . '</li>'; | |
| 1132 | + } | |
| 1133 | + } | |
| 1134 | + $reg_steps .= '</ul>'; | |
| 1135 | + $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps; | |
| 1136 | + $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__( | |
| 1137 | + 'Registration Step Progress', | |
| 1138 | + 'event_espresso' | |
| 1139 | + ); | |
| 1140 | + | |
| 1141 | + | |
| 1142 | + $this->_get_registrations_to_apply_payment_to(); | |
| 1143 | + $this->_get_payment_methods($payments); | |
| 1144 | + $this->_get_payment_status_array(); | |
| 1145 | + $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction. | |
| 1146 | + | |
| 1147 | + $this->_template_args['transaction_form_url'] = add_query_arg( | |
| 1148 | + array( | |
| 1149 | + 'action' => 'edit_transaction', | |
| 1150 | + 'process' => 'transaction', | |
| 1151 | + ), | |
| 1152 | + TXN_ADMIN_URL | |
| 1153 | + ); | |
| 1154 | + $this->_template_args['apply_payment_form_url'] = add_query_arg( | |
| 1155 | + array( | |
| 1156 | + 'page' => 'espresso_transactions', | |
| 1157 | + 'action' => 'espresso_apply_payment', | |
| 1158 | + ), | |
| 1159 | + WP_AJAX_URL | |
| 1160 | + ); | |
| 1161 | + $this->_template_args['delete_payment_form_url'] = add_query_arg( | |
| 1162 | + array( | |
| 1163 | + 'page' => 'espresso_transactions', | |
| 1164 | + 'action' => 'espresso_delete_payment', | |
| 1165 | + ), | |
| 1166 | + WP_AJAX_URL | |
| 1167 | + ); | |
| 1168 | + | |
| 1169 | + $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction); | |
| 1170 | + | |
| 1171 | + // 'espresso_delete_payment_nonce' | |
| 1172 | + | |
| 1173 | + $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php'; | |
| 1174 | + echo EEH_Template::display_template($template_path, $this->_template_args, true); | |
| 1175 | + } | |
| 1176 | + | |
| 1177 | + | |
| 1178 | + /** | |
| 1179 | + * _get_registration_payment_IDs | |
| 1180 | + * generates an array of Payment IDs and their corresponding Registration IDs | |
| 1181 | + * | |
| 1182 | + * @access protected | |
| 1183 | + * @param EE_Payment[] $payments | |
| 1184 | + * @return array | |
| 1185 | + * @throws EE_Error | |
| 1186 | + * @throws InvalidArgumentException | |
| 1187 | + * @throws InvalidDataTypeException | |
| 1188 | + * @throws InvalidInterfaceException | |
| 1189 | + * @throws ReflectionException | |
| 1190 | + */ | |
| 1191 | + protected function _get_registration_payment_IDs($payments = array()) | |
| 1192 | +	{ | |
| 1193 | + $existing_reg_payments = array(); | |
| 1194 | + // get all reg payments for these payments | |
| 1195 | + $reg_payments = EEM_Registration_Payment::instance()->get_all( | |
| 1196 | + array( | |
| 1197 | + array( | |
| 1198 | + 'PAY_ID' => array( | |
| 1199 | + 'IN', | |
| 1200 | + array_keys($payments), | |
| 1201 | + ), | |
| 1202 | + ), | |
| 1203 | + ) | |
| 1204 | + ); | |
| 1205 | +		if (! empty($reg_payments)) { | |
| 1206 | +			foreach ($payments as $payment) { | |
| 1207 | +				if (! $payment instanceof EE_Payment) { | |
| 1208 | + continue; | |
| 1209 | +				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) { | |
| 1210 | + $existing_reg_payments[ $payment->ID() ] = array(); | |
| 1211 | + } | |
| 1212 | +				foreach ($reg_payments as $reg_payment) { | |
| 1213 | + if ($reg_payment instanceof EE_Registration_Payment | |
| 1214 | + && $reg_payment->payment_ID() === $payment->ID() | |
| 1215 | +					) { | |
| 1216 | + $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID(); | |
| 1217 | + } | |
| 1218 | + } | |
| 1219 | + } | |
| 1220 | + } | |
| 1221 | + | |
| 1222 | + return $existing_reg_payments; | |
| 1223 | + } | |
| 1224 | + | |
| 1225 | + | |
| 1226 | + /** | |
| 1227 | + * _get_registrations_to_apply_payment_to | |
| 1228 | + * generates HTML for displaying a series of checkboxes in the admin payment modal window | |
| 1229 | + * which allows the admin to only apply the payment to the specific registrations | |
| 1230 | + * | |
| 1231 | + * @access protected | |
| 1232 | + * @return void | |
| 1233 | + * @throws \EE_Error | |
| 1234 | + */ | |
| 1235 | + protected function _get_registrations_to_apply_payment_to() | |
| 1236 | +	{ | |
| 1237 | + // we want any registration with an active status (ie: not deleted or cancelled) | |
| 1238 | + $query_params = array( | |
| 1239 | + array( | |
| 1240 | + 'STS_ID' => array( | |
| 1241 | + 'IN', | |
| 1242 | + array( | |
| 1243 | + EEM_Registration::status_id_approved, | |
| 1244 | + EEM_Registration::status_id_pending_payment, | |
| 1245 | + EEM_Registration::status_id_not_approved, | |
| 1246 | + ), | |
| 1247 | + ), | |
| 1248 | + ), | |
| 1249 | + ); | |
| 1250 | + $registrations_to_apply_payment_to = EEH_HTML::br() | |
| 1251 | + . EEH_HTML::div( | |
| 1252 | + '', | |
| 1253 | + 'txn-admin-apply-payment-to-registrations-dv', | |
| 1254 | + '', | |
| 1255 | + 'clear: both; margin: 1.5em 0 0; display: none;' | |
| 1256 | + ); | |
| 1257 | +		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap'); | |
| 1258 | +		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl'); | |
| 1259 | + $registrations_to_apply_payment_to .= EEH_HTML::thead( | |
| 1260 | + EEH_HTML::tr( | |
| 1261 | +				EEH_HTML::th(esc_html__('ID', 'event_espresso')) . | |
| 1262 | +				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) . | |
| 1263 | +				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) . | |
| 1264 | +				EEH_HTML::th(esc_html__('Event', 'event_espresso')) . | |
| 1265 | +				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1266 | +				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1267 | +				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr') | |
| 1268 | + ) | |
| 1269 | + ); | |
| 1270 | + $registrations_to_apply_payment_to .= EEH_HTML::tbody(); | |
| 1271 | + // get registrations for TXN | |
| 1272 | + $registrations = $this->_transaction->registrations($query_params); | |
| 1273 | + $existing_reg_payments = $this->_template_args['existing_reg_payments']; | |
| 1274 | +		foreach ($registrations as $registration) { | |
| 1275 | +			if ($registration instanceof EE_Registration) { | |
| 1276 | + $attendee_name = $registration->attendee() instanceof EE_Attendee | |
| 1277 | + ? $registration->attendee()->full_name() | |
| 1278 | +					: esc_html__('Unknown Attendee', 'event_espresso'); | |
| 1279 | + $owing = $registration->final_price() - $registration->paid(); | |
| 1280 | + $taxable = $registration->ticket()->taxable() | |
| 1281 | +					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>' | |
| 1282 | + : ''; | |
| 1283 | + $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments) | |
| 1284 | + ? ' checked="checked"' | |
| 1285 | + : ''; | |
| 1286 | + $disabled = $registration->final_price() > 0 ? '' : ' disabled'; | |
| 1287 | + $registrations_to_apply_payment_to .= EEH_HTML::tr( | |
| 1288 | + EEH_HTML::td($registration->ID()) . | |
| 1289 | + EEH_HTML::td($attendee_name) . | |
| 1290 | + EEH_HTML::td( | |
| 1291 | + $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable | |
| 1292 | + ) . | |
| 1293 | + EEH_HTML::td($registration->event_name()) . | |
| 1294 | + EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1295 | + EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1296 | + EEH_HTML::td( | |
| 1297 | + '<input type="checkbox" value="' . $registration->ID() | |
| 1298 | + . '" name="txn_admin_payment[registrations]"' | |
| 1299 | + . $checked . $disabled . '>', | |
| 1300 | + '', | |
| 1301 | + 'jst-cntr' | |
| 1302 | + ), | |
| 1303 | + 'apply-payment-registration-row-' . $registration->ID() | |
| 1304 | + ); | |
| 1305 | + } | |
| 1306 | + } | |
| 1307 | + $registrations_to_apply_payment_to .= EEH_HTML::tbodyx(); | |
| 1308 | + $registrations_to_apply_payment_to .= EEH_HTML::tablex(); | |
| 1309 | + $registrations_to_apply_payment_to .= EEH_HTML::divx(); | |
| 1310 | + $registrations_to_apply_payment_to .= EEH_HTML::p( | |
| 1311 | + esc_html__( | |
| 1312 | + 'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.', | |
| 1313 | + 'event_espresso' | |
| 1314 | + ), | |
| 1315 | + '', | |
| 1316 | + 'clear description' | |
| 1317 | + ); | |
| 1318 | + $registrations_to_apply_payment_to .= EEH_HTML::divx(); | |
| 1319 | + $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to; | |
| 1320 | + } | |
| 1321 | + | |
| 1322 | + | |
| 1323 | + /** | |
| 1324 | + * _get_reg_status_selection | |
| 1325 | + * | |
| 1326 | + * @todo this will need to be adjusted either once MER comes along OR we move default reg status to tickets | |
| 1327 | + * instead of events. | |
| 1328 | + * @access protected | |
| 1329 | + * @return void | |
| 1330 | + * @throws EE_Error | |
| 1331 | + */ | |
| 1332 | + protected function _get_reg_status_selection() | |
| 1333 | +	{ | |
| 1334 | + // first get all possible statuses | |
| 1335 | + $statuses = EEM_Registration::reg_status_array(array(), true); | |
| 1336 | + // let's add a "don't change" option. | |
| 1337 | +		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso'); | |
| 1338 | + $status_array = array_merge($status_array, $statuses); | |
| 1339 | + $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input( | |
| 1340 | + 'txn_reg_status_change[reg_status]', | |
| 1341 | + $status_array, | |
| 1342 | + 'NAN', | |
| 1343 | + 'id="txn-admin-payment-reg-status-inp"', | |
| 1344 | + 'txn-reg-status-change-reg-status' | |
| 1345 | + ); | |
| 1346 | + $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input( | |
| 1347 | + 'delete_txn_reg_status_change[reg_status]', | |
| 1348 | + $status_array, | |
| 1349 | + 'NAN', | |
| 1350 | + 'delete-txn-admin-payment-reg-status-inp', | |
| 1351 | + 'delete-txn-reg-status-change-reg-status' | |
| 1352 | + ); | |
| 1353 | + } | |
| 1354 | + | |
| 1355 | + | |
| 1356 | + /** | |
| 1357 | + * _get_payment_methods | |
| 1358 | + * Gets all the payment methods available generally, or the ones that are already | |
| 1359 | + * selected on these payments (in case their payment methods are no longer active). | |
| 1360 | + * Has the side-effect of updating the template args' payment_methods item | |
| 1361 | + * | |
| 1362 | + * @access private | |
| 1363 | + * @param EE_Payment[] to show on this page | |
| 1364 | + * @return void | |
| 1365 | + * @throws EE_Error | |
| 1366 | + * @throws InvalidArgumentException | |
| 1367 | + * @throws InvalidDataTypeException | |
| 1368 | + * @throws InvalidInterfaceException | |
| 1369 | + * @throws ReflectionException | |
| 1370 | + */ | |
| 1371 | + private function _get_payment_methods($payments = array()) | |
| 1372 | +	{ | |
| 1373 | + $payment_methods_of_payments = array(); | |
| 1374 | +		foreach ($payments as $payment) { | |
| 1375 | +			if ($payment instanceof EE_Payment) { | |
| 1376 | +				$payment_methods_of_payments[] = $payment->get('PMD_ID'); | |
| 1377 | + } | |
| 1378 | + } | |
| 1379 | +		if ($payment_methods_of_payments) { | |
| 1380 | + $query_args = array( | |
| 1381 | + array( | |
| 1382 | + 'OR*payment_method_for_payment' => array( | |
| 1383 | +						'PMD_ID'    => array('IN', $payment_methods_of_payments), | |
| 1384 | +						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'), | |
| 1385 | + ), | |
| 1386 | + ), | |
| 1387 | + ); | |
| 1388 | +		} else { | |
| 1389 | +			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'))); | |
| 1390 | + } | |
| 1391 | + $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args); | |
| 1392 | + } | |
| 1393 | + | |
| 1394 | + | |
| 1395 | + /** | |
| 1396 | + * txn_attendees_meta_box | |
| 1397 | + * generates HTML for the Attendees Transaction main meta box | |
| 1398 | + * | |
| 1399 | + * @access public | |
| 1400 | + * @param WP_Post $post | |
| 1401 | + * @param array $metabox | |
| 1402 | + * @return void | |
| 1403 | + * @throws DomainException | |
| 1404 | + * @throws EE_Error | |
| 1405 | + */ | |
| 1406 | +	public function txn_attendees_meta_box($post, $metabox = array('args' => array())) | |
| 1407 | +	{ | |
| 1408 | + | |
| 1409 | + /** @noinspection NonSecureExtractUsageInspection */ | |
| 1410 | + extract($metabox['args']); | |
| 1411 | + $this->_template_args['post'] = $post; | |
| 1412 | + $this->_template_args['event_attendees'] = array(); | |
| 1413 | + // process items in cart | |
| 1414 | + $line_items = $this->_transaction->get_many_related( | |
| 1415 | + 'Line_Item', | |
| 1416 | +			array(array('LIN_type' => 'line-item')) | |
| 1417 | + ); | |
| 1418 | +		if (! empty($line_items)) { | |
| 1419 | +			foreach ($line_items as $item) { | |
| 1420 | +				if ($item instanceof EE_Line_Item) { | |
| 1421 | +					switch ($item->OBJ_type()) { | |
| 1422 | + case 'Event': | |
| 1423 | + break; | |
| 1424 | + case 'Ticket': | |
| 1425 | + $ticket = $item->ticket(); | |
| 1426 | + // right now we're only handling tickets here. | |
| 1427 | + // Cause its expected that only tickets will have attendees right? | |
| 1428 | +							if (! $ticket instanceof EE_Ticket) { | |
| 1429 | + break; | |
| 1430 | + } | |
| 1431 | +							try { | |
| 1432 | + $event_name = $ticket->get_event_name(); | |
| 1433 | +							} catch (Exception $e) { | |
| 1434 | + EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 1435 | +								$event_name = esc_html__('Unknown Event', 'event_espresso'); | |
| 1436 | + } | |
| 1437 | +							$event_name .= ' - ' . $item->get('LIN_name'); | |
| 1438 | +							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price')); | |
| 1439 | + // now get all of the registrations for this transaction that use this ticket | |
| 1440 | + $registrations = $ticket->get_many_related( | |
| 1441 | + 'Registration', | |
| 1442 | +								array(array('TXN_ID' => $this->_transaction->ID())) | |
| 1443 | + ); | |
| 1444 | +							foreach ($registrations as $registration) { | |
| 1445 | +								if (! $registration instanceof EE_Registration) { | |
| 1446 | + break; | |
| 1447 | + } | |
| 1448 | + $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID'] | |
| 1449 | + = $registration->status_ID(); | |
| 1450 | + $this->_template_args['event_attendees'][ $registration->ID() ]['att_num'] | |
| 1451 | + = $registration->count(); | |
| 1452 | + $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name'] | |
| 1453 | + = $event_name; | |
| 1454 | + $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price'] | |
| 1455 | + = $ticket_price; | |
| 1456 | + // attendee info | |
| 1457 | +								$attendee = $registration->get_first_related('Attendee'); | |
| 1458 | +								if ($attendee instanceof EE_Attendee) { | |
| 1459 | + $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] | |
| 1460 | + = $attendee->ID(); | |
| 1461 | + $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] | |
| 1462 | + = $attendee->full_name(); | |
| 1463 | + $this->_template_args['event_attendees'][ $registration->ID() ]['email'] | |
| 1464 | + = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name | |
| 1465 | + . esc_html__( | |
| 1466 | + ' Event', | |
| 1467 | + 'event_espresso' | |
| 1468 | + ) | |
| 1469 | + . '">' . $attendee->email() . '</a>'; | |
| 1470 | + $this->_template_args['event_attendees'][ $registration->ID() ]['address'] | |
| 1471 | + = EEH_Address::format($attendee, 'inline', false, false); | |
| 1472 | +								} else { | |
| 1473 | + $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = ''; | |
| 1474 | + $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = ''; | |
| 1475 | + $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = ''; | |
| 1476 | + $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = ''; | |
| 1477 | + } | |
| 1478 | + } | |
| 1479 | + break; | |
| 1480 | + } | |
| 1481 | + } | |
| 1482 | + } | |
| 1483 | + | |
| 1484 | + $this->_template_args['transaction_form_url'] = add_query_arg( | |
| 1485 | + array( | |
| 1486 | + 'action' => 'edit_transaction', | |
| 1487 | + 'process' => 'attendees', | |
| 1488 | + ), | |
| 1489 | + TXN_ADMIN_URL | |
| 1490 | + ); | |
| 1491 | + echo EEH_Template::display_template( | |
| 1492 | + TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php', | |
| 1493 | + $this->_template_args, | |
| 1494 | + true | |
| 1495 | + ); | |
| 1496 | +		} else { | |
| 1497 | + echo sprintf( | |
| 1498 | + esc_html__( | |
| 1499 | + '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s', | |
| 1500 | + 'event_espresso' | |
| 1501 | + ), | |
| 1502 | + '<p class="important-notice">', | |
| 1503 | + '</p>' | |
| 1504 | + ); | |
| 1505 | + } | |
| 1506 | + } | |
| 1507 | + | |
| 1508 | + | |
| 1509 | + /** | |
| 1510 | + * txn_registrant_side_meta_box | |
| 1511 | + * generates HTML for the Edit Transaction side meta box | |
| 1512 | + * | |
| 1513 | + * @access public | |
| 1514 | + * @return void | |
| 1515 | + * @throws DomainException | |
| 1516 | + * @throws EE_Error | |
| 1517 | + * @throws InvalidArgumentException | |
| 1518 | + * @throws InvalidDataTypeException | |
| 1519 | + * @throws InvalidInterfaceException | |
| 1520 | + * @throws ReflectionException | |
| 1521 | + */ | |
| 1522 | + public function txn_registrant_side_meta_box() | |
| 1523 | +	{ | |
| 1524 | + $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration | |
| 1525 | +			? $this->_transaction->primary_registration()->get_first_related('Attendee') | |
| 1526 | + : null; | |
| 1527 | +		if (! $primary_att instanceof EE_Attendee) { | |
| 1528 | + $this->_template_args['no_attendee_message'] = esc_html__( | |
| 1529 | + 'There is no attached contact for this transaction. The transaction either failed due to an error or was abandoned.', | |
| 1530 | + 'event_espresso' | |
| 1531 | + ); | |
| 1532 | + $primary_att = EEM_Attendee::instance()->create_default_object(); | |
| 1533 | + } | |
| 1534 | + $this->_template_args['ATT_ID'] = $primary_att->ID(); | |
| 1535 | + $this->_template_args['prime_reg_fname'] = $primary_att->fname(); | |
| 1536 | + $this->_template_args['prime_reg_lname'] = $primary_att->lname(); | |
| 1537 | + $this->_template_args['prime_reg_email'] = $primary_att->email(); | |
| 1538 | + $this->_template_args['prime_reg_phone'] = $primary_att->phone(); | |
| 1539 | + $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce( | |
| 1540 | + array( | |
| 1541 | + 'action' => 'edit_attendee', | |
| 1542 | + 'post' => $primary_att->ID(), | |
| 1543 | + ), | |
| 1544 | + REG_ADMIN_URL | |
| 1545 | + ); | |
| 1546 | + // get formatted address for registrant | |
| 1547 | + $this->_template_args['formatted_address'] = EEH_Address::format($primary_att); | |
| 1548 | + echo EEH_Template::display_template( | |
| 1549 | + TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php', | |
| 1550 | + $this->_template_args, | |
| 1551 | + true | |
| 1552 | + ); | |
| 1553 | + } | |
| 1554 | + | |
| 1555 | + | |
| 1556 | + /** | |
| 1557 | + * txn_billing_info_side_meta_box | |
| 1558 | + * generates HTML for the Edit Transaction side meta box | |
| 1559 | + * | |
| 1560 | + * @access public | |
| 1561 | + * @return void | |
| 1562 | + * @throws DomainException | |
| 1563 | + * @throws EE_Error | |
| 1564 | + */ | |
| 1565 | + public function txn_billing_info_side_meta_box() | |
| 1566 | +	{ | |
| 1567 | + | |
| 1568 | + $this->_template_args['billing_form'] = $this->_transaction->billing_info(); | |
| 1569 | + $this->_template_args['billing_form_url'] = add_query_arg( | |
| 1570 | +			array('action' => 'edit_transaction', 'process' => 'billing'), | |
| 1571 | + TXN_ADMIN_URL | |
| 1572 | + ); | |
| 1573 | + | |
| 1574 | + $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php'; | |
| 1575 | + echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/ | |
| 1576 | + } | |
| 1577 | + | |
| 1578 | + | |
| 1579 | + /** | |
| 1580 | + * apply_payments_or_refunds | |
| 1581 | + * registers a payment or refund made towards a transaction | |
| 1582 | + * | |
| 1583 | + * @access public | |
| 1584 | + * @return void | |
| 1585 | + * @throws EE_Error | |
| 1586 | + * @throws InvalidArgumentException | |
| 1587 | + * @throws ReflectionException | |
| 1588 | + * @throws RuntimeException | |
| 1589 | + * @throws InvalidDataTypeException | |
| 1590 | + * @throws InvalidInterfaceException | |
| 1591 | + */ | |
| 1592 | + public function apply_payments_or_refunds() | |
| 1593 | +	{ | |
| 1594 | +		$json_response_data = array('return_data' => false); | |
| 1595 | + $valid_data = $this->_validate_payment_request_data(); | |
| 1596 | + $has_access = EE_Registry::instance()->CAP->current_user_can( | |
| 1597 | + 'ee_edit_payments', | |
| 1598 | + 'apply_payment_or_refund_from_registration_details' | |
| 1599 | + ); | |
| 1600 | +		if (! empty($valid_data) && $has_access) { | |
| 1601 | + $PAY_ID = $valid_data['PAY_ID']; | |
| 1602 | + // save the new payment | |
| 1603 | + $payment = $this->_create_payment_from_request_data($valid_data); | |
| 1604 | + // get the TXN for this payment | |
| 1605 | + $transaction = $payment->transaction(); | |
| 1606 | + // verify transaction | |
| 1607 | +			if ($transaction instanceof EE_Transaction) { | |
| 1608 | + // calculate_total_payments_and_update_status | |
| 1609 | + $this->_process_transaction_payments($transaction); | |
| 1610 | + $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment); | |
| 1611 | + $this->_remove_existing_registration_payments($payment, $PAY_ID); | |
| 1612 | + // apply payment to registrations (if applicable) | |
| 1613 | +				if (! empty($REG_IDs)) { | |
| 1614 | + $this->_update_registration_payments($transaction, $payment, $REG_IDs); | |
| 1615 | + $this->_maybe_send_notifications(); | |
| 1616 | + // now process status changes for the same registrations | |
| 1617 | + $this->_process_registration_status_change($transaction, $REG_IDs); | |
| 1618 | + } | |
| 1619 | + $this->_maybe_send_notifications($payment); | |
| 1620 | + // prepare to render page | |
| 1621 | + $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs); | |
| 1622 | + do_action( | |
| 1623 | + 'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording', | |
| 1624 | + $transaction, | |
| 1625 | + $payment | |
| 1626 | + ); | |
| 1627 | +			} else { | |
| 1628 | + EE_Error::add_error( | |
| 1629 | + esc_html__( | |
| 1630 | + 'A valid Transaction for this payment could not be retrieved.', | |
| 1631 | + 'event_espresso' | |
| 1632 | + ), | |
| 1633 | + __FILE__, | |
| 1634 | + __FUNCTION__, | |
| 1635 | + __LINE__ | |
| 1636 | + ); | |
| 1637 | + } | |
| 1638 | +		} else { | |
| 1639 | +			if ($has_access) { | |
| 1640 | + EE_Error::add_error( | |
| 1641 | + esc_html__( | |
| 1642 | + 'The payment form data could not be processed. Please try again.', | |
| 1643 | + 'event_espresso' | |
| 1644 | + ), | |
| 1645 | + __FILE__, | |
| 1646 | + __FUNCTION__, | |
| 1647 | + __LINE__ | |
| 1648 | + ); | |
| 1649 | +			} else { | |
| 1650 | + EE_Error::add_error( | |
| 1651 | + esc_html__( | |
| 1652 | + 'You do not have access to apply payments or refunds to a registration.', | |
| 1653 | + 'event_espresso' | |
| 1654 | + ), | |
| 1655 | + __FILE__, | |
| 1656 | + __FUNCTION__, | |
| 1657 | + __LINE__ | |
| 1658 | + ); | |
| 1659 | + } | |
| 1660 | + } | |
| 1661 | + $notices = EE_Error::get_notices( | |
| 1662 | + false, | |
| 1663 | + false, | |
| 1664 | + false | |
| 1665 | + ); | |
| 1666 | + $this->_template_args = array( | |
| 1667 | + 'data' => $json_response_data, | |
| 1668 | + 'error' => $notices['errors'], | |
| 1669 | + 'success' => $notices['success'], | |
| 1670 | + ); | |
| 1671 | + $this->_return_json(); | |
| 1672 | + } | |
| 1673 | + | |
| 1674 | + | |
| 1675 | + /** | |
| 1676 | + * _validate_payment_request_data | |
| 1677 | + * | |
| 1678 | + * @return array | |
| 1679 | + * @throws EE_Error | |
| 1680 | + */ | |
| 1681 | + protected function _validate_payment_request_data() | |
| 1682 | +	{ | |
| 1683 | +		if (! isset($this->_req_data['txn_admin_payment'])) { | |
| 1684 | + return false; | |
| 1685 | + } | |
| 1686 | + $payment_form = $this->_generate_payment_form_section(); | |
| 1687 | +		try { | |
| 1688 | +			if ($payment_form->was_submitted()) { | |
| 1689 | + $payment_form->receive_form_submission(); | |
| 1690 | +				if (! $payment_form->is_valid()) { | |
| 1691 | + $submission_error_messages = array(); | |
| 1692 | +					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) { | |
| 1693 | +						if ($validation_error instanceof EE_Validation_Error) { | |
| 1694 | + $submission_error_messages[] = sprintf( | |
| 1695 | +								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'), | |
| 1696 | + $validation_error->get_form_section()->html_label_text(), | |
| 1697 | + $validation_error->getMessage() | |
| 1698 | + ); | |
| 1699 | + } | |
| 1700 | + } | |
| 1701 | + EE_Error::add_error( | |
| 1702 | +						implode('<br />', $submission_error_messages), | |
| 1703 | + __FILE__, | |
| 1704 | + __FUNCTION__, | |
| 1705 | + __LINE__ | |
| 1706 | + ); | |
| 1707 | + | |
| 1708 | + return array(); | |
| 1709 | + } | |
| 1710 | + } | |
| 1711 | +		} catch (EE_Error $e) { | |
| 1712 | + EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | |
| 1713 | + | |
| 1714 | + return array(); | |
| 1715 | + } | |
| 1716 | + | |
| 1717 | + return $payment_form->valid_data(); | |
| 1718 | + } | |
| 1719 | + | |
| 1720 | + | |
| 1721 | + /** | |
| 1722 | + * _generate_payment_form_section | |
| 1723 | + * | |
| 1724 | + * @return EE_Form_Section_Proper | |
| 1725 | + * @throws EE_Error | |
| 1726 | + */ | |
| 1727 | + protected function _generate_payment_form_section() | |
| 1728 | +	{ | |
| 1729 | + return new EE_Form_Section_Proper( | |
| 1730 | + array( | |
| 1731 | + 'name' => 'txn_admin_payment', | |
| 1732 | + 'subsections' => array( | |
| 1733 | + 'PAY_ID' => new EE_Text_Input( | |
| 1734 | + array( | |
| 1735 | + 'default' => 0, | |
| 1736 | + 'required' => false, | |
| 1737 | +							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'), | |
| 1738 | + 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1739 | + ) | |
| 1740 | + ), | |
| 1741 | + 'TXN_ID' => new EE_Text_Input( | |
| 1742 | + array( | |
| 1743 | + 'default' => 0, | |
| 1744 | + 'required' => true, | |
| 1745 | +							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'), | |
| 1746 | + 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1747 | + ) | |
| 1748 | + ), | |
| 1749 | + 'type' => new EE_Text_Input( | |
| 1750 | + array( | |
| 1751 | + 'default' => 1, | |
| 1752 | + 'required' => true, | |
| 1753 | +							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'), | |
| 1754 | + 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1755 | + ) | |
| 1756 | + ), | |
| 1757 | + 'amount' => new EE_Text_Input( | |
| 1758 | + array( | |
| 1759 | + 'default' => 0, | |
| 1760 | + 'required' => true, | |
| 1761 | +							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'), | |
| 1762 | + 'validation_strategies' => array(new EE_Float_Normalization()), | |
| 1763 | + ) | |
| 1764 | + ), | |
| 1765 | + 'status' => new EE_Text_Input( | |
| 1766 | + array( | |
| 1767 | + 'default' => EEM_Payment::status_id_approved, | |
| 1768 | + 'required' => true, | |
| 1769 | +							'html_label_text' => esc_html__('Payment status', 'event_espresso'), | |
| 1770 | + ) | |
| 1771 | + ), | |
| 1772 | + 'PMD_ID' => new EE_Text_Input( | |
| 1773 | + array( | |
| 1774 | + 'default' => 2, | |
| 1775 | + 'required' => true, | |
| 1776 | +							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'), | |
| 1777 | + 'validation_strategies' => array(new EE_Int_Normalization()), | |
| 1778 | + ) | |
| 1779 | + ), | |
| 1780 | + 'date' => new EE_Text_Input( | |
| 1781 | + array( | |
| 1782 | + 'default' => time(), | |
| 1783 | + 'required' => true, | |
| 1784 | +							'html_label_text' => esc_html__('Payment date', 'event_espresso'), | |
| 1785 | + ) | |
| 1786 | + ), | |
| 1787 | + 'txn_id_chq_nmbr' => new EE_Text_Input( | |
| 1788 | + array( | |
| 1789 | + 'default' => '', | |
| 1790 | + 'required' => false, | |
| 1791 | +							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'), | |
| 1792 | + 'validation_strategies' => array( | |
| 1793 | + new EE_Max_Length_Validation_Strategy( | |
| 1794 | +									esc_html__('Input too long', 'event_espresso'), | |
| 1795 | + 100 | |
| 1796 | + ), | |
| 1797 | + ), | |
| 1798 | + ) | |
| 1799 | + ), | |
| 1800 | + 'po_number' => new EE_Text_Input( | |
| 1801 | + array( | |
| 1802 | + 'default' => '', | |
| 1803 | + 'required' => false, | |
| 1804 | +							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'), | |
| 1805 | + 'validation_strategies' => array( | |
| 1806 | + new EE_Max_Length_Validation_Strategy( | |
| 1807 | +									esc_html__('Input too long', 'event_espresso'), | |
| 1808 | + 100 | |
| 1809 | + ), | |
| 1810 | + ), | |
| 1811 | + ) | |
| 1812 | + ), | |
| 1813 | + 'accounting' => new EE_Text_Input( | |
| 1814 | + array( | |
| 1815 | + 'default' => '', | |
| 1816 | + 'required' => false, | |
| 1817 | +							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'), | |
| 1818 | + 'validation_strategies' => array( | |
| 1819 | + new EE_Max_Length_Validation_Strategy( | |
| 1820 | +									esc_html__('Input too long', 'event_espresso'), | |
| 1821 | + 100 | |
| 1822 | + ), | |
| 1823 | + ), | |
| 1824 | + ) | |
| 1825 | + ), | |
| 1826 | + ), | |
| 1827 | + ) | |
| 1828 | + ); | |
| 1829 | + } | |
| 1830 | + | |
| 1831 | + | |
| 1832 | + /** | |
| 1833 | + * _create_payment_from_request_data | |
| 1834 | + * | |
| 1835 | + * @param array $valid_data | |
| 1836 | + * @return EE_Payment | |
| 1837 | + * @throws EE_Error | |
| 1838 | + */ | |
| 1839 | + protected function _create_payment_from_request_data($valid_data) | |
| 1840 | +	{ | |
| 1841 | + $PAY_ID = $valid_data['PAY_ID']; | |
| 1842 | + // get payment amount | |
| 1843 | + $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0; | |
| 1844 | + // payments have a type value of 1 and refunds have a type value of -1 | |
| 1845 | + // so multiplying amount by type will give a positive value for payments, and negative values for refunds | |
| 1846 | + $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount; | |
| 1847 | + // for some reason the date string coming in has extra spaces between the date and time. This fixes that. | |
| 1848 | + $date = $valid_data['date'] | |
| 1849 | +			? preg_replace('/\s+/', ' ', $valid_data['date']) | |
| 1850 | +			: date('Y-m-d g:i a', current_time('timestamp')); | |
| 1851 | + $payment = EE_Payment::new_instance( | |
| 1852 | + array( | |
| 1853 | + 'TXN_ID' => $valid_data['TXN_ID'], | |
| 1854 | + 'STS_ID' => $valid_data['status'], | |
| 1855 | + 'PAY_timestamp' => $date, | |
| 1856 | + 'PAY_source' => EEM_Payment_Method::scope_admin, | |
| 1857 | + 'PMD_ID' => $valid_data['PMD_ID'], | |
| 1858 | + 'PAY_amount' => $amount, | |
| 1859 | + 'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'], | |
| 1860 | + 'PAY_po_number' => $valid_data['po_number'], | |
| 1861 | + 'PAY_extra_accntng' => $valid_data['accounting'], | |
| 1862 | + 'PAY_details' => $valid_data, | |
| 1863 | + 'PAY_ID' => $PAY_ID, | |
| 1864 | + ), | |
| 1865 | + '', | |
| 1866 | +			array('Y-m-d', 'g:i a') | |
| 1867 | + ); | |
| 1868 | + | |
| 1869 | +		if (! $payment->save()) { | |
| 1870 | + EE_Error::add_error( | |
| 1871 | + sprintf( | |
| 1872 | +					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'), | |
| 1873 | + $payment->ID() | |
| 1874 | + ), | |
| 1875 | + __FILE__, | |
| 1876 | + __FUNCTION__, | |
| 1877 | + __LINE__ | |
| 1878 | + ); | |
| 1879 | + } | |
| 1880 | + | |
| 1881 | + return $payment; | |
| 1882 | + } | |
| 1883 | + | |
| 1884 | + | |
| 1885 | + /** | |
| 1886 | + * _process_transaction_payments | |
| 1887 | + * | |
| 1888 | + * @param \EE_Transaction $transaction | |
| 1889 | + * @return void | |
| 1890 | + * @throws EE_Error | |
| 1891 | + * @throws InvalidArgumentException | |
| 1892 | + * @throws ReflectionException | |
| 1893 | + * @throws InvalidDataTypeException | |
| 1894 | + * @throws InvalidInterfaceException | |
| 1895 | + */ | |
| 1896 | + protected function _process_transaction_payments(EE_Transaction $transaction) | |
| 1897 | +	{ | |
| 1898 | + /** @type EE_Transaction_Payments $transaction_payments */ | |
| 1899 | +		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 1900 | + // update the transaction with this payment | |
| 1901 | +		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) { | |
| 1902 | + EE_Error::add_success( | |
| 1903 | + esc_html__( | |
| 1904 | + 'The payment has been processed successfully.', | |
| 1905 | + 'event_espresso' | |
| 1906 | + ), | |
| 1907 | + __FILE__, | |
| 1908 | + __FUNCTION__, | |
| 1909 | + __LINE__ | |
| 1910 | + ); | |
| 1911 | +		} else { | |
| 1912 | + EE_Error::add_error( | |
| 1913 | + esc_html__( | |
| 1914 | + 'The payment was processed successfully but the amount paid for the transaction was not updated.', | |
| 1915 | + 'event_espresso' | |
| 1916 | + ), | |
| 1917 | + __FILE__, | |
| 1918 | + __FUNCTION__, | |
| 1919 | + __LINE__ | |
| 1920 | + ); | |
| 1921 | + } | |
| 1922 | + } | |
| 1923 | + | |
| 1924 | + | |
| 1925 | + /** | |
| 1926 | + * _get_REG_IDs_to_apply_payment_to | |
| 1927 | + * returns a list of registration IDs that the payment will apply to | |
| 1928 | + * | |
| 1929 | + * @param \EE_Payment $payment | |
| 1930 | + * @return array | |
| 1931 | + * @throws EE_Error | |
| 1932 | + */ | |
| 1933 | + protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment) | |
| 1934 | +	{ | |
| 1935 | + $REG_IDs = array(); | |
| 1936 | + // grab array of IDs for specific registrations to apply changes to | |
| 1937 | +		if (isset($this->_req_data['txn_admin_payment']['registrations'])) { | |
| 1938 | + $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations']; | |
| 1939 | + } | |
| 1940 | + // nothing specified ? then get all reg IDs | |
| 1941 | +		if (empty($REG_IDs)) { | |
| 1942 | + $registrations = $payment->transaction()->registrations(); | |
| 1943 | + $REG_IDs = ! empty($registrations) | |
| 1944 | + ? array_keys($registrations) | |
| 1945 | + : $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 1946 | + } | |
| 1947 | + | |
| 1948 | + // ensure that REG_IDs are integers and NOT strings | |
| 1949 | +		return array_map('intval', $REG_IDs); | |
| 1950 | + } | |
| 1951 | + | |
| 1952 | + | |
| 1953 | + /** | |
| 1954 | + * @return array | |
| 1955 | + */ | |
| 1956 | + public function existing_reg_payment_REG_IDs() | |
| 1957 | +	{ | |
| 1958 | + return $this->_existing_reg_payment_REG_IDs; | |
| 1959 | + } | |
| 1960 | + | |
| 1961 | + | |
| 1962 | + /** | |
| 1963 | + * @param array $existing_reg_payment_REG_IDs | |
| 1964 | + */ | |
| 1965 | + public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null) | |
| 1966 | +	{ | |
| 1967 | + $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs; | |
| 1968 | + } | |
| 1969 | + | |
| 1970 | + | |
| 1971 | + /** | |
| 1972 | + * _get_existing_reg_payment_REG_IDs | |
| 1973 | + * returns a list of registration IDs that the payment is currently related to | |
| 1974 | + * as recorded in the database | |
| 1975 | + * | |
| 1976 | + * @param \EE_Payment $payment | |
| 1977 | + * @return array | |
| 1978 | + * @throws EE_Error | |
| 1979 | + */ | |
| 1980 | + protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment) | |
| 1981 | +	{ | |
| 1982 | +		if ($this->existing_reg_payment_REG_IDs() === null) { | |
| 1983 | + // let's get any existing reg payment records for this payment | |
| 1984 | +			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration'); | |
| 1985 | + // but we only want the REG IDs, so grab the array keys | |
| 1986 | + $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs) | |
| 1987 | + ? array_keys($existing_reg_payment_REG_IDs) | |
| 1988 | + : array(); | |
| 1989 | + $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs); | |
| 1990 | + } | |
| 1991 | + | |
| 1992 | + return $this->existing_reg_payment_REG_IDs(); | |
| 1993 | + } | |
| 1994 | + | |
| 1995 | + | |
| 1996 | + /** | |
| 1997 | + * _remove_existing_registration_payments | |
| 1998 | + * this calculates the difference between existing relations | |
| 1999 | + * to the supplied payment and the new list registration IDs, | |
| 2000 | + * removes any related registrations that no longer apply, | |
| 2001 | + * and then updates the registration paid fields | |
| 2002 | + * | |
| 2003 | + * @param \EE_Payment $payment | |
| 2004 | + * @param int $PAY_ID | |
| 2005 | + * @return bool; | |
| 2006 | + * @throws EE_Error | |
| 2007 | + * @throws InvalidArgumentException | |
| 2008 | + * @throws ReflectionException | |
| 2009 | + * @throws InvalidDataTypeException | |
| 2010 | + * @throws InvalidInterfaceException | |
| 2011 | + */ | |
| 2012 | + protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0) | |
| 2013 | +	{ | |
| 2014 | + // newly created payments will have nothing recorded for $PAY_ID | |
| 2015 | +		if ($PAY_ID == 0) { | |
| 2016 | + return false; | |
| 2017 | + } | |
| 2018 | + $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 2019 | +		if (empty($existing_reg_payment_REG_IDs)) { | |
| 2020 | + return false; | |
| 2021 | + } | |
| 2022 | + /** @type EE_Transaction_Payments $transaction_payments */ | |
| 2023 | +		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 2024 | + | |
| 2025 | + return $transaction_payments->delete_registration_payments_and_update_registrations( | |
| 2026 | + $payment, | |
| 2027 | + array( | |
| 2028 | + array( | |
| 2029 | + 'PAY_ID' => $payment->ID(), | |
| 2030 | +					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs), | |
| 2031 | + ), | |
| 2032 | + ) | |
| 2033 | + ); | |
| 2034 | + } | |
| 2035 | + | |
| 2036 | + | |
| 2037 | + /** | |
| 2038 | + * _update_registration_payments | |
| 2039 | + * this applies the payments to the selected registrations | |
| 2040 | + * but only if they have not already been paid for | |
| 2041 | + * | |
| 2042 | + * @param EE_Transaction $transaction | |
| 2043 | + * @param \EE_Payment $payment | |
| 2044 | + * @param array $REG_IDs | |
| 2045 | + * @return void | |
| 2046 | + * @throws EE_Error | |
| 2047 | + * @throws InvalidArgumentException | |
| 2048 | + * @throws ReflectionException | |
| 2049 | + * @throws RuntimeException | |
| 2050 | + * @throws InvalidDataTypeException | |
| 2051 | + * @throws InvalidInterfaceException | |
| 2052 | + */ | |
| 2053 | + protected function _update_registration_payments( | |
| 2054 | + EE_Transaction $transaction, | |
| 2055 | + EE_Payment $payment, | |
| 2056 | + $REG_IDs = array() | |
| 2057 | +	) { | |
| 2058 | + // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments() | |
| 2059 | + // so let's do that using our set of REG_IDs from the form | |
| 2060 | + $registration_query_where_params = array( | |
| 2061 | +			'REG_ID' => array('IN', $REG_IDs), | |
| 2062 | + ); | |
| 2063 | + // but add in some conditions regarding payment, | |
| 2064 | + // so that we don't apply payments to registrations that are free or have already been paid for | |
| 2065 | + // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative ) | |
| 2066 | +		if (! $payment->is_a_refund()) { | |
| 2067 | +			$registration_query_where_params['REG_final_price'] = array('!=', 0); | |
| 2068 | +			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true); | |
| 2069 | + } | |
| 2070 | + $registrations = $transaction->registrations(array($registration_query_where_params)); | |
| 2071 | +		if (! empty($registrations)) { | |
| 2072 | + /** @type EE_Payment_Processor $payment_processor */ | |
| 2073 | +			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor'); | |
| 2074 | + $payment_processor->process_registration_payments($transaction, $payment, $registrations); | |
| 2075 | + } | |
| 2076 | + } | |
| 2077 | + | |
| 2078 | + | |
| 2079 | + /** | |
| 2080 | + * _process_registration_status_change | |
| 2081 | + * This processes requested registration status changes for all the registrations | |
| 2082 | + * on a given transaction and (optionally) sends out notifications for the changes. | |
| 2083 | + * | |
| 2084 | + * @param EE_Transaction $transaction | |
| 2085 | + * @param array $REG_IDs | |
| 2086 | + * @return bool | |
| 2087 | + * @throws EE_Error | |
| 2088 | + * @throws InvalidArgumentException | |
| 2089 | + * @throws ReflectionException | |
| 2090 | + * @throws InvalidDataTypeException | |
| 2091 | + * @throws InvalidInterfaceException | |
| 2092 | + */ | |
| 2093 | + protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array()) | |
| 2094 | +	{ | |
| 2095 | + // first if there is no change in status then we get out. | |
| 2096 | + if (! isset($this->_req_data['txn_reg_status_change']['reg_status']) | |
| 2097 | + || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN' | |
| 2098 | +		) { | |
| 2099 | + // no error message, no change requested, just nothing to do man. | |
| 2100 | + return false; | |
| 2101 | + } | |
| 2102 | + /** @type EE_Transaction_Processor $transaction_processor */ | |
| 2103 | +		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor'); | |
| 2104 | + | |
| 2105 | + // made it here dude? Oh WOW. K, let's take care of changing the statuses | |
| 2106 | + return $transaction_processor->manually_update_registration_statuses( | |
| 2107 | + $transaction, | |
| 2108 | + sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']), | |
| 2109 | +			array(array('REG_ID' => array('IN', $REG_IDs))) | |
| 2110 | + ); | |
| 2111 | + } | |
| 2112 | + | |
| 2113 | + | |
| 2114 | + /** | |
| 2115 | + * _build_payment_json_response | |
| 2116 | + * | |
| 2117 | + * @access public | |
| 2118 | + * @param \EE_Payment $payment | |
| 2119 | + * @param array $REG_IDs | |
| 2120 | + * @param bool | null $delete_txn_reg_status_change | |
| 2121 | + * @return array | |
| 2122 | + * @throws EE_Error | |
| 2123 | + * @throws InvalidArgumentException | |
| 2124 | + * @throws InvalidDataTypeException | |
| 2125 | + * @throws InvalidInterfaceException | |
| 2126 | + * @throws ReflectionException | |
| 2127 | + */ | |
| 2128 | + protected function _build_payment_json_response( | |
| 2129 | + EE_Payment $payment, | |
| 2130 | + $REG_IDs = array(), | |
| 2131 | + $delete_txn_reg_status_change = null | |
| 2132 | +	) { | |
| 2133 | + // was the payment deleted ? | |
| 2134 | +		if (is_bool($delete_txn_reg_status_change)) { | |
| 2135 | + return array( | |
| 2136 | + 'PAY_ID' => $payment->ID(), | |
| 2137 | + 'amount' => $payment->amount(), | |
| 2138 | + 'total_paid' => $payment->transaction()->paid(), | |
| 2139 | + 'txn_status' => $payment->transaction()->status_ID(), | |
| 2140 | + 'pay_status' => $payment->STS_ID(), | |
| 2141 | + 'registrations' => $this->_registration_payment_data_array($REG_IDs), | |
| 2142 | + 'delete_txn_reg_status_change' => $delete_txn_reg_status_change, | |
| 2143 | + ); | |
| 2144 | +		} else { | |
| 2145 | + $this->_get_payment_status_array(); | |
| 2146 | + | |
| 2147 | + return array( | |
| 2148 | + 'amount' => $payment->amount(), | |
| 2149 | + 'total_paid' => $payment->transaction()->paid(), | |
| 2150 | + 'txn_status' => $payment->transaction()->status_ID(), | |
| 2151 | + 'pay_status' => $payment->STS_ID(), | |
| 2152 | + 'PAY_ID' => $payment->ID(), | |
| 2153 | + 'STS_ID' => $payment->STS_ID(), | |
| 2154 | + 'status' => self::$_pay_status[ $payment->STS_ID() ], | |
| 2155 | +				'date'             => $payment->timestamp('Y-m-d', 'h:i a'), | |
| 2156 | + 'method' => strtoupper($payment->source()), | |
| 2157 | + 'PM_ID' => $payment->payment_method() ? $payment->payment_method()->ID() : 1, | |
| 2158 | + 'gateway' => $payment->payment_method() | |
| 2159 | + ? $payment->payment_method()->admin_name() | |
| 2160 | +					: esc_html__("Unknown", 'event_espresso'), | |
| 2161 | + 'gateway_response' => $payment->gateway_response(), | |
| 2162 | + 'txn_id_chq_nmbr' => $payment->txn_id_chq_nmbr(), | |
| 2163 | + 'po_number' => $payment->po_number(), | |
| 2164 | + 'extra_accntng' => $payment->extra_accntng(), | |
| 2165 | + 'registrations' => $this->_registration_payment_data_array($REG_IDs), | |
| 2166 | + ); | |
| 2167 | + } | |
| 2168 | + } | |
| 2169 | + | |
| 2170 | + | |
| 2171 | + /** | |
| 2172 | + * delete_payment | |
| 2173 | + * delete a payment or refund made towards a transaction | |
| 2174 | + * | |
| 2175 | + * @access public | |
| 2176 | + * @return void | |
| 2177 | + * @throws EE_Error | |
| 2178 | + * @throws InvalidArgumentException | |
| 2179 | + * @throws ReflectionException | |
| 2180 | + * @throws InvalidDataTypeException | |
| 2181 | + * @throws InvalidInterfaceException | |
| 2182 | + */ | |
| 2183 | + public function delete_payment() | |
| 2184 | +	{ | |
| 2185 | +		$json_response_data = array('return_data' => false); | |
| 2186 | + $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID']) | |
| 2187 | + ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID']) | |
| 2188 | + : 0; | |
| 2189 | + $can_delete = EE_Registry::instance()->CAP->current_user_can( | |
| 2190 | + 'ee_delete_payments', | |
| 2191 | + 'delete_payment_from_registration_details' | |
| 2192 | + ); | |
| 2193 | +		if ($PAY_ID && $can_delete) { | |
| 2194 | + $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change']) | |
| 2195 | + ? $this->_req_data['delete_txn_reg_status_change'] | |
| 2196 | + : false; | |
| 2197 | + $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID); | |
| 2198 | +			if ($payment instanceof EE_Payment) { | |
| 2199 | + $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment); | |
| 2200 | + /** @type EE_Transaction_Payments $transaction_payments */ | |
| 2201 | +				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments'); | |
| 2202 | +				if ($transaction_payments->delete_payment_and_update_transaction($payment)) { | |
| 2203 | + $json_response_data['return_data'] = $this->_build_payment_json_response( | |
| 2204 | + $payment, | |
| 2205 | + $REG_IDs, | |
| 2206 | + $delete_txn_reg_status_change | |
| 2207 | + ); | |
| 2208 | +					if ($delete_txn_reg_status_change) { | |
| 2209 | + $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change; | |
| 2210 | + // MAKE sure we also add the delete_txn_req_status_change to the | |
| 2211 | + // $_REQUEST global because that's how messages will be looking for it. | |
| 2212 | + $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change; | |
| 2213 | + $this->_maybe_send_notifications(); | |
| 2214 | + $this->_process_registration_status_change($payment->transaction(), $REG_IDs); | |
| 2215 | + } | |
| 2216 | + } | |
| 2217 | +			} else { | |
| 2218 | + EE_Error::add_error( | |
| 2219 | +					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'), | |
| 2220 | + __FILE__, | |
| 2221 | + __FUNCTION__, | |
| 2222 | + __LINE__ | |
| 2223 | + ); | |
| 2224 | + } | |
| 2225 | +		} else { | |
| 2226 | +			if ($can_delete) { | |
| 2227 | + EE_Error::add_error( | |
| 2228 | + esc_html__( | |
| 2229 | + 'A valid Payment ID was not received, therefore payment form data could not be loaded.', | |
| 2230 | + 'event_espresso' | |
| 2231 | + ), | |
| 2232 | + __FILE__, | |
| 2233 | + __FUNCTION__, | |
| 2234 | + __LINE__ | |
| 2235 | + ); | |
| 2236 | +			} else { | |
| 2237 | + EE_Error::add_error( | |
| 2238 | + esc_html__( | |
| 2239 | + 'You do not have access to delete a payment.', | |
| 2240 | + 'event_espresso' | |
| 2241 | + ), | |
| 2242 | + __FILE__, | |
| 2243 | + __FUNCTION__, | |
| 2244 | + __LINE__ | |
| 2245 | + ); | |
| 2246 | + } | |
| 2247 | + } | |
| 2248 | + $notices = EE_Error::get_notices(false, false, false); | |
| 2249 | + $this->_template_args = array( | |
| 2250 | + 'data' => $json_response_data, | |
| 2251 | + 'success' => $notices['success'], | |
| 2252 | + 'error' => $notices['errors'], | |
| 2253 | + 'attention' => $notices['attention'], | |
| 2254 | + ); | |
| 2255 | + $this->_return_json(); | |
| 2256 | + } | |
| 2257 | + | |
| 2258 | + | |
| 2259 | + /** | |
| 2260 | + * _registration_payment_data_array | |
| 2261 | + * adds info for 'owing' and 'paid' for each registration to the json response | |
| 2262 | + * | |
| 2263 | + * @access protected | |
| 2264 | + * @param array $REG_IDs | |
| 2265 | + * @return array | |
| 2266 | + * @throws EE_Error | |
| 2267 | + * @throws InvalidArgumentException | |
| 2268 | + * @throws InvalidDataTypeException | |
| 2269 | + * @throws InvalidInterfaceException | |
| 2270 | + * @throws ReflectionException | |
| 2271 | + */ | |
| 2272 | + protected function _registration_payment_data_array($REG_IDs) | |
| 2273 | +	{ | |
| 2274 | + $registration_payment_data = array(); | |
| 2275 | + // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows. | |
| 2276 | +		if (! empty($REG_IDs)) { | |
| 2277 | +			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs)))); | |
| 2278 | +			foreach ($registrations as $registration) { | |
| 2279 | +				if ($registration instanceof EE_Registration) { | |
| 2280 | + $registration_payment_data[ $registration->ID() ] = array( | |
| 2281 | + 'paid' => $registration->pretty_paid(), | |
| 2282 | + 'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()), | |
| 2283 | + ); | |
| 2284 | + } | |
| 2285 | + } | |
| 2286 | + } | |
| 2287 | + | |
| 2288 | + return $registration_payment_data; | |
| 2289 | + } | |
| 2290 | + | |
| 2291 | + | |
| 2292 | + /** | |
| 2293 | + * _maybe_send_notifications | |
| 2294 | + * determines whether or not the admin has indicated that notifications should be sent. | |
| 2295 | + * If so, will toggle a filter switch for delivering registration notices. | |
| 2296 | + * If passed an EE_Payment object, then it will trigger payment notifications instead. | |
| 2297 | + * | |
| 2298 | + * @access protected | |
| 2299 | + * @param \EE_Payment | null $payment | |
| 2300 | + */ | |
| 2301 | + protected function _maybe_send_notifications($payment = null) | |
| 2302 | +	{ | |
| 2303 | +		switch ($payment instanceof EE_Payment) { | |
| 2304 | + // payment notifications | |
| 2305 | + case true: | |
| 2306 | + if (isset( | |
| 2307 | + $this->_req_data['txn_payments'], | |
| 2308 | + $this->_req_data['txn_payments']['send_notifications'] | |
| 2309 | + ) | |
| 2310 | + && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN) | |
| 2311 | +				) { | |
| 2312 | + $this->_process_payment_notification($payment); | |
| 2313 | + } | |
| 2314 | + break; | |
| 2315 | + // registration notifications | |
| 2316 | + case false: | |
| 2317 | + if (isset( | |
| 2318 | + $this->_req_data['txn_reg_status_change'], | |
| 2319 | + $this->_req_data['txn_reg_status_change']['send_notifications'] | |
| 2320 | + ) | |
| 2321 | + && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN) | |
| 2322 | +				) { | |
| 2323 | +					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true'); | |
| 2324 | + } | |
| 2325 | + break; | |
| 2326 | + } | |
| 2327 | + } | |
| 2328 | + | |
| 2329 | + | |
| 2330 | + /** | |
| 2331 | + * _send_payment_reminder | |
| 2332 | + * generates HTML for the View Transaction Details Admin page | |
| 2333 | + * | |
| 2334 | + * @access protected | |
| 2335 | + * @return void | |
| 2336 | + * @throws EE_Error | |
| 2337 | + * @throws InvalidArgumentException | |
| 2338 | + * @throws InvalidDataTypeException | |
| 2339 | + * @throws InvalidInterfaceException | |
| 2340 | + */ | |
| 2341 | + protected function _send_payment_reminder() | |
| 2342 | +	{ | |
| 2343 | + $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false; | |
| 2344 | + $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID); | |
| 2345 | + $query_args = isset($this->_req_data['redirect_to']) ? array( | |
| 2346 | + 'action' => $this->_req_data['redirect_to'], | |
| 2347 | + 'TXN_ID' => $this->_req_data['TXN_ID'], | |
| 2348 | + ) : array(); | |
| 2349 | + do_action( | |
| 2350 | + 'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder', | |
| 2351 | + $transaction | |
| 2352 | + ); | |
| 2353 | + $this->_redirect_after_action( | |
| 2354 | + false, | |
| 2355 | +			esc_html__('payment reminder', 'event_espresso'), | |
| 2356 | +			esc_html__('sent', 'event_espresso'), | |
| 2357 | + $query_args, | |
| 2358 | + true | |
| 2359 | + ); | |
| 2360 | + } | |
| 2361 | + | |
| 2362 | + | |
| 2363 | + /** | |
| 2364 | + * get_transactions | |
| 2365 | + * get transactions for given parameters (used by list table) | |
| 2366 | + * | |
| 2367 | + * @param int $perpage how many transactions displayed per page | |
| 2368 | + * @param boolean $count return the count or objects | |
| 2369 | + * @param string $view | |
| 2370 | + * @return mixed int = count || array of transaction objects | |
| 2371 | + * @throws EE_Error | |
| 2372 | + * @throws InvalidArgumentException | |
| 2373 | + * @throws InvalidDataTypeException | |
| 2374 | + * @throws InvalidInterfaceException | |
| 2375 | + */ | |
| 2376 | + public function get_transactions($perpage, $count = false, $view = '') | |
| 2377 | +	{ | |
| 2378 | + | |
| 2379 | + $TXN = EEM_Transaction::instance(); | |
| 2380 | + | |
| 2381 | + $start_date = isset($this->_req_data['txn-filter-start-date']) | |
| 2382 | + ? wp_strip_all_tags($this->_req_data['txn-filter-start-date']) | |
| 2383 | + : date( | |
| 2384 | + 'm/d/Y', | |
| 2385 | +				strtotime('-10 year') | |
| 2386 | + ); | |
| 2387 | + $end_date = isset($this->_req_data['txn-filter-end-date']) | |
| 2388 | + ? wp_strip_all_tags($this->_req_data['txn-filter-end-date']) | |
| 2389 | +			: date('m/d/Y'); | |
| 2390 | + | |
| 2391 | + // make sure our timestamps start and end right at the boundaries for each day | |
| 2392 | +		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00'; | |
| 2393 | +		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59'; | |
| 2394 | + | |
| 2395 | + | |
| 2396 | + // convert to timestamps | |
| 2397 | + $start_date = strtotime($start_date); | |
| 2398 | + $end_date = strtotime($end_date); | |
| 2399 | + | |
| 2400 | + // makes sure start date is the lowest value and vice versa | |
| 2401 | + $start_date = min($start_date, $end_date); | |
| 2402 | + $end_date = max($start_date, $end_date); | |
| 2403 | + | |
| 2404 | + // convert to correct format for query | |
| 2405 | + $start_date = EEM_Transaction::instance()->convert_datetime_for_query( | |
| 2406 | + 'TXN_timestamp', | |
| 2407 | +			date('Y-m-d H:i:s', $start_date), | |
| 2408 | + 'Y-m-d H:i:s' | |
| 2409 | + ); | |
| 2410 | + $end_date = EEM_Transaction::instance()->convert_datetime_for_query( | |
| 2411 | + 'TXN_timestamp', | |
| 2412 | +			date('Y-m-d H:i:s', $end_date), | |
| 2413 | + 'Y-m-d H:i:s' | |
| 2414 | + ); | |
| 2415 | + | |
| 2416 | + | |
| 2417 | + // set orderby | |
| 2418 | + $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : ''; | |
| 2419 | + | |
| 2420 | +		switch ($this->_req_data['orderby']) { | |
| 2421 | + case 'TXN_ID': | |
| 2422 | + $orderby = 'TXN_ID'; | |
| 2423 | + break; | |
| 2424 | + case 'ATT_fname': | |
| 2425 | + $orderby = 'Registration.Attendee.ATT_fname'; | |
| 2426 | + break; | |
| 2427 | + case 'event_name': | |
| 2428 | + $orderby = 'Registration.Event.EVT_name'; | |
| 2429 | + break; | |
| 2430 | + default: // 'TXN_timestamp' | |
| 2431 | + $orderby = 'TXN_timestamp'; | |
| 2432 | + } | |
| 2433 | + | |
| 2434 | + $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC'; | |
| 2435 | + $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1; | |
| 2436 | + $per_page = ! empty($perpage) ? $perpage : 10; | |
| 2437 | + $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page; | |
| 2438 | + | |
| 2439 | + $offset = ($current_page - 1) * $per_page; | |
| 2440 | + $limit = array($offset, $per_page); | |
| 2441 | + | |
| 2442 | + $_where = array( | |
| 2443 | +			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)), | |
| 2444 | + 'Registration.REG_count' => 1, | |
| 2445 | + ); | |
| 2446 | + | |
| 2447 | +		if (isset($this->_req_data['EVT_ID'])) { | |
| 2448 | + $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID']; | |
| 2449 | + } | |
| 2450 | + | |
| 2451 | +		if (isset($this->_req_data['s'])) { | |
| 2452 | + $search_string = '%' . $this->_req_data['s'] . '%'; | |
| 2453 | + $_where['OR'] = array( | |
| 2454 | +				'Registration.Event.EVT_name'         => array('LIKE', $search_string), | |
| 2455 | +				'Registration.Event.EVT_desc'         => array('LIKE', $search_string), | |
| 2456 | +				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string), | |
| 2457 | +				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string), | |
| 2458 | +				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string), | |
| 2459 | +				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string), | |
| 2460 | +				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string), | |
| 2461 | +				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string), | |
| 2462 | +				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string), | |
| 2463 | +				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string), | |
| 2464 | +				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string), | |
| 2465 | +				'Registration.REG_final_price'        => array('LIKE', $search_string), | |
| 2466 | +				'Registration.REG_code'               => array('LIKE', $search_string), | |
| 2467 | +				'Registration.REG_count'              => array('LIKE', $search_string), | |
| 2468 | +				'Registration.REG_group_size'         => array('LIKE', $search_string), | |
| 2469 | +				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string), | |
| 2470 | +				'Registration.Ticket.TKT_description' => array('LIKE', $search_string), | |
| 2471 | +				'Payment.PAY_source'                  => array('LIKE', $search_string), | |
| 2472 | +				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string), | |
| 2473 | +				'TXN_session_data'                    => array('LIKE', $search_string), | |
| 2474 | +				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string), | |
| 2475 | + ); | |
| 2476 | + } | |
| 2477 | + | |
| 2478 | + // failed transactions | |
| 2479 | + $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count) | |
| 2480 | + || ($count && $view === 'failed'); | |
| 2481 | + $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count) | |
| 2482 | + || ($count && $view === 'abandoned'); | |
| 2483 | + $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count) | |
| 2484 | + || ($count && $view === 'incomplete'); | |
| 2485 | + | |
| 2486 | +		if ($failed) { | |
| 2487 | + $_where['STS_ID'] = EEM_Transaction::failed_status_code; | |
| 2488 | +		} elseif ($abandoned) { | |
| 2489 | + $_where['STS_ID'] = EEM_Transaction::abandoned_status_code; | |
| 2490 | +		} elseif ($incomplete) { | |
| 2491 | + $_where['STS_ID'] = EEM_Transaction::incomplete_status_code; | |
| 2492 | +		} else { | |
| 2493 | +			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code); | |
| 2494 | +			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code); | |
| 2495 | + } | |
| 2496 | + | |
| 2497 | + $query_params = apply_filters( | |
| 2498 | + 'FHEE__Transactions_Admin_Page___get_transactions_query_params', | |
| 2499 | + array( | |
| 2500 | + $_where, | |
| 2501 | + 'order_by' => array($orderby => $sort), | |
| 2502 | + 'limit' => $limit, | |
| 2503 | + 'default_where_conditions' => EEM_Base::default_where_conditions_this_only, | |
| 2504 | + ), | |
| 2505 | + $this->_req_data, | |
| 2506 | + $view, | |
| 2507 | + $count | |
| 2508 | + ); | |
| 2509 | + | |
| 2510 | + $transactions = $count | |
| 2511 | + ? $TXN->count(array($query_params[0]), 'TXN_ID', true) | |
| 2512 | + : $TXN->get_all($query_params); | |
| 2513 | + | |
| 2514 | + return $transactions; | |
| 2515 | + } | |
| 2516 | 2516 | } | 
| @@ -363,7 +363,7 @@ discard block | ||
| 363 | 363 | // enqueue style | 
| 364 | 364 | wp_register_style( | 
| 365 | 365 | 'espresso_txn', | 
| 366 | - TXN_ASSETS_URL . 'espresso_transactions_admin.css', | |
| 366 | + TXN_ASSETS_URL.'espresso_transactions_admin.css', | |
| 367 | 367 | array(), | 
| 368 | 368 | EVENT_ESPRESSO_VERSION | 
| 369 | 369 | ); | 
| @@ -371,7 +371,7 @@ discard block | ||
| 371 | 371 | // scripts | 
| 372 | 372 | wp_register_script( | 
| 373 | 373 | 'espresso_txn', | 
| 374 | - TXN_ASSETS_URL . 'espresso_transactions_admin.js', | |
| 374 | + TXN_ASSETS_URL.'espresso_transactions_admin.js', | |
| 375 | 375 | array( | 
| 376 | 376 | 'ee_admin_js', | 
| 377 | 377 | 'ee-datepicker', | 
| @@ -499,7 +499,7 @@ discard block | ||
| 499 | 499 | $this->_transaction->verify_abandoned_transaction_status(); | 
| 500 | 500 | } | 
| 501 | 501 | |
| 502 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 502 | +        if ( ! $this->_transaction instanceof EE_Transaction) { | |
| 503 | 503 | $error_msg = sprintf( | 
| 504 | 504 | esc_html__( | 
| 505 | 505 | 'An error occurred and the details for the transaction with the ID # %d could not be retrieved.', | 
| @@ -597,7 +597,7 @@ discard block | ||
| 597 | 597 | 'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items', | 
| 598 | 598 | array( | 
| 599 | 599 | 'overpaid' => array( | 
| 600 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code, | |
| 600 | + 'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::overpaid_status_code, | |
| 601 | 601 | 'desc' => EEH_Template::pretty_status( | 
| 602 | 602 | EEM_Transaction::overpaid_status_code, | 
| 603 | 603 | false, | 
| @@ -605,7 +605,7 @@ discard block | ||
| 605 | 605 | ), | 
| 606 | 606 | ), | 
| 607 | 607 | 'complete' => array( | 
| 608 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code, | |
| 608 | + 'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::complete_status_code, | |
| 609 | 609 | 'desc' => EEH_Template::pretty_status( | 
| 610 | 610 | EEM_Transaction::complete_status_code, | 
| 611 | 611 | false, | 
| @@ -613,7 +613,7 @@ discard block | ||
| 613 | 613 | ), | 
| 614 | 614 | ), | 
| 615 | 615 | 'incomplete' => array( | 
| 616 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code, | |
| 616 | + 'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::incomplete_status_code, | |
| 617 | 617 | 'desc' => EEH_Template::pretty_status( | 
| 618 | 618 | EEM_Transaction::incomplete_status_code, | 
| 619 | 619 | false, | 
| @@ -621,7 +621,7 @@ discard block | ||
| 621 | 621 | ), | 
| 622 | 622 | ), | 
| 623 | 623 | 'abandoned' => array( | 
| 624 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code, | |
| 624 | + 'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::abandoned_status_code, | |
| 625 | 625 | 'desc' => EEH_Template::pretty_status( | 
| 626 | 626 | EEM_Transaction::abandoned_status_code, | 
| 627 | 627 | false, | 
| @@ -629,7 +629,7 @@ discard block | ||
| 629 | 629 | ), | 
| 630 | 630 | ), | 
| 631 | 631 | 'failed' => array( | 
| 632 | - 'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code, | |
| 632 | + 'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::failed_status_code, | |
| 633 | 633 | 'desc' => EEH_Template::pretty_status( | 
| 634 | 634 | EEM_Transaction::failed_status_code, | 
| 635 | 635 | false, | 
| @@ -678,7 +678,7 @@ discard block | ||
| 678 | 678 | 'Click to Edit event', | 
| 679 | 679 | 'event_espresso' | 
| 680 | 680 | ) | 
| 681 | -                . '">' . $event->get('EVT_name') . '</a>', | |
| 681 | +                . '">'.$event->get('EVT_name').'</a>', | |
| 682 | 682 | '</h3>' | 
| 683 | 683 | ) | 
| 684 | 684 | : ''; | 
| @@ -712,7 +712,7 @@ discard block | ||
| 712 | 712 | |
| 713 | 713 | $this->_set_transaction_object(); | 
| 714 | 714 | |
| 715 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 715 | +        if ( ! $this->_transaction instanceof EE_Transaction) { | |
| 716 | 716 | return; | 
| 717 | 717 | } | 
| 718 | 718 | $primary_registration = $this->_transaction->primary_registration(); | 
| @@ -726,9 +726,9 @@ discard block | ||
| 726 | 726 |          $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp'); | 
| 727 | 727 |          $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso'); | 
| 728 | 728 | |
| 729 | -        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ]; | |
| 729 | +        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->get('STS_ID')]; | |
| 730 | 730 |          $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso'); | 
| 731 | -        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID'); | |
| 731 | +        $this->_template_args['txn_status']['class'] = 'status-'.$this->_transaction->get('STS_ID'); | |
| 732 | 732 | |
| 733 | 733 |          $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total'); | 
| 734 | 734 |          $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid'); | 
| @@ -846,7 +846,7 @@ discard block | ||
| 846 | 846 | // grab messages at the last second | 
| 847 | 847 | $this->_template_args['notices'] = EE_Error::get_notices(); | 
| 848 | 848 | // path to template | 
| 849 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php'; | |
| 849 | + $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_header.template.php'; | |
| 850 | 850 | $this->_template_args['admin_page_header'] = EEH_Template::display_template( | 
| 851 | 851 | $template_path, | 
| 852 | 852 | $this->_template_args, | 
| @@ -875,7 +875,7 @@ discard block | ||
| 875 | 875 | |
| 876 | 876 | $this->_set_transaction_object(); | 
| 877 | 877 | |
| 878 | -        if (! $this->_transaction instanceof EE_Transaction) { | |
| 878 | +        if ( ! $this->_transaction instanceof EE_Transaction) { | |
| 879 | 879 | return; | 
| 880 | 880 | } | 
| 881 | 881 | add_meta_box( | 
| @@ -930,7 +930,7 @@ discard block | ||
| 930 | 930 |      { | 
| 931 | 931 | $content = ''; | 
| 932 | 932 | $actions = array(); | 
| 933 | -        if (! $transaction instanceof EE_Transaction) { | |
| 933 | +        if ( ! $transaction instanceof EE_Transaction) { | |
| 934 | 934 | return $content; | 
| 935 | 935 | } | 
| 936 | 936 | /** @var EE_Registration $primary_registration */ | 
| @@ -991,7 +991,7 @@ discard block | ||
| 991 | 991 | ); | 
| 992 | 992 |          if ($actions) { | 
| 993 | 993 | $content = '<ul>'; | 
| 994 | -            $content .= '<li>' . implode('</li><li>', $actions) . '</li>'; | |
| 994 | +            $content .= '<li>'.implode('</li><li>', $actions).'</li>'; | |
| 995 | 995 | $content .= '</uL>'; | 
| 996 | 996 | } | 
| 997 | 997 | return $content; | 
| @@ -1056,7 +1056,7 @@ discard block | ||
| 1056 | 1056 | |
| 1057 | 1057 | // process payment details | 
| 1058 | 1058 |          $payments = $this->_transaction->get_many_related('Payment'); | 
| 1059 | -        if (! empty($payments)) { | |
| 1059 | +        if ( ! empty($payments)) { | |
| 1060 | 1060 | $this->_template_args['payments'] = $payments; | 
| 1061 | 1061 | $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments); | 
| 1062 | 1062 |          } else { | 
| @@ -1117,7 +1117,7 @@ discard block | ||
| 1117 | 1117 |                                    esc_html__('%1$s : Initiated %2$s', 'event_espresso'), | 
| 1118 | 1118 |                                    ucwords(str_replace('_', ' ', $reg_step)), | 
| 1119 | 1119 | date( | 
| 1120 | -                                      get_option('date_format') . ' ' . get_option('time_format'), | |
| 1120 | +                                      get_option('date_format').' '.get_option('time_format'), | |
| 1121 | 1121 |                                        ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)) | 
| 1122 | 1122 | ) | 
| 1123 | 1123 | ) | 
| @@ -1170,7 +1170,7 @@ discard block | ||
| 1170 | 1170 | |
| 1171 | 1171 | // 'espresso_delete_payment_nonce' | 
| 1172 | 1172 | |
| 1173 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php'; | |
| 1173 | + $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_txn_details.template.php'; | |
| 1174 | 1174 | echo EEH_Template::display_template($template_path, $this->_template_args, true); | 
| 1175 | 1175 | } | 
| 1176 | 1176 | |
| @@ -1202,18 +1202,18 @@ discard block | ||
| 1202 | 1202 | ), | 
| 1203 | 1203 | ) | 
| 1204 | 1204 | ); | 
| 1205 | -        if (! empty($reg_payments)) { | |
| 1205 | +        if ( ! empty($reg_payments)) { | |
| 1206 | 1206 |              foreach ($payments as $payment) { | 
| 1207 | -                if (! $payment instanceof EE_Payment) { | |
| 1207 | +                if ( ! $payment instanceof EE_Payment) { | |
| 1208 | 1208 | continue; | 
| 1209 | -                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) { | |
| 1210 | - $existing_reg_payments[ $payment->ID() ] = array(); | |
| 1209 | +                } elseif ( ! isset($existing_reg_payments[$payment->ID()])) { | |
| 1210 | + $existing_reg_payments[$payment->ID()] = array(); | |
| 1211 | 1211 | } | 
| 1212 | 1212 |                  foreach ($reg_payments as $reg_payment) { | 
| 1213 | 1213 | if ($reg_payment instanceof EE_Registration_Payment | 
| 1214 | 1214 | && $reg_payment->payment_ID() === $payment->ID() | 
| 1215 | 1215 |                      ) { | 
| 1216 | - $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID(); | |
| 1216 | + $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID(); | |
| 1217 | 1217 | } | 
| 1218 | 1218 | } | 
| 1219 | 1219 | } | 
| @@ -1254,16 +1254,16 @@ discard block | ||
| 1254 | 1254 | '', | 
| 1255 | 1255 | 'clear: both; margin: 1.5em 0 0; display: none;' | 
| 1256 | 1256 | ); | 
| 1257 | -        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap'); | |
| 1257 | +        $registrations_to_apply_payment_to .= EEH_HTML::br().EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap'); | |
| 1258 | 1258 |          $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl'); | 
| 1259 | 1259 | $registrations_to_apply_payment_to .= EEH_HTML::thead( | 
| 1260 | 1260 | EEH_HTML::tr( | 
| 1261 | -                EEH_HTML::th(esc_html__('ID', 'event_espresso')) . | |
| 1262 | -                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) . | |
| 1263 | -                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) . | |
| 1264 | -                EEH_HTML::th(esc_html__('Event', 'event_espresso')) . | |
| 1265 | -                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1266 | -                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1261 | +                EEH_HTML::th(esc_html__('ID', 'event_espresso')). | |
| 1262 | +                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')). | |
| 1263 | +                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')). | |
| 1264 | +                EEH_HTML::th(esc_html__('Event', 'event_espresso')). | |
| 1265 | +                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr'). | |
| 1266 | +                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr'). | |
| 1267 | 1267 |                  EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr') | 
| 1268 | 1268 | ) | 
| 1269 | 1269 | ); | 
| @@ -1278,29 +1278,29 @@ discard block | ||
| 1278 | 1278 |                      : esc_html__('Unknown Attendee', 'event_espresso'); | 
| 1279 | 1279 | $owing = $registration->final_price() - $registration->paid(); | 
| 1280 | 1280 | $taxable = $registration->ticket()->taxable() | 
| 1281 | -                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>' | |
| 1281 | +                    ? ' <span class="smaller-text lt-grey-text"> '.esc_html__('+ tax', 'event_espresso').'</span>' | |
| 1282 | 1282 | : ''; | 
| 1283 | 1283 | $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments) | 
| 1284 | 1284 | ? ' checked="checked"' | 
| 1285 | 1285 | : ''; | 
| 1286 | 1286 | $disabled = $registration->final_price() > 0 ? '' : ' disabled'; | 
| 1287 | 1287 | $registrations_to_apply_payment_to .= EEH_HTML::tr( | 
| 1288 | - EEH_HTML::td($registration->ID()) . | |
| 1289 | - EEH_HTML::td($attendee_name) . | |
| 1288 | + EEH_HTML::td($registration->ID()). | |
| 1289 | + EEH_HTML::td($attendee_name). | |
| 1290 | 1290 | EEH_HTML::td( | 
| 1291 | - $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable | |
| 1292 | - ) . | |
| 1293 | - EEH_HTML::td($registration->event_name()) . | |
| 1294 | - EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') . | |
| 1295 | - EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') . | |
| 1291 | + $registration->ticket()->name().' : '.$registration->ticket()->pretty_price().$taxable | |
| 1292 | + ). | |
| 1293 | + EEH_HTML::td($registration->event_name()). | |
| 1294 | + EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr'). | |
| 1295 | + EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr'). | |
| 1296 | 1296 | EEH_HTML::td( | 
| 1297 | - '<input type="checkbox" value="' . $registration->ID() | |
| 1297 | + '<input type="checkbox" value="'.$registration->ID() | |
| 1298 | 1298 | . '" name="txn_admin_payment[registrations]"' | 
| 1299 | - . $checked . $disabled . '>', | |
| 1299 | + . $checked.$disabled.'>', | |
| 1300 | 1300 | '', | 
| 1301 | 1301 | 'jst-cntr' | 
| 1302 | 1302 | ), | 
| 1303 | - 'apply-payment-registration-row-' . $registration->ID() | |
| 1303 | + 'apply-payment-registration-row-'.$registration->ID() | |
| 1304 | 1304 | ); | 
| 1305 | 1305 | } | 
| 1306 | 1306 | } | 
| @@ -1381,12 +1381,12 @@ discard block | ||
| 1381 | 1381 | array( | 
| 1382 | 1382 | 'OR*payment_method_for_payment' => array( | 
| 1383 | 1383 |                          'PMD_ID'    => array('IN', $payment_methods_of_payments), | 
| 1384 | -                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'), | |
| 1384 | +                        'PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%'), | |
| 1385 | 1385 | ), | 
| 1386 | 1386 | ), | 
| 1387 | 1387 | ); | 
| 1388 | 1388 |          } else { | 
| 1389 | -            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'))); | |
| 1389 | +            $query_args = array(array('PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%'))); | |
| 1390 | 1390 | } | 
| 1391 | 1391 | $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args); | 
| 1392 | 1392 | } | 
| @@ -1415,7 +1415,7 @@ discard block | ||
| 1415 | 1415 | 'Line_Item', | 
| 1416 | 1416 |              array(array('LIN_type' => 'line-item')) | 
| 1417 | 1417 | ); | 
| 1418 | -        if (! empty($line_items)) { | |
| 1418 | +        if ( ! empty($line_items)) { | |
| 1419 | 1419 |              foreach ($line_items as $item) { | 
| 1420 | 1420 |                  if ($item instanceof EE_Line_Item) { | 
| 1421 | 1421 |                      switch ($item->OBJ_type()) { | 
| @@ -1425,7 +1425,7 @@ discard block | ||
| 1425 | 1425 | $ticket = $item->ticket(); | 
| 1426 | 1426 | // right now we're only handling tickets here. | 
| 1427 | 1427 | // Cause its expected that only tickets will have attendees right? | 
| 1428 | -                            if (! $ticket instanceof EE_Ticket) { | |
| 1428 | +                            if ( ! $ticket instanceof EE_Ticket) { | |
| 1429 | 1429 | break; | 
| 1430 | 1430 | } | 
| 1431 | 1431 |                              try { | 
| @@ -1434,7 +1434,7 @@ discard block | ||
| 1434 | 1434 | EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__); | 
| 1435 | 1435 |                                  $event_name = esc_html__('Unknown Event', 'event_espresso'); | 
| 1436 | 1436 | } | 
| 1437 | -                            $event_name .= ' - ' . $item->get('LIN_name'); | |
| 1437 | +                            $event_name .= ' - '.$item->get('LIN_name'); | |
| 1438 | 1438 |                              $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price')); | 
| 1439 | 1439 | // now get all of the registrations for this transaction that use this ticket | 
| 1440 | 1440 | $registrations = $ticket->get_many_related( | 
| @@ -1442,38 +1442,38 @@ discard block | ||
| 1442 | 1442 |                                  array(array('TXN_ID' => $this->_transaction->ID())) | 
| 1443 | 1443 | ); | 
| 1444 | 1444 |                              foreach ($registrations as $registration) { | 
| 1445 | -                                if (! $registration instanceof EE_Registration) { | |
| 1445 | +                                if ( ! $registration instanceof EE_Registration) { | |
| 1446 | 1446 | break; | 
| 1447 | 1447 | } | 
| 1448 | - $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID'] | |
| 1448 | + $this->_template_args['event_attendees'][$registration->ID()]['STS_ID'] | |
| 1449 | 1449 | = $registration->status_ID(); | 
| 1450 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_num'] | |
| 1450 | + $this->_template_args['event_attendees'][$registration->ID()]['att_num'] | |
| 1451 | 1451 | = $registration->count(); | 
| 1452 | - $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name'] | |
| 1452 | + $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name'] | |
| 1453 | 1453 | = $event_name; | 
| 1454 | - $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price'] | |
| 1454 | + $this->_template_args['event_attendees'][$registration->ID()]['ticket_price'] | |
| 1455 | 1455 | = $ticket_price; | 
| 1456 | 1456 | // attendee info | 
| 1457 | 1457 |                                  $attendee = $registration->get_first_related('Attendee'); | 
| 1458 | 1458 |                                  if ($attendee instanceof EE_Attendee) { | 
| 1459 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] | |
| 1459 | + $this->_template_args['event_attendees'][$registration->ID()]['att_id'] | |
| 1460 | 1460 | = $attendee->ID(); | 
| 1461 | - $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] | |
| 1461 | + $this->_template_args['event_attendees'][$registration->ID()]['attendee'] | |
| 1462 | 1462 | = $attendee->full_name(); | 
| 1463 | - $this->_template_args['event_attendees'][ $registration->ID() ]['email'] | |
| 1464 | - = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name | |
| 1463 | + $this->_template_args['event_attendees'][$registration->ID()]['email'] | |
| 1464 | + = '<a href="mailto:'.$attendee->email().'?subject='.$event_name | |
| 1465 | 1465 | . esc_html__( | 
| 1466 | 1466 | ' Event', | 
| 1467 | 1467 | 'event_espresso' | 
| 1468 | 1468 | ) | 
| 1469 | - . '">' . $attendee->email() . '</a>'; | |
| 1470 | - $this->_template_args['event_attendees'][ $registration->ID() ]['address'] | |
| 1469 | + . '">'.$attendee->email().'</a>'; | |
| 1470 | + $this->_template_args['event_attendees'][$registration->ID()]['address'] | |
| 1471 | 1471 | = EEH_Address::format($attendee, 'inline', false, false); | 
| 1472 | 1472 |                                  } else { | 
| 1473 | - $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = ''; | |
| 1474 | - $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = ''; | |
| 1475 | - $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = ''; | |
| 1476 | - $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = ''; | |
| 1473 | + $this->_template_args['event_attendees'][$registration->ID()]['att_id'] = ''; | |
| 1474 | + $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = ''; | |
| 1475 | + $this->_template_args['event_attendees'][$registration->ID()]['email'] = ''; | |
| 1476 | + $this->_template_args['event_attendees'][$registration->ID()]['address'] = ''; | |
| 1477 | 1477 | } | 
| 1478 | 1478 | } | 
| 1479 | 1479 | break; | 
| @@ -1489,7 +1489,7 @@ discard block | ||
| 1489 | 1489 | TXN_ADMIN_URL | 
| 1490 | 1490 | ); | 
| 1491 | 1491 | echo EEH_Template::display_template( | 
| 1492 | - TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php', | |
| 1492 | + TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_attendees.template.php', | |
| 1493 | 1493 | $this->_template_args, | 
| 1494 | 1494 | true | 
| 1495 | 1495 | ); | 
| @@ -1524,7 +1524,7 @@ discard block | ||
| 1524 | 1524 | $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration | 
| 1525 | 1525 |              ? $this->_transaction->primary_registration()->get_first_related('Attendee') | 
| 1526 | 1526 | : null; | 
| 1527 | -        if (! $primary_att instanceof EE_Attendee) { | |
| 1527 | +        if ( ! $primary_att instanceof EE_Attendee) { | |
| 1528 | 1528 | $this->_template_args['no_attendee_message'] = esc_html__( | 
| 1529 | 1529 | 'There is no attached contact for this transaction. The transaction either failed due to an error or was abandoned.', | 
| 1530 | 1530 | 'event_espresso' | 
| @@ -1546,7 +1546,7 @@ discard block | ||
| 1546 | 1546 | // get formatted address for registrant | 
| 1547 | 1547 | $this->_template_args['formatted_address'] = EEH_Address::format($primary_att); | 
| 1548 | 1548 | echo EEH_Template::display_template( | 
| 1549 | - TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php', | |
| 1549 | + TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_registrant.template.php', | |
| 1550 | 1550 | $this->_template_args, | 
| 1551 | 1551 | true | 
| 1552 | 1552 | ); | 
| @@ -1571,8 +1571,8 @@ discard block | ||
| 1571 | 1571 | TXN_ADMIN_URL | 
| 1572 | 1572 | ); | 
| 1573 | 1573 | |
| 1574 | - $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php'; | |
| 1575 | - echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/ | |
| 1574 | + $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_billing_info.template.php'; | |
| 1575 | + echo EEH_Template::display_template($template_path, $this->_template_args, true); /**/ | |
| 1576 | 1576 | } | 
| 1577 | 1577 | |
| 1578 | 1578 | |
| @@ -1597,7 +1597,7 @@ discard block | ||
| 1597 | 1597 | 'ee_edit_payments', | 
| 1598 | 1598 | 'apply_payment_or_refund_from_registration_details' | 
| 1599 | 1599 | ); | 
| 1600 | -        if (! empty($valid_data) && $has_access) { | |
| 1600 | +        if ( ! empty($valid_data) && $has_access) { | |
| 1601 | 1601 | $PAY_ID = $valid_data['PAY_ID']; | 
| 1602 | 1602 | // save the new payment | 
| 1603 | 1603 | $payment = $this->_create_payment_from_request_data($valid_data); | 
| @@ -1610,7 +1610,7 @@ discard block | ||
| 1610 | 1610 | $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment); | 
| 1611 | 1611 | $this->_remove_existing_registration_payments($payment, $PAY_ID); | 
| 1612 | 1612 | // apply payment to registrations (if applicable) | 
| 1613 | -                if (! empty($REG_IDs)) { | |
| 1613 | +                if ( ! empty($REG_IDs)) { | |
| 1614 | 1614 | $this->_update_registration_payments($transaction, $payment, $REG_IDs); | 
| 1615 | 1615 | $this->_maybe_send_notifications(); | 
| 1616 | 1616 | // now process status changes for the same registrations | 
| @@ -1680,14 +1680,14 @@ discard block | ||
| 1680 | 1680 | */ | 
| 1681 | 1681 | protected function _validate_payment_request_data() | 
| 1682 | 1682 |      { | 
| 1683 | -        if (! isset($this->_req_data['txn_admin_payment'])) { | |
| 1683 | +        if ( ! isset($this->_req_data['txn_admin_payment'])) { | |
| 1684 | 1684 | return false; | 
| 1685 | 1685 | } | 
| 1686 | 1686 | $payment_form = $this->_generate_payment_form_section(); | 
| 1687 | 1687 |          try { | 
| 1688 | 1688 |              if ($payment_form->was_submitted()) { | 
| 1689 | 1689 | $payment_form->receive_form_submission(); | 
| 1690 | -                if (! $payment_form->is_valid()) { | |
| 1690 | +                if ( ! $payment_form->is_valid()) { | |
| 1691 | 1691 | $submission_error_messages = array(); | 
| 1692 | 1692 |                      foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) { | 
| 1693 | 1693 |                          if ($validation_error instanceof EE_Validation_Error) { | 
| @@ -1866,7 +1866,7 @@ discard block | ||
| 1866 | 1866 |              array('Y-m-d', 'g:i a') | 
| 1867 | 1867 | ); | 
| 1868 | 1868 | |
| 1869 | -        if (! $payment->save()) { | |
| 1869 | +        if ( ! $payment->save()) { | |
| 1870 | 1870 | EE_Error::add_error( | 
| 1871 | 1871 | sprintf( | 
| 1872 | 1872 |                      esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'), | 
| @@ -2063,12 +2063,12 @@ discard block | ||
| 2063 | 2063 | // but add in some conditions regarding payment, | 
| 2064 | 2064 | // so that we don't apply payments to registrations that are free or have already been paid for | 
| 2065 | 2065 | // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative ) | 
| 2066 | -        if (! $payment->is_a_refund()) { | |
| 2066 | +        if ( ! $payment->is_a_refund()) { | |
| 2067 | 2067 |              $registration_query_where_params['REG_final_price'] = array('!=', 0); | 
| 2068 | 2068 |              $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true); | 
| 2069 | 2069 | } | 
| 2070 | 2070 | $registrations = $transaction->registrations(array($registration_query_where_params)); | 
| 2071 | -        if (! empty($registrations)) { | |
| 2071 | +        if ( ! empty($registrations)) { | |
| 2072 | 2072 | /** @type EE_Payment_Processor $payment_processor */ | 
| 2073 | 2073 |              $payment_processor = EE_Registry::instance()->load_core('Payment_Processor'); | 
| 2074 | 2074 | $payment_processor->process_registration_payments($transaction, $payment, $registrations); | 
| @@ -2093,7 +2093,7 @@ discard block | ||
| 2093 | 2093 | protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array()) | 
| 2094 | 2094 |      { | 
| 2095 | 2095 | // first if there is no change in status then we get out. | 
| 2096 | - if (! isset($this->_req_data['txn_reg_status_change']['reg_status']) | |
| 2096 | + if ( ! isset($this->_req_data['txn_reg_status_change']['reg_status']) | |
| 2097 | 2097 | || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN' | 
| 2098 | 2098 |          ) { | 
| 2099 | 2099 | // no error message, no change requested, just nothing to do man. | 
| @@ -2151,7 +2151,7 @@ discard block | ||
| 2151 | 2151 | 'pay_status' => $payment->STS_ID(), | 
| 2152 | 2152 | 'PAY_ID' => $payment->ID(), | 
| 2153 | 2153 | 'STS_ID' => $payment->STS_ID(), | 
| 2154 | - 'status' => self::$_pay_status[ $payment->STS_ID() ], | |
| 2154 | + 'status' => self::$_pay_status[$payment->STS_ID()], | |
| 2155 | 2155 |                  'date'             => $payment->timestamp('Y-m-d', 'h:i a'), | 
| 2156 | 2156 | 'method' => strtoupper($payment->source()), | 
| 2157 | 2157 | 'PM_ID' => $payment->payment_method() ? $payment->payment_method()->ID() : 1, | 
| @@ -2273,11 +2273,11 @@ discard block | ||
| 2273 | 2273 |      { | 
| 2274 | 2274 | $registration_payment_data = array(); | 
| 2275 | 2275 | // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows. | 
| 2276 | -        if (! empty($REG_IDs)) { | |
| 2276 | +        if ( ! empty($REG_IDs)) { | |
| 2277 | 2277 |              $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs)))); | 
| 2278 | 2278 |              foreach ($registrations as $registration) { | 
| 2279 | 2279 |                  if ($registration instanceof EE_Registration) { | 
| 2280 | - $registration_payment_data[ $registration->ID() ] = array( | |
| 2280 | + $registration_payment_data[$registration->ID()] = array( | |
| 2281 | 2281 | 'paid' => $registration->pretty_paid(), | 
| 2282 | 2282 | 'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()), | 
| 2283 | 2283 | ); | 
| @@ -2389,8 +2389,8 @@ discard block | ||
| 2389 | 2389 |              : date('m/d/Y'); | 
| 2390 | 2390 | |
| 2391 | 2391 | // make sure our timestamps start and end right at the boundaries for each day | 
| 2392 | -        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00'; | |
| 2393 | -        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59'; | |
| 2392 | +        $start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00'; | |
| 2393 | +        $end_date = date('Y-m-d', strtotime($end_date)).' 23:59:59'; | |
| 2394 | 2394 | |
| 2395 | 2395 | |
| 2396 | 2396 | // convert to timestamps | 
| @@ -2449,7 +2449,7 @@ discard block | ||
| 2449 | 2449 | } | 
| 2450 | 2450 | |
| 2451 | 2451 |          if (isset($this->_req_data['s'])) { | 
| 2452 | - $search_string = '%' . $this->_req_data['s'] . '%'; | |
| 2452 | + $search_string = '%'.$this->_req_data['s'].'%'; | |
| 2453 | 2453 | $_where['OR'] = array( | 
| 2454 | 2454 |                  'Registration.Event.EVT_name'         => array('LIKE', $search_string), | 
| 2455 | 2455 |                  'Registration.Event.EVT_desc'         => array('LIKE', $search_string), | 
| @@ -2476,11 +2476,11 @@ discard block | ||
| 2476 | 2476 | } | 
| 2477 | 2477 | |
| 2478 | 2478 | // failed transactions | 
| 2479 | - $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count) | |
| 2479 | + $failed = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count) | |
| 2480 | 2480 | || ($count && $view === 'failed'); | 
| 2481 | - $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count) | |
| 2481 | + $abandoned = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count) | |
| 2482 | 2482 | || ($count && $view === 'abandoned'); | 
| 2483 | - $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count) | |
| 2483 | + $incomplete = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count) | |
| 2484 | 2484 | || ($count && $view === 'incomplete'); | 
| 2485 | 2485 | |
| 2486 | 2486 |          if ($failed) { | 
| @@ -9,261 +9,261 @@ | ||
| 9 | 9 | */ | 
| 10 | 10 | class EE_HABTM_Relation extends EE_Model_Relation_Base | 
| 11 | 11 |  { | 
| 12 | - /** | |
| 13 | - * Model which defines the relation between two other models. Eg, the EE_Event_Question_Group model, | |
| 14 | - * which joins EE_Event and EE_Question_Group | |
| 15 | - * | |
| 16 | - * @var EEM_Base | |
| 17 | - */ | |
| 18 | - protected $_joining_model_name; | |
| 12 | + /** | |
| 13 | + * Model which defines the relation between two other models. Eg, the EE_Event_Question_Group model, | |
| 14 | + * which joins EE_Event and EE_Question_Group | |
| 15 | + * | |
| 16 | + * @var EEM_Base | |
| 17 | + */ | |
| 18 | + protected $_joining_model_name; | |
| 19 | 19 | |
| 20 | - protected $_model_relation_chain_to_join_model; | |
| 20 | + protected $_model_relation_chain_to_join_model; | |
| 21 | 21 | |
| 22 | 22 | |
| 23 | - /** | |
| 24 | - * Object representing the relationship between two models. HasAndBelongsToMany relations always use a join-table | |
| 25 | - * (and an ee joining-model.) This knows how to join the models, | |
| 26 | - * get related models across the relation, and add-and-remove the relationships. | |
| 27 | - * | |
| 28 | - * @param bool $joining_model_name | |
| 29 | - * @param boolean $block_deletes for this type of relation, we block by default for now. if there | |
| 30 | - * are related models across this relation, block (prevent and add an | |
| 31 | - * error) the deletion of this model | |
| 32 | - * @param string $blocking_delete_error_message a customized error message on blocking deletes instead of the | |
| 33 | - * default | |
| 34 | - */ | |
| 35 | - public function __construct($joining_model_name, $block_deletes = true, $blocking_delete_error_message = '') | |
| 36 | -    { | |
| 37 | - $this->_joining_model_name = $joining_model_name; | |
| 38 | - parent::__construct($block_deletes, $blocking_delete_error_message); | |
| 39 | - } | |
| 23 | + /** | |
| 24 | + * Object representing the relationship between two models. HasAndBelongsToMany relations always use a join-table | |
| 25 | + * (and an ee joining-model.) This knows how to join the models, | |
| 26 | + * get related models across the relation, and add-and-remove the relationships. | |
| 27 | + * | |
| 28 | + * @param bool $joining_model_name | |
| 29 | + * @param boolean $block_deletes for this type of relation, we block by default for now. if there | |
| 30 | + * are related models across this relation, block (prevent and add an | |
| 31 | + * error) the deletion of this model | |
| 32 | + * @param string $blocking_delete_error_message a customized error message on blocking deletes instead of the | |
| 33 | + * default | |
| 34 | + */ | |
| 35 | + public function __construct($joining_model_name, $block_deletes = true, $blocking_delete_error_message = '') | |
| 36 | +	{ | |
| 37 | + $this->_joining_model_name = $joining_model_name; | |
| 38 | + parent::__construct($block_deletes, $blocking_delete_error_message); | |
| 39 | + } | |
| 40 | 40 | |
| 41 | - /** | |
| 42 | - * Gets the joining model's object | |
| 43 | - * | |
| 44 | - * @return EEM_Base | |
| 45 | - */ | |
| 46 | - public function get_join_model() | |
| 47 | -    { | |
| 48 | - return $this->_get_model($this->_joining_model_name); | |
| 49 | - } | |
| 41 | + /** | |
| 42 | + * Gets the joining model's object | |
| 43 | + * | |
| 44 | + * @return EEM_Base | |
| 45 | + */ | |
| 46 | + public function get_join_model() | |
| 47 | +	{ | |
| 48 | + return $this->_get_model($this->_joining_model_name); | |
| 49 | + } | |
| 50 | 50 | |
| 51 | 51 | |
| 52 | - /** | |
| 53 | - * Gets the SQL string for joining the main model's table containing the pk to the join table. Eg "LEFT JOIN | |
| 54 | - * real_join_table AS join_table_alias ON this_table_alias.pk = join_table_alias.fk_to_this_table" | |
| 55 | - * | |
| 56 | - * @param string $model_relation_chain like 'Event.Event_Venue.Venue' | |
| 57 | - * @return string of SQL | |
| 58 | - * @throws \EE_Error | |
| 59 | - */ | |
| 60 | - public function get_join_to_intermediate_model_statement($model_relation_chain) | |
| 61 | -    { | |
| 62 | - // create sql like | |
| 63 | - // LEFT JOIN join_table AS join_table_alias ON this_table_alias.this_table_pk = join_table_alias.join_table_fk_to_this | |
| 64 | - // LEFT JOIN other_table AS other_table_alias ON join_table_alias.join_table_fk_to_other = other_table_alias.other_table_pk | |
| 65 | - // remember the model relation chain to the JOIN model, because we'll | |
| 66 | - // need it for get_join_statement() | |
| 67 | - $this->_model_relation_chain_to_join_model = $model_relation_chain; | |
| 68 | - $this_table_pk_field = $this->get_this_model()->get_primary_key_field();// get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 69 | - $join_table_fk_field_to_this_table = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 70 | - $this_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 71 | - $model_relation_chain, | |
| 72 | - $this->get_this_model()->get_this_model_name() | |
| 73 | - ) . $this_table_pk_field->get_table_alias(); | |
| 52 | + /** | |
| 53 | + * Gets the SQL string for joining the main model's table containing the pk to the join table. Eg "LEFT JOIN | |
| 54 | + * real_join_table AS join_table_alias ON this_table_alias.pk = join_table_alias.fk_to_this_table" | |
| 55 | + * | |
| 56 | + * @param string $model_relation_chain like 'Event.Event_Venue.Venue' | |
| 57 | + * @return string of SQL | |
| 58 | + * @throws \EE_Error | |
| 59 | + */ | |
| 60 | + public function get_join_to_intermediate_model_statement($model_relation_chain) | |
| 61 | +	{ | |
| 62 | + // create sql like | |
| 63 | + // LEFT JOIN join_table AS join_table_alias ON this_table_alias.this_table_pk = join_table_alias.join_table_fk_to_this | |
| 64 | + // LEFT JOIN other_table AS other_table_alias ON join_table_alias.join_table_fk_to_other = other_table_alias.other_table_pk | |
| 65 | + // remember the model relation chain to the JOIN model, because we'll | |
| 66 | + // need it for get_join_statement() | |
| 67 | + $this->_model_relation_chain_to_join_model = $model_relation_chain; | |
| 68 | + $this_table_pk_field = $this->get_this_model()->get_primary_key_field();// get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 69 | + $join_table_fk_field_to_this_table = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 70 | + $this_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 71 | + $model_relation_chain, | |
| 72 | + $this->get_this_model()->get_this_model_name() | |
| 73 | + ) . $this_table_pk_field->get_table_alias(); | |
| 74 | 74 | |
| 75 | - $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 76 | - $model_relation_chain, | |
| 77 | - $this->get_join_model()->get_this_model_name() | |
| 78 | - ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 79 | - $join_table = $this->get_join_model()->get_table_for_alias($join_table_alias); | |
| 80 | - // phew! ok, we have all the info we need, now we can create the SQL join string | |
| 81 | - $SQL = $this->_left_join( | |
| 82 | - $join_table, | |
| 83 | - $join_table_alias, | |
| 84 | - $join_table_fk_field_to_this_table->get_table_column(), | |
| 85 | - $this_table_alias, | |
| 86 | - $this_table_pk_field->get_table_column() | |
| 87 | - ) . $this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias); | |
| 75 | + $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 76 | + $model_relation_chain, | |
| 77 | + $this->get_join_model()->get_this_model_name() | |
| 78 | + ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 79 | + $join_table = $this->get_join_model()->get_table_for_alias($join_table_alias); | |
| 80 | + // phew! ok, we have all the info we need, now we can create the SQL join string | |
| 81 | + $SQL = $this->_left_join( | |
| 82 | + $join_table, | |
| 83 | + $join_table_alias, | |
| 84 | + $join_table_fk_field_to_this_table->get_table_column(), | |
| 85 | + $this_table_alias, | |
| 86 | + $this_table_pk_field->get_table_column() | |
| 87 | + ) . $this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias); | |
| 88 | 88 | |
| 89 | - return $SQL; | |
| 90 | - } | |
| 89 | + return $SQL; | |
| 90 | + } | |
| 91 | 91 | |
| 92 | 92 | |
| 93 | - /** | |
| 94 | - * Gets the SQL string for joining the join table to the other model's pk's table. Eg "LEFT JOIN real_other_table | |
| 95 | - * AS other_table_alias ON join_table_alias.fk_to_other_table = other_table_alias.pk" If you want to join between | |
| 96 | - * modelA -> joinModelAB -> modelB (eg, Event -> Event_Question_Group -> Question_Group), you should prepend the | |
| 97 | - * result of this function with results from get_join_to_intermediate_model_statement(), so that you join first to | |
| 98 | - * the intermediate join table, and then to the other model's pk's table | |
| 99 | - * | |
| 100 | - * @param string $model_relation_chain like 'Event.Event_Venue.Venue' | |
| 101 | - * @return string of SQL | |
| 102 | - * @throws \EE_Error | |
| 103 | - */ | |
| 104 | - public function get_join_statement($model_relation_chain) | |
| 105 | -    { | |
| 106 | -        if ($this->_model_relation_chain_to_join_model === null) { | |
| 107 | - throw new EE_Error(sprintf(__( | |
| 108 | - 'When using EE_HABTM_Relation to create a join, you must call get_join_to_intermediate_model_statement BEFORE get_join_statement', | |
| 109 | - 'event_espresso' | |
| 110 | - ))); | |
| 111 | - } | |
| 112 | - $join_table_fk_field_to_this_table = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 113 | - $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 114 | - $this->_model_relation_chain_to_join_model, | |
| 115 | - $this->get_join_model()->get_this_model_name() | |
| 116 | - ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 117 | - $other_table_pk_field = $this->get_other_model()->get_primary_key_field(); | |
| 118 | - $join_table_fk_field_to_other_table = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 119 | - $other_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 120 | - $model_relation_chain, | |
| 121 | - $this->get_other_model()->get_this_model_name() | |
| 122 | - ) . $other_table_pk_field->get_table_alias(); | |
| 123 | - $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias); | |
| 93 | + /** | |
| 94 | + * Gets the SQL string for joining the join table to the other model's pk's table. Eg "LEFT JOIN real_other_table | |
| 95 | + * AS other_table_alias ON join_table_alias.fk_to_other_table = other_table_alias.pk" If you want to join between | |
| 96 | + * modelA -> joinModelAB -> modelB (eg, Event -> Event_Question_Group -> Question_Group), you should prepend the | |
| 97 | + * result of this function with results from get_join_to_intermediate_model_statement(), so that you join first to | |
| 98 | + * the intermediate join table, and then to the other model's pk's table | |
| 99 | + * | |
| 100 | + * @param string $model_relation_chain like 'Event.Event_Venue.Venue' | |
| 101 | + * @return string of SQL | |
| 102 | + * @throws \EE_Error | |
| 103 | + */ | |
| 104 | + public function get_join_statement($model_relation_chain) | |
| 105 | +	{ | |
| 106 | +		if ($this->_model_relation_chain_to_join_model === null) { | |
| 107 | + throw new EE_Error(sprintf(__( | |
| 108 | + 'When using EE_HABTM_Relation to create a join, you must call get_join_to_intermediate_model_statement BEFORE get_join_statement', | |
| 109 | + 'event_espresso' | |
| 110 | + ))); | |
| 111 | + } | |
| 112 | + $join_table_fk_field_to_this_table = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 113 | + $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 114 | + $this->_model_relation_chain_to_join_model, | |
| 115 | + $this->get_join_model()->get_this_model_name() | |
| 116 | + ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 117 | + $other_table_pk_field = $this->get_other_model()->get_primary_key_field(); | |
| 118 | + $join_table_fk_field_to_other_table = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 119 | + $other_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | |
| 120 | + $model_relation_chain, | |
| 121 | + $this->get_other_model()->get_this_model_name() | |
| 122 | + ) . $other_table_pk_field->get_table_alias(); | |
| 123 | + $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias); | |
| 124 | 124 | |
| 125 | - $SQL = $this->_left_join( | |
| 126 | - $other_table, | |
| 127 | - $other_table_alias, | |
| 128 | - $other_table_pk_field->get_table_column(), | |
| 129 | - $join_table_alias, | |
| 130 | - $join_table_fk_field_to_other_table->get_table_column() | |
| 131 | - ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias); | |
| 132 | - return $SQL; | |
| 133 | - } | |
| 125 | + $SQL = $this->_left_join( | |
| 126 | + $other_table, | |
| 127 | + $other_table_alias, | |
| 128 | + $other_table_pk_field->get_table_column(), | |
| 129 | + $join_table_alias, | |
| 130 | + $join_table_fk_field_to_other_table->get_table_column() | |
| 131 | + ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias); | |
| 132 | + return $SQL; | |
| 133 | + } | |
| 134 | 134 | |
| 135 | 135 | |
| 136 | - /** | |
| 137 | - * Ensures there is an entry in the join table between these two models. Feel free to do this manually if you like. | |
| 138 | - * If the join table has additional columns (eg, the Event_Question_Group table has a is_primary column), then | |
| 139 | - * you'll want to directly use the EEM_Event_Question_Group model to add the entry to the table and set those extra | |
| 140 | - * columns' values | |
| 141 | - * | |
| 142 | - * @param EE_Base_Class|int $this_obj_or_id | |
| 143 | - * @param EE_Base_Class|int $other_obj_or_id | |
| 144 | - * @param array $extra_join_model_fields_n_values col=>val pairs that are used as extra conditions for | |
| 145 | - * checking existing values and for setting new rows if | |
| 146 | - * no exact matches. | |
| 147 | - * @return EE_Base_Class | |
| 148 | - * @throws \EE_Error | |
| 149 | - */ | |
| 150 | - public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array()) | |
| 151 | -    { | |
| 152 | - $this_model_obj = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true); | |
| 153 | - $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true); | |
| 154 | - // check if such a relationship already exists | |
| 155 | - $join_model_fk_to_this_model = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 156 | - $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 136 | + /** | |
| 137 | + * Ensures there is an entry in the join table between these two models. Feel free to do this manually if you like. | |
| 138 | + * If the join table has additional columns (eg, the Event_Question_Group table has a is_primary column), then | |
| 139 | + * you'll want to directly use the EEM_Event_Question_Group model to add the entry to the table and set those extra | |
| 140 | + * columns' values | |
| 141 | + * | |
| 142 | + * @param EE_Base_Class|int $this_obj_or_id | |
| 143 | + * @param EE_Base_Class|int $other_obj_or_id | |
| 144 | + * @param array $extra_join_model_fields_n_values col=>val pairs that are used as extra conditions for | |
| 145 | + * checking existing values and for setting new rows if | |
| 146 | + * no exact matches. | |
| 147 | + * @return EE_Base_Class | |
| 148 | + * @throws \EE_Error | |
| 149 | + */ | |
| 150 | + public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array()) | |
| 151 | +	{ | |
| 152 | + $this_model_obj = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true); | |
| 153 | + $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true); | |
| 154 | + // check if such a relationship already exists | |
| 155 | + $join_model_fk_to_this_model = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 156 | + $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 157 | 157 | |
| 158 | - $foreign_keys = $all_fields = array( | |
| 159 | - $join_model_fk_to_this_model->get_name() => $this_model_obj->ID(), | |
| 160 | - $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(), | |
| 161 | - ); | |
| 158 | + $foreign_keys = $all_fields = array( | |
| 159 | + $join_model_fk_to_this_model->get_name() => $this_model_obj->ID(), | |
| 160 | + $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(), | |
| 161 | + ); | |
| 162 | 162 | |
| 163 | - // if $where_query exists lets add them to the query_params. | |
| 164 | -        if (! empty($extra_join_model_fields_n_values)) { | |
| 165 | - // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | |
| 166 | - // make sure we strip THIS models name from the query param | |
| 167 | - $parsed_query = array(); | |
| 168 | -            foreach ($extra_join_model_fields_n_values as $query_param => $val) { | |
| 169 | - $query_param = str_replace( | |
| 170 | - $this->get_join_model()->get_this_model_name() . ".", | |
| 171 | - "", | |
| 172 | - $query_param | |
| 173 | - ); | |
| 174 | - $parsed_query[ $query_param ] = $val; | |
| 175 | - } | |
| 176 | - $all_fields = array_merge($foreign_keys, $parsed_query); | |
| 177 | - } | |
| 163 | + // if $where_query exists lets add them to the query_params. | |
| 164 | +		if (! empty($extra_join_model_fields_n_values)) { | |
| 165 | + // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | |
| 166 | + // make sure we strip THIS models name from the query param | |
| 167 | + $parsed_query = array(); | |
| 168 | +			foreach ($extra_join_model_fields_n_values as $query_param => $val) { | |
| 169 | + $query_param = str_replace( | |
| 170 | + $this->get_join_model()->get_this_model_name() . ".", | |
| 171 | + "", | |
| 172 | + $query_param | |
| 173 | + ); | |
| 174 | + $parsed_query[ $query_param ] = $val; | |
| 175 | + } | |
| 176 | + $all_fields = array_merge($foreign_keys, $parsed_query); | |
| 177 | + } | |
| 178 | 178 | |
| 179 | - $existing_entry_in_join_table = $this->get_join_model()->get_one(array($all_fields)); | |
| 180 | - // If there is already an entry in the join table, indicating a relationship, update it instead of adding a | |
| 181 | - // new row. | |
| 182 | - // Again, if you want more sophisticated logic or insertions (handling more columns than just 2 foreign keys to | |
| 183 | - // the other tables) use the joining model directly! | |
| 184 | -        if (! $existing_entry_in_join_table) { | |
| 185 | - $this->get_join_model()->insert($all_fields); | |
| 186 | - } | |
| 187 | - return $other_model_obj; | |
| 188 | - } | |
| 179 | + $existing_entry_in_join_table = $this->get_join_model()->get_one(array($all_fields)); | |
| 180 | + // If there is already an entry in the join table, indicating a relationship, update it instead of adding a | |
| 181 | + // new row. | |
| 182 | + // Again, if you want more sophisticated logic or insertions (handling more columns than just 2 foreign keys to | |
| 183 | + // the other tables) use the joining model directly! | |
| 184 | +		if (! $existing_entry_in_join_table) { | |
| 185 | + $this->get_join_model()->insert($all_fields); | |
| 186 | + } | |
| 187 | + return $other_model_obj; | |
| 188 | + } | |
| 189 | 189 | |
| 190 | 190 | |
| 191 | - /** | |
| 192 | - * Deletes any rows in the join table that have foreign keys matching the other model objects specified | |
| 193 | - * | |
| 194 | - * @param EE_Base_Class|int $this_obj_or_id | |
| 195 | - * @param EE_Base_Class|int $other_obj_or_id | |
| 196 | - * @param array $where_query col=>val pairs that are used as extra conditions for checking existing | |
| 197 | - * values and for removing existing rows if exact matches exist. | |
| 198 | - * @return EE_Base_Class | |
| 199 | - * @throws \EE_Error | |
| 200 | - */ | |
| 201 | - public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array()) | |
| 202 | -    { | |
| 203 | - $this_model_obj = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true); | |
| 204 | - $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true); | |
| 205 | - // check if such a relationship already exists | |
| 206 | - $join_model_fk_to_this_model = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 207 | - $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 191 | + /** | |
| 192 | + * Deletes any rows in the join table that have foreign keys matching the other model objects specified | |
| 193 | + * | |
| 194 | + * @param EE_Base_Class|int $this_obj_or_id | |
| 195 | + * @param EE_Base_Class|int $other_obj_or_id | |
| 196 | + * @param array $where_query col=>val pairs that are used as extra conditions for checking existing | |
| 197 | + * values and for removing existing rows if exact matches exist. | |
| 198 | + * @return EE_Base_Class | |
| 199 | + * @throws \EE_Error | |
| 200 | + */ | |
| 201 | + public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array()) | |
| 202 | +	{ | |
| 203 | + $this_model_obj = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true); | |
| 204 | + $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true); | |
| 205 | + // check if such a relationship already exists | |
| 206 | + $join_model_fk_to_this_model = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | |
| 207 | + $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 208 | 208 | |
| 209 | - $cols_n_values = array( | |
| 210 | - $join_model_fk_to_this_model->get_name() => $this_model_obj->ID(), | |
| 211 | - $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(), | |
| 212 | - ); | |
| 209 | + $cols_n_values = array( | |
| 210 | + $join_model_fk_to_this_model->get_name() => $this_model_obj->ID(), | |
| 211 | + $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(), | |
| 212 | + ); | |
| 213 | 213 | |
| 214 | - // if $where_query exists lets add them to the query_params. | |
| 215 | -        if (! empty($where_query)) { | |
| 216 | - // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | |
| 217 | - // make sure we strip THIS models name from the query param | |
| 218 | - $parsed_query = array(); | |
| 219 | -            foreach ($where_query as $query_param => $val) { | |
| 220 | - $query_param = str_replace( | |
| 221 | - $this->get_join_model()->get_this_model_name() . ".", | |
| 222 | - "", | |
| 223 | - $query_param | |
| 224 | - ); | |
| 225 | - $parsed_query[ $query_param ] = $val; | |
| 226 | - } | |
| 227 | - $cols_n_values = array_merge($cols_n_values, $parsed_query); | |
| 228 | - } | |
| 214 | + // if $where_query exists lets add them to the query_params. | |
| 215 | +		if (! empty($where_query)) { | |
| 216 | + // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | |
| 217 | + // make sure we strip THIS models name from the query param | |
| 218 | + $parsed_query = array(); | |
| 219 | +			foreach ($where_query as $query_param => $val) { | |
| 220 | + $query_param = str_replace( | |
| 221 | + $this->get_join_model()->get_this_model_name() . ".", | |
| 222 | + "", | |
| 223 | + $query_param | |
| 224 | + ); | |
| 225 | + $parsed_query[ $query_param ] = $val; | |
| 226 | + } | |
| 227 | + $cols_n_values = array_merge($cols_n_values, $parsed_query); | |
| 228 | + } | |
| 229 | 229 | |
| 230 | - $this->get_join_model()->delete(array($cols_n_values)); | |
| 231 | - return $other_model_obj; | |
| 232 | - } | |
| 230 | + $this->get_join_model()->delete(array($cols_n_values)); | |
| 231 | + return $other_model_obj; | |
| 232 | + } | |
| 233 | 233 | |
| 234 | - /** | |
| 235 | - * Gets all the non-key fields (ie, not the primary key and not foreign keys) on the join model. | |
| 236 | - * @since $VID:$ | |
| 237 | - * @return EE_Model_Field_Base[] | |
| 238 | - * @throws EE_Error | |
| 239 | - */ | |
| 240 | - public function getNonKeyFields() | |
| 241 | -    { | |
| 242 | - // all fields besides the primary key and two foreign keys should be parameters | |
| 243 | - $join_model = $this->get_join_model(); | |
| 244 | - $standard_fields = array(); | |
| 245 | -        if ($join_model->has_primary_key_field()) { | |
| 246 | - $standard_fields[] = $join_model->primary_key_name(); | |
| 247 | - } | |
| 248 | -        if ($this->get_this_model()->has_primary_key_field()) { | |
| 249 | - $standard_fields[] = $this->get_this_model()->primary_key_name(); | |
| 250 | - } | |
| 251 | -        if ($this->get_other_model()->has_primary_key_field()) { | |
| 252 | - $standard_fields[] = $this->get_other_model()->primary_key_name(); | |
| 253 | - } | |
| 254 | - return array_diff_key( | |
| 255 | - $join_model->field_settings(), | |
| 256 | - array_flip($standard_fields) | |
| 257 | - ); | |
| 258 | - } | |
| 234 | + /** | |
| 235 | + * Gets all the non-key fields (ie, not the primary key and not foreign keys) on the join model. | |
| 236 | + * @since $VID:$ | |
| 237 | + * @return EE_Model_Field_Base[] | |
| 238 | + * @throws EE_Error | |
| 239 | + */ | |
| 240 | + public function getNonKeyFields() | |
| 241 | +	{ | |
| 242 | + // all fields besides the primary key and two foreign keys should be parameters | |
| 243 | + $join_model = $this->get_join_model(); | |
| 244 | + $standard_fields = array(); | |
| 245 | +		if ($join_model->has_primary_key_field()) { | |
| 246 | + $standard_fields[] = $join_model->primary_key_name(); | |
| 247 | + } | |
| 248 | +		if ($this->get_this_model()->has_primary_key_field()) { | |
| 249 | + $standard_fields[] = $this->get_this_model()->primary_key_name(); | |
| 250 | + } | |
| 251 | +		if ($this->get_other_model()->has_primary_key_field()) { | |
| 252 | + $standard_fields[] = $this->get_other_model()->primary_key_name(); | |
| 253 | + } | |
| 254 | + return array_diff_key( | |
| 255 | + $join_model->field_settings(), | |
| 256 | + array_flip($standard_fields) | |
| 257 | + ); | |
| 258 | + } | |
| 259 | 259 | |
| 260 | - /** | |
| 261 | - * Returns true if the join model has non-key fields (ie, fields that aren't the primary key or foreign keys.) | |
| 262 | - * @since $VID:$ | |
| 263 | - * @return boolean | |
| 264 | - */ | |
| 265 | - public function hasNonKeyFields() | |
| 266 | -    { | |
| 267 | - return count($this->get_join_model()->field_settings()) > 3; | |
| 268 | - } | |
| 260 | + /** | |
| 261 | + * Returns true if the join model has non-key fields (ie, fields that aren't the primary key or foreign keys.) | |
| 262 | + * @since $VID:$ | |
| 263 | + * @return boolean | |
| 264 | + */ | |
| 265 | + public function hasNonKeyFields() | |
| 266 | +	{ | |
| 267 | + return count($this->get_join_model()->field_settings()) > 3; | |
| 268 | + } | |
| 269 | 269 | } | 
| @@ -65,18 +65,18 @@ discard block | ||
| 65 | 65 | // remember the model relation chain to the JOIN model, because we'll | 
| 66 | 66 | // need it for get_join_statement() | 
| 67 | 67 | $this->_model_relation_chain_to_join_model = $model_relation_chain; | 
| 68 | - $this_table_pk_field = $this->get_this_model()->get_primary_key_field();// get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 68 | + $this_table_pk_field = $this->get_this_model()->get_primary_key_field(); // get_foreign_key_to($this->get_other_model()->get_this_model_name()); | |
| 69 | 69 | $join_table_fk_field_to_this_table = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name()); | 
| 70 | 70 | $this_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | 
| 71 | 71 | $model_relation_chain, | 
| 72 | 72 | $this->get_this_model()->get_this_model_name() | 
| 73 | - ) . $this_table_pk_field->get_table_alias(); | |
| 73 | + ).$this_table_pk_field->get_table_alias(); | |
| 74 | 74 | |
| 75 | 75 | $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | 
| 76 | 76 | $model_relation_chain, | 
| 77 | 77 | $this->get_join_model()->get_this_model_name() | 
| 78 | - ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 79 | - $join_table = $this->get_join_model()->get_table_for_alias($join_table_alias); | |
| 78 | + ).$join_table_fk_field_to_this_table->get_table_alias(); | |
| 79 | + $join_table = $this->get_join_model()->get_table_for_alias($join_table_alias); | |
| 80 | 80 | // phew! ok, we have all the info we need, now we can create the SQL join string | 
| 81 | 81 | $SQL = $this->_left_join( | 
| 82 | 82 | $join_table, | 
| @@ -84,7 +84,7 @@ discard block | ||
| 84 | 84 | $join_table_fk_field_to_this_table->get_table_column(), | 
| 85 | 85 | $this_table_alias, | 
| 86 | 86 | $this_table_pk_field->get_table_column() | 
| 87 | - ) . $this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias); | |
| 87 | + ).$this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias); | |
| 88 | 88 | |
| 89 | 89 | return $SQL; | 
| 90 | 90 | } | 
| @@ -113,14 +113,14 @@ discard block | ||
| 113 | 113 | $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | 
| 114 | 114 | $this->_model_relation_chain_to_join_model, | 
| 115 | 115 | $this->get_join_model()->get_this_model_name() | 
| 116 | - ) . $join_table_fk_field_to_this_table->get_table_alias(); | |
| 116 | + ).$join_table_fk_field_to_this_table->get_table_alias(); | |
| 117 | 117 | $other_table_pk_field = $this->get_other_model()->get_primary_key_field(); | 
| 118 | 118 | $join_table_fk_field_to_other_table = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name()); | 
| 119 | 119 | $other_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix( | 
| 120 | 120 | $model_relation_chain, | 
| 121 | 121 | $this->get_other_model()->get_this_model_name() | 
| 122 | - ) . $other_table_pk_field->get_table_alias(); | |
| 123 | - $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias); | |
| 122 | + ).$other_table_pk_field->get_table_alias(); | |
| 123 | + $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias); | |
| 124 | 124 | |
| 125 | 125 | $SQL = $this->_left_join( | 
| 126 | 126 | $other_table, | 
| @@ -128,7 +128,7 @@ discard block | ||
| 128 | 128 | $other_table_pk_field->get_table_column(), | 
| 129 | 129 | $join_table_alias, | 
| 130 | 130 | $join_table_fk_field_to_other_table->get_table_column() | 
| 131 | - ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias); | |
| 131 | + ).$this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias); | |
| 132 | 132 | return $SQL; | 
| 133 | 133 | } | 
| 134 | 134 | |
| @@ -161,17 +161,17 @@ discard block | ||
| 161 | 161 | ); | 
| 162 | 162 | |
| 163 | 163 | // if $where_query exists lets add them to the query_params. | 
| 164 | -        if (! empty($extra_join_model_fields_n_values)) { | |
| 164 | +        if ( ! empty($extra_join_model_fields_n_values)) { | |
| 165 | 165 | // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | 
| 166 | 166 | // make sure we strip THIS models name from the query param | 
| 167 | 167 | $parsed_query = array(); | 
| 168 | 168 |              foreach ($extra_join_model_fields_n_values as $query_param => $val) { | 
| 169 | - $query_param = str_replace( | |
| 170 | - $this->get_join_model()->get_this_model_name() . ".", | |
| 169 | + $query_param = str_replace( | |
| 170 | + $this->get_join_model()->get_this_model_name().".", | |
| 171 | 171 | "", | 
| 172 | 172 | $query_param | 
| 173 | 173 | ); | 
| 174 | - $parsed_query[ $query_param ] = $val; | |
| 174 | + $parsed_query[$query_param] = $val; | |
| 175 | 175 | } | 
| 176 | 176 | $all_fields = array_merge($foreign_keys, $parsed_query); | 
| 177 | 177 | } | 
| @@ -181,7 +181,7 @@ discard block | ||
| 181 | 181 | // new row. | 
| 182 | 182 | // Again, if you want more sophisticated logic or insertions (handling more columns than just 2 foreign keys to | 
| 183 | 183 | // the other tables) use the joining model directly! | 
| 184 | -        if (! $existing_entry_in_join_table) { | |
| 184 | +        if ( ! $existing_entry_in_join_table) { | |
| 185 | 185 | $this->get_join_model()->insert($all_fields); | 
| 186 | 186 | } | 
| 187 | 187 | return $other_model_obj; | 
| @@ -212,17 +212,17 @@ discard block | ||
| 212 | 212 | ); | 
| 213 | 213 | |
| 214 | 214 | // if $where_query exists lets add them to the query_params. | 
| 215 | -        if (! empty($where_query)) { | |
| 215 | +        if ( ! empty($where_query)) { | |
| 216 | 216 | // make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name) | 
| 217 | 217 | // make sure we strip THIS models name from the query param | 
| 218 | 218 | $parsed_query = array(); | 
| 219 | 219 |              foreach ($where_query as $query_param => $val) { | 
| 220 | - $query_param = str_replace( | |
| 221 | - $this->get_join_model()->get_this_model_name() . ".", | |
| 220 | + $query_param = str_replace( | |
| 221 | + $this->get_join_model()->get_this_model_name().".", | |
| 222 | 222 | "", | 
| 223 | 223 | $query_param | 
| 224 | 224 | ); | 
| 225 | - $parsed_query[ $query_param ] = $val; | |
| 225 | + $parsed_query[$query_param] = $val; | |
| 226 | 226 | } | 
| 227 | 227 | $cols_n_values = array_merge($cols_n_values, $parsed_query); | 
| 228 | 228 | } | 
| @@ -38,103 +38,103 @@ | ||
| 38 | 38 | * @since 4.0 | 
| 39 | 39 | */ | 
| 40 | 40 |  if (function_exists('espresso_version')) { | 
| 41 | -    if (! function_exists('espresso_duplicate_plugin_error')) { | |
| 42 | - /** | |
| 43 | - * espresso_duplicate_plugin_error | |
| 44 | - * displays if more than one version of EE is activated at the same time | |
| 45 | - */ | |
| 46 | - function espresso_duplicate_plugin_error() | |
| 47 | -        { | |
| 48 | - ?> | |
| 41 | +	if (! function_exists('espresso_duplicate_plugin_error')) { | |
| 42 | + /** | |
| 43 | + * espresso_duplicate_plugin_error | |
| 44 | + * displays if more than one version of EE is activated at the same time | |
| 45 | + */ | |
| 46 | + function espresso_duplicate_plugin_error() | |
| 47 | +		{ | |
| 48 | + ?> | |
| 49 | 49 | <div class="error"> | 
| 50 | 50 | <p> | 
| 51 | 51 | <?php | 
| 52 | - echo esc_html__( | |
| 53 | - 'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.', | |
| 54 | - 'event_espresso' | |
| 55 | - ); ?> | |
| 52 | + echo esc_html__( | |
| 53 | + 'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.', | |
| 54 | + 'event_espresso' | |
| 55 | + ); ?> | |
| 56 | 56 | </p> | 
| 57 | 57 | </div> | 
| 58 | 58 | <?php | 
| 59 | - espresso_deactivate_plugin(plugin_basename(__FILE__)); | |
| 60 | - } | |
| 61 | - } | |
| 62 | -    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1); | |
| 59 | + espresso_deactivate_plugin(plugin_basename(__FILE__)); | |
| 60 | + } | |
| 61 | + } | |
| 62 | +	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1); | |
| 63 | 63 |  } else { | 
| 64 | -    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0'); | |
| 65 | -    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) { | |
| 66 | - /** | |
| 67 | - * espresso_minimum_php_version_error | |
| 68 | - * | |
| 69 | - * @return void | |
| 70 | - */ | |
| 71 | - function espresso_minimum_php_version_error() | |
| 72 | -        { | |
| 73 | - ?> | |
| 64 | +	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0'); | |
| 65 | +	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) { | |
| 66 | + /** | |
| 67 | + * espresso_minimum_php_version_error | |
| 68 | + * | |
| 69 | + * @return void | |
| 70 | + */ | |
| 71 | + function espresso_minimum_php_version_error() | |
| 72 | +		{ | |
| 73 | + ?> | |
| 74 | 74 | <div class="error"> | 
| 75 | 75 | <p> | 
| 76 | 76 | <?php | 
| 77 | - printf( | |
| 78 | - esc_html__( | |
| 79 | - 'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.', | |
| 80 | - 'event_espresso' | |
| 81 | - ), | |
| 82 | - EE_MIN_PHP_VER_REQUIRED, | |
| 83 | - PHP_VERSION, | |
| 84 | - '<br/>', | |
| 85 | - '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>' | |
| 86 | - ); | |
| 87 | - ?> | |
| 77 | + printf( | |
| 78 | + esc_html__( | |
| 79 | + 'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.', | |
| 80 | + 'event_espresso' | |
| 81 | + ), | |
| 82 | + EE_MIN_PHP_VER_REQUIRED, | |
| 83 | + PHP_VERSION, | |
| 84 | + '<br/>', | |
| 85 | + '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>' | |
| 86 | + ); | |
| 87 | + ?> | |
| 88 | 88 | </p> | 
| 89 | 89 | </div> | 
| 90 | 90 | <?php | 
| 91 | - espresso_deactivate_plugin(plugin_basename(__FILE__)); | |
| 92 | - } | |
| 91 | + espresso_deactivate_plugin(plugin_basename(__FILE__)); | |
| 92 | + } | |
| 93 | 93 | |
| 94 | -        add_action('admin_notices', 'espresso_minimum_php_version_error', 1); | |
| 95 | -    } else { | |
| 96 | -        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__); | |
| 97 | - /** | |
| 98 | - * espresso_version | |
| 99 | - * Returns the plugin version | |
| 100 | - * | |
| 101 | - * @return string | |
| 102 | - */ | |
| 103 | - function espresso_version() | |
| 104 | -        { | |
| 105 | -            return apply_filters('FHEE__espresso__espresso_version', '4.9.76.rc.009'); | |
| 106 | - } | |
| 94 | +		add_action('admin_notices', 'espresso_minimum_php_version_error', 1); | |
| 95 | +	} else { | |
| 96 | +		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__); | |
| 97 | + /** | |
| 98 | + * espresso_version | |
| 99 | + * Returns the plugin version | |
| 100 | + * | |
| 101 | + * @return string | |
| 102 | + */ | |
| 103 | + function espresso_version() | |
| 104 | +		{ | |
| 105 | +			return apply_filters('FHEE__espresso__espresso_version', '4.9.76.rc.009'); | |
| 106 | + } | |
| 107 | 107 | |
| 108 | - /** | |
| 109 | - * espresso_plugin_activation | |
| 110 | - * adds a wp-option to indicate that EE has been activated via the WP admin plugins page | |
| 111 | - */ | |
| 112 | - function espresso_plugin_activation() | |
| 113 | -        { | |
| 114 | -            update_option('ee_espresso_activation', true); | |
| 115 | - } | |
| 108 | + /** | |
| 109 | + * espresso_plugin_activation | |
| 110 | + * adds a wp-option to indicate that EE has been activated via the WP admin plugins page | |
| 111 | + */ | |
| 112 | + function espresso_plugin_activation() | |
| 113 | +		{ | |
| 114 | +			update_option('ee_espresso_activation', true); | |
| 115 | + } | |
| 116 | 116 | |
| 117 | - register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation'); | |
| 117 | + register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation'); | |
| 118 | 118 | |
| 119 | - require_once __DIR__ . '/core/bootstrap_espresso.php'; | |
| 120 | - bootstrap_espresso(); | |
| 121 | - } | |
| 119 | + require_once __DIR__ . '/core/bootstrap_espresso.php'; | |
| 120 | + bootstrap_espresso(); | |
| 121 | + } | |
| 122 | 122 | } | 
| 123 | 123 |  if (! function_exists('espresso_deactivate_plugin')) { | 
| 124 | - /** | |
| 125 | - * deactivate_plugin | |
| 126 | - * usage: espresso_deactivate_plugin( plugin_basename( __FILE__ )); | |
| 127 | - * | |
| 128 | - * @access public | |
| 129 | - * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file | |
| 130 | - * @return void | |
| 131 | - */ | |
| 132 | - function espresso_deactivate_plugin($plugin_basename = '') | |
| 133 | -    { | |
| 134 | -        if (! function_exists('deactivate_plugins')) { | |
| 135 | - require_once ABSPATH . 'wp-admin/includes/plugin.php'; | |
| 136 | - } | |
| 137 | - unset($_GET['activate'], $_REQUEST['activate']); | |
| 138 | - deactivate_plugins($plugin_basename); | |
| 139 | - } | |
| 124 | + /** | |
| 125 | + * deactivate_plugin | |
| 126 | + * usage: espresso_deactivate_plugin( plugin_basename( __FILE__ )); | |
| 127 | + * | |
| 128 | + * @access public | |
| 129 | + * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file | |
| 130 | + * @return void | |
| 131 | + */ | |
| 132 | + function espresso_deactivate_plugin($plugin_basename = '') | |
| 133 | +	{ | |
| 134 | +		if (! function_exists('deactivate_plugins')) { | |
| 135 | + require_once ABSPATH . 'wp-admin/includes/plugin.php'; | |
| 136 | + } | |
| 137 | + unset($_GET['activate'], $_REQUEST['activate']); | |
| 138 | + deactivate_plugins($plugin_basename); | |
| 139 | + } | |
| 140 | 140 | } |