Rev 3639 | Rev 4398 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
<?phpdeclare(strict_types=1);namespace LeadersLinked\Controller;use Laminas\Db\Adapter\AdapterInterface;use Laminas\Cache\Storage\Adapter\AbstractAdapter;use Laminas\Mvc\Controller\AbstractActionController;use LeadersLinked\Hydrator\ObjectPropertyHydrator;use Laminas\Log\LoggerInterface;use Laminas\View\Model\ViewModel;use Laminas\View\Model\JsonModel;use LeadersLinked\Mapper\UserMapper;use LeadersLinked\Library\Functions;use LeadersLinked\Mapper\UserPasswordMapper;use LeadersLinked\Form\AccountSetting\NotificationSettingForm;use LeadersLinked\Mapper\UserNotificationSettingMapper;use LeadersLinked\Form\AccountSetting\ChangePasswordForm;use LeadersLinked\Form\AccountSetting\ChangeImageForm;use LeadersLinked\Library\Image;use LeadersLinked\Form\AccountSetting\LocationForm;use LeadersLinked\Model\Location;use LeadersLinked\Mapper\LocationMapper;use LeadersLinked\Form\AccountSetting\PrivacySettingForm;use LeadersLinked\Mapper\UserProfileMapper;use LeadersLinked\Form\AccountSetting\BasicForm;use LeadersLinked\Form\Transaction\FundsAddForm;use LeadersLinked\Mapper\UserBrowserMapper;use LeadersLinked\Mapper\QueryMapper;use LeadersLinked\Mapper\DeviceHistoryMapper;use LeadersLinked\Mapper\DeviceMapper;use Laminas\Hydrator\ArraySerializableHydrator;use Laminas\Db\ResultSet\HydratingResultSet;use Laminas\Paginator\Adapter\DbSelect;use Laminas\Paginator\Paginator;use LeadersLinked\Mapper\UserIpMapper;use LeadersLinked\Model\Transaction;use LeadersLinked\Model\Provider;use LeadersLinked\Mapper\TransactionMapper;use PayPalCheckoutSdk\Core\SandboxEnvironment;use PayPalCheckoutSdk\Core\ProductionEnvironment;use PayPalCheckoutSdk\Core\PayPalHttpClient;use PayPalCheckoutSdk\Orders\OrdersCreateRequest;use PayPalHttp\HttpException;use LeadersLinked\Mapper\UserProviderMapper;use LeadersLinked\Model\UserProvider;use LeadersLinked\Model\UserPassword;use LeadersLinked\Model\UserDeleted;use LeadersLinked\Mapper\UserDeletedMapper;use LeadersLinked\Model\UserType;use LeadersLinked\Model\User;use LeadersLinked\Library\QueueEmail;use LeadersLinked\Mapper\EmailTemplateMapper;use LeadersLinked\Model\EmailTemplate;class AccountSettingController extends AbstractActionController{/**** @var AdapterInterface*/private $adapter;/**** @var AbstractAdapter*/private $cache;/**** @var LoggerInterface*/private $logger;/**** @var array*/private $config;/**** @param AdapterInterface $adapter* @param AbstractAdapter $cache* @param LoggerInterface $logger* @param array $config*/public function __construct($adapter, $cache , $logger, $config){$this->adapter = $adapter;$this->cache = $cache;$this->logger = $logger;$this->config = $config;}public function indexAction(){$request = $this->getRequest();if($request->isGet()) {$tab = filter_var($this->params()->fromQuery('tab'), FILTER_SANITIZE_STRING);if(!in_array($tab, ['nav-basic', 'nav-notification', 'nav-password', 'nav-image', 'nav-location', 'nav-privacy', 'nav-ips', 'nav-browsers', 'nav-transactions', 'nav-social-networks'])) {$tab = 'nav-basic';}$sandbox = $this->config['leaderslinked.runmode.sandbox'];if($sandbox) {$google_map_key = $this->config['leaderslinked.google_map.sandbox_api_key'];} else {$google_map_key = $this->config['leaderslinked.google_map.production_api_key'];}$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);$userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);$formNotificationSetting = new NotificationSettingForm();$formNotificationSetting->setData((array) $userUserNotificationSetting );$formLocation = new LocationForm();if($currentUser->location_id) {$locationMapper = LocationMapper::getInstance($this->adapter);$location = $locationMapper->fetchOne($currentUser->location_id);if($location) {$location_formatted_address = $location->formatted_address;$formLocation->setData((array) $location);}} else {$location_formatted_address = '';}$facebook = 0;$twitter = 0;$google = 0;$userProviderMapper = UserProviderMapper::getInstance($this->adapter);$userProviders = $userProviderMapper->fetchAllByUserId($currentUser->id);foreach($userProviders as $userProvider){switch($userProvider->provider){case UserProvider::PROVIDER_FACEBOOK :$facebook = 1;break;case UserProvider::PROVIDER_TWITTER :$twitter = 1;break;case UserProvider::PROVIDER_GOOGLE :$google = 1;break;}}$hydrator = new ObjectPropertyHydrator();$user_data = $hydrator->extract($currentUser);$formBasic = new BasicForm();$formBasic->setData($user_data);$formChangePassword = new ChangePasswordForm();$formChangeImage = new ChangeImageForm($this->config);$formPrivacy = new PrivacySettingForm();$formPrivacy->setData(['show_in_search' => $currentUser->show_in_search,]);$formAddFund = new FundsAddForm();$this->layout()->setTemplate('layout/layout.phtml');$viewModel = new ViewModel();$viewModel->setTemplate('leaders-linked/account-settings/index.phtml');$viewModel->setVariables(['tab' => $tab,'balance' => number_format(floatval($currentUser->balance), 2),'amounts' => ['5' => '5 LABEL_USD','10' => '10 LABEL_USD','15' => '15 LABEL_USD','20' => '20 LABEL_USD','25' => '25 LABEL_USD','50' => '50 LABEL_USD','75' => '75 LABEL_USD','100' => '100 LABEL_USD',],'usertype_id' => $currentUser->usertype_id,'image' => $this->url()->fromRoute('storage',['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $currentUser->image]),'formNotificationSetting' => $formNotificationSetting,'formBasic' => $formBasic,'formChangePassword' => $formChangePassword,'formChangeImage' => $formChangeImage,'formLocation' => $formLocation,'formPrivacy' => $formPrivacy,'formAddFund' => $formAddFund,'config' => $this->config,'google_map_key' => $google_map_key,'location_formatted_address' => $location_formatted_address,'google' => $google,'facebook' => $facebook,'twitter' => $twitter,]);return $viewModel ;} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function notificationAction(){$request = $this->getRequest();if($request->isGet()) {$hydrator = new ObjectPropertyHydrator();$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);$userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);return new JsonModel(['success' => true,'data' => ['receive_connection_request' => $userUserNotificationSetting->receive_connection_request ? 1 : 0,'accept_my_request_connection' => $userUserNotificationSetting->accept_my_request_connection ? 1 : 0,'receive_invitation_group' => $userUserNotificationSetting->receive_invitation_group ? 1 : 0,'accept_my_request_join_group' => $userUserNotificationSetting->accept_my_request_join_group ? 1 : 0,'receive_request_join_my_group' => $userUserNotificationSetting->receive_request_join_my_group ? 1 : 0,'receive_invitation_company' => $userUserNotificationSetting->receive_invitation_company ? 1 : 0,'like_my_feed' => $userUserNotificationSetting->like_my_feed ? 1 : 0,'comment_my_feed' => $userUserNotificationSetting->comment_my_feed ? 1 : 0,'share_my_feed' => $userUserNotificationSetting->share_my_feed ? 1 : 0,'receive_inmail' => $userUserNotificationSetting->receive_inmail ? 1 : 0,'receive_invitation_meeting' => $userUserNotificationSetting->receive_invitation_meeting ? 1 : 0,'receive_reminder_meeting' => $userUserNotificationSetting->receive_reminder_meeting ? 1 : 0,'receive_records_available_meeting' => $userUserNotificationSetting->receive_records_available_meeting ? 1 : 0,]]);} else if($request->isPost()) {$dataPost = $request->getPost()->toArray();$form = new NotificationSettingForm();$form->setData($dataPost);if($form->isValid()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);$userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);$hydrator->hydrate($dataPost, $userUserNotificationSetting);if($userUserNotificationSettingMapper->update($userUserNotificationSetting)) {$this->logger->info('Se guardo las preferencias de notificación', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_NOTIFICATION_SETTINGS_UPDATE'];} else {$data = ['success' => false,'data' => 'ERROR_UNKNOWN'];}return new JsonModel($data);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}public function passwordAction(){$request = $this->getRequest();if($request->isPost()) {$dataPost = $request->getPost()->toArray();$form = new ChangePasswordForm();$form->setData($dataPost);if($form->isValid()) {$data = (array) $form->getData();$password = $data['password'];$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);$userPasswords = $userPasswordMapper->fetchAllByUserId($currentUser->id);$oldPassword = false;foreach($userPasswords as $userPassword){if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)){$oldPassword = true;break;}}if($oldPassword) {$this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);return new JsonModel(['success' => false,'data' => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED']);} else {$password_hash = password_hash($password, PASSWORD_DEFAULT);$userMapper = UserMapper::getInstance($this->adapter);$result = $userMapper->updatePassword($currentUser, $password_hash);if($result) {$userPassword = new UserPassword();$userPassword->user_id = $currentUser->id;$userPassword->password = $password_hash;$userPasswordMapper->insert($userPassword);$this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);return new JsonModel(['success' => true,'data' => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED']);} else {$this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);return new JsonModel(['success' => true,'data' => 'ERROR_THERE_WAS_AN_ERROR']);}}} else {$messages = [];$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}public function imageAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$operation = $this->params()->fromRoute('operation');$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userMapper = UserMapper::getInstance($this->adapter);$target_path = $this->config['leaderslinked.fullpath.user'] . DIRECTORY_SEPARATOR . $currentUser->uuid;return new JsonModel(['success' => true,'data' => $this->url()->fromRoute('storage', ['code' => $currentUser->uuid, 'type' => 'user', 'filename' => $currentUser->image])]);} else if($request->isPost()) {$target_path = $this->config['leaderslinked.fullpath.user'] . DIRECTORY_SEPARATOR . $currentUser->uuid;$userMapper = UserMapper::getInstance($this->adapter);if($operation == 'delete') {$this->logger->info('Se borro el image del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);if($currentUser->image) {if(!image ::delete($target_path, $currentUser->image)) {return new JsonModel(['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR']);}}$currentUser->image = '';if(!$userMapper->update($currentUser)) {return new JsonModel(['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR']);}} else {$form = new ChangeImageForm($this->config);$data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$form->setData($data);if($form->isValid()) {$files = $request->getFiles()->toArray();if(!empty($files['image']['error'])) {return new JsonModel(['success' => false,'data' => 'ERROR_UPLOAD_FILE']);}if($currentUser->image) {if(!Image::delete($target_path, $currentUser->image)) {return new JsonModel(['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR']);}}$target_filename = 'user-' . uniqid() . '.png';list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);$source = $files['image']['tmp_name'];$crop_to_dimensions = true;if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {return new JsonModel(['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR']);}$currentUser->image = $target_filename;if(!$userMapper->updateImage($currentUser)) {return new JsonModel(['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR']);} else {$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);if($userProfile) {$userProfile->image = $currentUser->image;$userProfileMapper->updateImage($userProfile);}}$this->logger->info('Se actualizo el image del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}return new JsonModel(['success' => true,'data' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $currentUser->image])]);}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de la ubucación* @return \Laminas\View\Model\JsonModel*/public function locationAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();if($request->isGet()) {$hydrator = new ObjectPropertyHydrator();$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$locationMapper = LocationMapper::getInstance($this->adapter);$location = $locationMapper->fetchOne($currentUser->location_id);$data = ['formatted_address' => $location ? $location->formatted_address : '','address1' => $location ? $location->address1 : '','address2' => $location ? $location->address2 : '','country' => $location ? $location->country : '','state' => $location ? $location->state : '','city1' => $location ? $location->city1 : '','city2' => $location ? $location->city2 : '','postal_code' => $location ? $location->postal_code : '','latitude' => $location ? $location->latitude : '','longitude' => $location ? $location->longitude : '',];return new JsonModel(['success' => true,'data' => $data]);} else if($request->isPost()) {$form = new LocationForm();$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if($form->isValid()) {$dataPost = (array) $form->getData();$location = new Location();$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $location);$location->id = $currentUser->location_id;$locationMapper = LocationMapper::getInstance($this->adapter);if($currentUser->location_id) {$result = $locationMapper->update($location);} else {$result = $locationMapper->insert($location);if($result) {$currentUser->location_id = $location->id;$userMapper = UserMapper::getInstance($this->adapter);$userMapper->updateLocation($currentUser);}}if($result) {$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);if($userProfile) {$userProfile->location_id = $location->id;$userProfileMapper->updateLocation($userProfile);}}if($result) {$this->logger->info('Se actualizo la ubicación del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$response = ['success' => true,'data' => ['formatted_address' => $location->formatted_address,'message' => 'LABEL_LOCATION_UPDATED' ,]];} else {$response = ['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR'];}return new JsonModel($response);} else {return new JsonModel(['success' => false,'data' => 'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY']);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}public function privacyAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userMapper = UserMapper::getInstance($this->adapter);$user = $userMapper->fetchOne($currentUser->id);return new JsonModel(['success' => true,'data' => ['show_in_search' => $user->show_in_search ? 1 : 0]]);} else if($request->isPost()) {$dataPost = $request->getPost()->toArray();$form = new PrivacySettingForm();$form->setData($dataPost);if($form->isValid()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$userMapper = UserMapper::getInstance($this->adapter);$hydrator->hydrate($dataPost, $currentUser);if($userMapper->updatePrivacy($currentUser)) {$this->logger->info('Se guardo las preferencias de privacidad', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_PRIVACY_UPDATE'];} else {$data = ['success' => false,'data' => 'ERROR_UNKNOWN'];}return new JsonModel($data);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}public function basicAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userMapper = UserMapper::getInstance($this->adapter);$user = $userMapper->fetchOne($currentUser->id);return new JsonModel(['success' => true,'data' => ['first_name' => $user->first_name,'last_name' => $user->last_name,'gender' => $user->gender ? $user->gender : '','phone' => $user->phone ? $user->phone : '','email' => $user->email,]]);} else if($request->isPost()) {$dataPost = $request->getPost()->toArray();$form = new BasicForm();$form->setData($dataPost);if($form->isValid()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$userMapper = UserMapper::getInstance($this->adapter);$hydrator->hydrate($dataPost, $currentUser);if($userMapper->updateBasic($currentUser)) {$this->logger->info('Se guardaron los datos básicos ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_BASIC_UPDATE'];} else {$data = ['success' => false,'data' => 'ERROR_UNKNOWN'];}return new JsonModel($data);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}public function browsersAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$search = '';$page = intval($this->params()->fromQuery('start', 1), 10);$records_x_page = intval($this->params()->fromQuery('length', 10), 10);$order_field = 'updated_on';$order_direction = 'DESC';$userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);$paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);$items = [];$records = $paginator->getCurrentItems();foreach($records as $record){$item = ['id' => $record->id,'platform' => $record->platform,'browser' => $record->browser,'device_type' => $record->device_type,'version' => $record->version,'updated_on' => $record->updated_on,];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);}}public function devicesAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$page = intval($this->params()->fromPost('start', 1), 10);$records_x_page = intval($this->params()->fromPost('length', 10), 10);/*select d.platform, d.brand, d.manufacturer, d.model, d.version,dh.ip, dh.updated_on from tbl_device_history as dhinner join tbl_devices as d on d.id = dh.device_idwhere dh.user_id = 4 order by dh.updated_on desc*/$queryMapper = QueryMapper::getInstance($this->adapter);$select = $queryMapper->getSql()->select();$select->columns(['ip', 'updated_on']);$select->from(['dh' => DeviceHistoryMapper::_TABLE]);$select->join(['d' => DeviceMapper::_TABLE], 'd.id = dh.device_id', ['id', 'platform','brand','manufacturer','model','version']);$select->where->equalTo('dh.user_id', $currentUser->id);$select->order('updated_on desc ');$hydrator = new ArraySerializableHydrator();$resultset = new HydratingResultSet($hydrator);$adapter = new DbSelect($select, $queryMapper->getSql(), $resultset);$paginator = new Paginator($adapter);$paginator->setItemCountPerPage($records_x_page);$paginator->setCurrentPageNumber($page);$items = [];$records = $paginator->getCurrentItems();foreach($records as $record){$item = ['id' => $record['id'],'platform' => $record['platform'],'brand' => $record['brand'],'manufacturer' => $record['manufacturer'],'version' => $record['version'],'model' => $record['model'],'version' => $record['version'],'ip' => $record['ip'],'updated_on' => $record['updated_on'],];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);}}public function ipsAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$search = '';$page = intval($this->params()->fromPost('start', 1), 10);$records_x_page = intval($this->params()->fromPost('length', 10), 10);$order_field = 'updated_on';$order_direction = 'DESC';$userBrowserMapper = UserIpMapper::getInstance($this->adapter);$paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);$items = [];$records = $paginator->getCurrentItems();foreach($records as $record){$item = ['id' => $record->id,'ip' => $record->ip,'country_name' => $record->country_name,'state_name' => $record->state_name,'city' => $record->city,'postal_code' => $record->postal_code,'updated_on' => $record->updated_on,];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);}}public function transactionsAction(){$request = $this->getRequest();if($request->isGet()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$search = '';$page = intval($this->params()->fromPost('start', 1), 10);$records_x_page = intval($this->params()->fromPost('length', 10), 10);$order_field = 'updated_on';$order_direction = 'DESC';$status = [Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',Transaction::STATUS_PENDING => 'LABEL_PENDING',Transaction::STATUS_PROCESSING => 'LABEL_PROCESSING',Transaction::STATUS_REJECTED => 'LABEL_REJECTED',Transaction::STATUS_COMPLETED => 'LABEL_COMPLETED',Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',];$types = [Transaction::TYPE_COUPON => 'LABEL_COUPON',Transaction::TYPE_PAYMENT => 'LABEL_PAYMENT',Transaction::TYPE_REVERSE => 'LABEL_REVERSE',Transaction::TYPE_TRANSFER => 'LABEL_TRANSFER',];$providers = [Provider::PAYPAL => 'LABEL_PAYPAL',];$transactionMapper = TransactionMapper::getInstance($this->adapter);$paginator = $transactionMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);$items = [];$records = $paginator->getCurrentItems();foreach($records as $record){$item = ['id' => $record->id,'description' => $record->description,'provider' => $providers[$record->provider],'type' => $types[$record->type],'status' => $status[$record->status],'previous' => $record->previous,'amount' => $record->amount,'current' => $record->current,'updated_on' => $record->updated_on,];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);}}public function addFundAction(){$request = $this->request;if($request->isPost()) {$form = new FundsAddForm();$form->setData($request->getPost()->toArray());if($form->isValid()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$dataPost = (array) $form->getData();$description = $dataPost['description'];$amount = $dataPost['amount'];$sandbox = $this->config['leaderslinked.runmode.sandbox_paypal'];if($sandbox) {//$account_id = $this->config['leaderslinked.paypal.sandbox_account_id'];$client_id = $this->config['leaderslinked.paypal.sandobx_client_id'];$client_secret = $this->config['leaderslinked.paypal.sandbox_client_secret'];$environment = new SandboxEnvironment($client_id, $client_secret);} else {// $account_id = $this->config['leaderslinked.paypal.production_account_id'];$client_id = $this->config['leaderslinked.paypal.production_client_id'];$client_secret = $this->config['leaderslinked.paypal.production_client_secret'];$environment = new ProductionEnvironment($client_id, $client_secret);}$internal_id = uniqid(Provider::PAYPAL, true);$client = new PayPalHttpClient($environment);$request = new OrdersCreateRequest;//$request->prefer('return=representation');$request->body = ['intent' => 'CAPTURE','purchase_units' => [['reference_id' => $internal_id,'description' => $description,'amount' => ['value' => number_format($amount, 2),'currency_code' => 'USD']]],'application_context' => ['brand_name' => 'Leaders Linked','locale' => 'es-UY','cancel_url' => $this->url()->fromRoute('paypal/cancel', [] , ['force_canonical' => true]),'return_url' => $this->url()->fromRoute('paypal/success', [] , ['force_canonical' => true]),]];try {// Call API with your client and get a response for your call$response = $client->execute($request);$external_id = $response->result->id;$approve_url = '';if($response->result->status == 'CREATED') {$response->result->id;foreach($response->result->links as $link){if($link->rel == 'approve') {$approve_url = $link->href;}//print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";}}//echo json_encode($resp, JSON_PRETTY_PRINT), "\n";// To toggle printing the whole response body comment/uncomment below line// echo json_encode($resp->result, JSON_PRETTY_PRINT), "\n";if($external_id && $approve_url) {$transaction = new Transaction();$transaction->internal_id = $internal_id;$transaction->external_id = $external_id;$transaction->provider = Provider::PAYPAL;$transaction->user_id = $currentUser->id;$transaction->previous = 0;$transaction->amount = $amount;$transaction->current = 0;$transaction->status = Transaction::STATUS_PENDING;$transaction->type = Transaction::TYPE_PAYMENT;$transaction->description = $description;$transaction->request = json_encode($response, JSON_PRETTY_PRINT);$requestId = Provider::PAYPAL . '-' . $external_id;$this->cache->setItem($requestId, serialize($transaction));return new JsonModel(['success' => true, 'data' => $approve_url]);} else {return new JsonModel(['success' => false, 'data' => 'ERROR_TRANSACTION_NOT_SAVED']);}} catch (HttpException $ex) {return new JsonModel(['success' => false, 'data' => $ex->getMessage()]);}} else {$message = '';;$form_messages = (array) $form->getMessages();foreach($form_messages as $fieldname => $field_messages){foreach( $field_messages as $key => $value){$message = $value;}}$response = ['success' => false,'data' => $message];return new JsonModel($response);}} else {return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);}}public function removeFacebookAction(){$request = $this->getRequest();if($request->isPost()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userProviderMapper = UserProviderMapper::getInstance($this->adapter);$userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK);if($userProvider) {if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK)) {return new JsonModel(['success' => true,'data' => 'LABEL_USER_PROVIDER_FACEBOOK_REMOVED']);} else {return new JsonModel(['success' => false,'data' => $userProviderMapper->getError()]);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_USER_PROVIDER_FACEBOOK_NOT_FOUND']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function addFacebookAction(){$request = $this->getRequest();if($request->isGet()) {try {$app_id = $this->config['leaderslinked.facebook.app_id'];$app_password = $this->config['leaderslinked.facebook.app_password'];$app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];//$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];//$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];$fb = new \Facebook\Facebook(['app_id' => $app_id,'app_secret' => $app_password,'default_graph_version' => $app_graph_version,]);$app_url_auth = $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);$helper = $fb->getRedirectLoginHelper();$permissions = ['email', 'public_profile']; // Optional permissions$facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);return new JsonModel(['success' => true,'data' => $facebookUrl]);} catch (\Throwable $e) {return new JsonModel(['success' => false,'data' => 'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function removeTwitterAction(){$request = $this->getRequest();if($request->isPost()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userProviderMapper = UserProviderMapper::getInstance($this->adapter);$userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER);if($userProvider) {if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER)) {return new JsonModel(['success' => true,'data' => 'LABEL_USER_PROVIDER_TWITTER_REMOVED']);} else {return new JsonModel(['success' => false,'data' => $userProviderMapper->getError()]);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_USER_PROVIDER_TWITTER_NOT_FOUND']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function addTwitterAction(){$request = $this->getRequest();if($request->isGet()) {try {if($this->config['leaderslinked.runmode.sandbox']) {$twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];$twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];} else {$twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];$twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];}/*echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;exit;*///$redirect_url = $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);$redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];$twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);$request_token = $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url ]);$twitterUrl = $twitter->url('oauth/authorize', [ 'oauth_token' => $request_token['oauth_token'] ]);$twitterSession = new \Laminas\Session\Container('twitter');$twitterSession->oauth_token = $request_token['oauth_token'];$twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];return new JsonModel(['success' => true,'data' => $twitterUrl]);} catch (\Throwable $e) {return new JsonModel(['success' => false,'data' => 'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function removeGoogleAction(){$request = $this->getRequest();if($request->isPost()) {$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userProviderMapper = UserProviderMapper::getInstance($this->adapter);$userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE);if($userProvider) {if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE)) {return new JsonModel(['success' => true,'data' => 'LABEL_USER_PROVIDER_GOOGLE_REMOVED']);} else {return new JsonModel(['success' => false,'data' => $userProviderMapper->getError()]);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_USER_PROVIDER_GOOGLE_NOT_FOUND']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function addGoogleAction(){$request = $this->getRequest();if($request->isGet()) {try {$google = new \Google_Client();$google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');$google->setAccessType("offline"); // offline access$google->setIncludeGrantedScopes(true); // incremental auth$google->addScope('profile');$google->addScope('email');// $redirect_url = $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);$redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];$google->setRedirectUri($redirect_url);$googleUrl = $google->createAuthUrl();return new JsonModel(['success' => true,'data' => $googleUrl]);} catch (\Throwable $e) {return new JsonModel(['success' => false,'data' => 'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE']);}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function deleteAccountAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$user = $currentUserPlugin->getUser();$request = $this->getRequest();if($request->isGet()) {$this->sendEmailDeleteAccountKey($user);return new JsonModel(['success' => true,'data' => ['message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_SENT_A_CONFIRMATION_CODE']]);} else if($request->isPost()) {$code = $this->params()->fromPost('code');if(empty($code) || $code != $user->delete_account_key) {$this->sendEmailDeleteAccountKey($user);return new JsonModel(['success' => false,'data' => ['message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_IS_WRONG']]);}$delete_account_generated_on = strtotime($user->delete_account_generated_on);$expiry_time = $delete_account_generated_on + $this->config['leaderslinked.security.delete_account_expired'];if (time() > $expiry_time) {$this->sendEmailDeleteAccountKey($user) ;return new JsonModel(['success' => false,'data' => ['message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_EXPIRED']]);}$userDeleted = new UserDeleted();$userDeleted->user_id = $user->id;$userDeleted->first_name = $user->first_name;$userDeleted->last_name = $user->last_name;$userDeleted->email = $user->email;$userDeleted->image = $user->image;$userDeleted->phone = $user->phone;$userDeleted->pending = UserDeleted::PENDING_YES;$userDeletedMapper = UserDeletedMapper::getInstance($this->adapter);if ($userDeletedMapper->insert($userDeleted)) {$this->sendEmailDeleteAccountCompleted($user);$user->first_name = 'LABEL_DELETE_ACCOUNT_FIRST_NAME';$user->last_name = 'LABEL_DELETE_ACCOUNT_LAST_NAME';$user->email = 'user-deleted-' . uniqid() . '@leaderslinked.com';$user->image = '';$user->usertype_id = UserType::USER_DELETED;$user->status = User::STATUS_DELETED;$user->delete_account_key = '';$user->delete_account_generated_on = '';$userMapper = UserMapper::getInstance($this->adapter);if($userMapper->update($user)) {return new JsonModel(['success' => true,'data' => ['message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_STARTED_DELETING_YOUR_DATA','redirect_url' => $this->url()->fromRoute('signout'),]]);} else {return new JsonModel(['success' => false,'data' => ['message' => $userDeletedMapper->getError()]]);}} else {return new JsonModel(['success' => false,'data' => ['message' => $userDeletedMapper->getError()]]);}}return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}private function sendEmailDeleteAccountKey($user){$delete_account_key = Functions::generatePassword(8);$userMapper = UserMapper::getInstance($this->adapter);$userMapper->updateDeleteAccountKey($user->id, $delete_account_key);$emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);$emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_CODE, $user->network_id);if($emailTemplate) {$arrayCont = ['firstname' => $user->first_name,'lastname' => $user->last_name,'code' => $delete_account_key,'link' => ''];$email = new QueueEmail($this->adapter);$email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));}}private function sendEmailDeleteAccountCompleted($user){$emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);$emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_COMPLETED, $user->network_id);if($emailTemplate) {$arrayCont = ['firstname' => $user->first_name,'lastname' => $user->last_name,'code' => '','link' => ''];$email = new QueueEmail($this->adapter);$email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));}}}