public function hooks($name, $payload = null) { $dispatcher = Engine_Hooks_Dispatcher::getInstance(); $event = $dispatcher->callEvent($name, $payload); $responses = $event->getResponses(); if (!is_array($responses) || empty($responses)) { return ''; } $content = ''; foreach ($responses as $response) { if (is_string($response)) { $content .= $response; } else { if (is_array($response) && !empty($response['type'])) { if ($response['type'] == 'partial') { $content .= $this->view->partial(@$response['args'][0], @$response['args'][1], @$response['args'][2], @$response['args'][3]); } else { if ($response['type'] == 'action') { $content .= $this->view->action(@$response['args'][0], @$response['args'][1], @$response['args'][2], @$response['args'][3]); } } } else { throw new Zend_View() - Exception('Unknown data type returned in ' . get_class($this)); continue; } } $content .= $this->getSeparator(); } return $content; }
public function indexAction() { // members, friends $table = Engine_Api::_()->getDbTable('users', 'user'); $select = $table->select()->setIntegrityCheck(false)->from($table->info('name'), array('COUNT(*) AS count', 'SUM(member_count) AS friends'))->where('enabled = ?', 1); $rows = $table->fetchAll($select)->toArray(); $this->view->member_count = $rows[0]['count']; $this->view->friend_count = $rows[0]['friends']; $friendship_types = Engine_Api::_()->getDbtable('membership', 'user'); if ($friendship_types->isReciprocal()) { $this->view->friend_count = round($rows[0]['friends'] / 2); } // posts $table = Engine_Api::_()->getDbTable('actions', 'activity'); $select = $table->select()->setIntegrityCheck(false)->from($table->info('name'), array('COUNT(*) AS count')); $rows = $table->fetchAll($select)->toArray(); $this->view->post_count = $rows[0]['count']; // comments $table = Engine_Api::_()->getDbTable('comments', 'activity'); $select = $table->select()->setIntegrityCheck(false)->from($table->info('name'), array('COUNT(*) AS count')); $rows = $table->fetchAll($select)->toArray(); $this->view->comment_count = $rows[0]['count']; // plugin hook $this->view->hooked_stats = array(); $events = Engine_Hooks_Dispatcher::getInstance()->callEvent('onStatistics'); $events_res = $events->getResponses(); if (is_array($events_res)) { $this->view->hooked_stats = $events_res; } }
public function indexAction() { // Users $userTable = Engine_Api::_()->getItemTable('user'); $select = new Zend_Db_Select($userTable->getAdapter()); $select->from($userTable->info('name'), 'COUNT(user_id) as count'); $data = $select->query()->fetch(); $this->view->userCount = (int) $data['count']; // Reports $reportTable = Engine_Api::_()->getDbtable('reports', 'core'); $select = new Zend_Db_Select($reportTable->getAdapter()); $select->from($reportTable->info('name'), 'COUNT(report_id) as count')->where('`read` = ?', 0); $data = $select->query()->fetch(); $this->view->reportCount = (int) $data['count']; // Plugins $moduleTable = Engine_Api::_()->getDbtable('modules', 'core'); $select = new Zend_Db_Select($moduleTable->getAdapter()); $select->from($moduleTable->info('name'), 'COUNT(TRUE) as count')->where('type = ?', 'extra'); $data = $select->query()->fetch(); $this->view->pluginCount = (int) $data['count']; // Notifications // Hook-based $event = Engine_Hooks_Dispatcher::_()->callEvent('getAdminNotifications'); $this->view->notifications = $event->getResponses(); // Database-based $select = Engine_Api::_()->getDbtable('log', 'core')->select()->where('domain = ?', 'admin')->order('timestamp DESC'); $this->view->paginator = $paginator = Zend_Paginator::factory($select); $paginator->setItemCountPerPage(4); }
public function indexAction() { $allowedHosts = array(); // self $host = $_SERVER['HTTP_HOST']; if (preg_match('/\\d+\\.\\d+\\.\\d+\\.\\d+/', $host)) { $allowedHosts[] = $host; } else { $allowedHosts[] = '*.' . $host; $allowedHosts[] = $host; } // For static base url $staticBaseUrl = Zend_Registry::get('StaticBaseUrl'); $parts = parse_url($staticBaseUrl); if (!empty($parts['host'])) { $host = $parts['host']; if (preg_match('/\\d+\\.\\d+\\.\\d+\\.\\d+/', $host)) { $allowedHosts[] = $host; } else { $allowedHosts[] = '*.' . $host; $allowedHosts[] = $host; } } // hooks $event = Engine_Hooks_Dispatcher::_()->callEvent('onGenerateCrossDomain'); if (($r = $event->getResponses()) && is_array($r)) { $allowedHosts += $r; } $this->view->allowedHosts = $allowedHosts; // options $this->_helper->layout()->disableLayout(); $this->getResponse()->setHeader('Content-Type', 'application/xml'); }
public function indexAction() { // members, friends $table = Engine_Api::_()->getItemTable('user'); $info = $table->select()->from($table, array('COUNT(*) AS count', 'SUM(member_count) AS friends'))->where('enabled = ?', true)->query()->fetch(); $this->view->member_count = $info['count']; $this->view->friend_count = $info['friends']; $friendship_types = Engine_Api::_()->getDbtable('membership', 'user'); if ($friendship_types->isReciprocal()) { $this->view->friend_count = round($info['friends'] / 2); } // posts $table = Engine_Api::_()->getDbTable('actions', 'activity'); $this->view->post_count = $table->select()->from($table, array('COUNT(*) AS count'))->query()->fetchColumn(); // comments $comment_count = 0; $table = Engine_Api::_()->getDbTable('comments', 'activity'); $comment_count += (int) $table->select()->from($table, array('COUNT(*) AS count'))->query()->fetchColumn(); $table = Engine_Api::_()->getDbTable('comments', 'core'); $comment_count += (int) $table->select()->from($table, array('COUNT(*) AS count'))->query()->fetchColumn(); $this->view->comment_count = $comment_count; // plugin hook $this->view->hooked_stats = array(); $events = Engine_Hooks_Dispatcher::getInstance()->callEvent('onStatistics'); $events_res = $events->getResponses(); if (is_array($events_res)) { $this->view->hooked_stats = $events_res; } }
public function onProcess() { // In this case, the step was placed before the account step. // Register a hook to this method for onUserCreateAfter if (!$this->_registry->user) { // Register temporary hook Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array('callback' => array($this, 'onProcess'))); return; } $user = $this->_registry->user; // Actual processing // Get selected package $packagesTable = Engine_Api::_()->getDbtable('packages', 'payment'); $package = $packagesTable->find($this->getSession()->data['package_id'])->current(); if (!$package) { throw new Engine_Exception('No subscription plan'); } $subscriptionsTable = Engine_Api::_()->getDbtable('subscriptions', 'payment'); // Insert the new temporary subscription $db = $subscriptionsTable->getAdapter(); $db->beginTransaction(); try { $subscription = $subscriptionsTable->createRow(); $subscription->setFromArray(array('package_id' => $package->package_id, 'user_id' => $user->getIdentity(), 'status' => 'initial', 'active' => false, 'creation_date' => new Zend_Db_Expr('NOW()'))); $subscription->save(); // If the package is free, let's set it active now and cancel the other if ($package->isFree()) { $subscription->setActive(true); $subscription->onPaymentSuccess(); //if( $currentSubscription ) { // $currentSubscription->cancel(); //} } $subscription_id = $subscription->subscription_id; $db->commit(); } catch (Exception $e) { $db->rollBack(); throw $e; } // Check if the subscription is ok if ($package->isFree() && $subscriptionsTable->check($user)) { return; } // Prepare subscription session $session = new Zend_Session_Namespace('Payment_Subscription'); $session->is_change = true; $session->user_id = $user->getIdentity(); $session->subscription_id = $subscription_id; }
public function onProcess() { // In this case, the step was placed before the account step. // Register a hook to this method for onUserCreateAfter if (!$this->_registry->user) { // Register temporary hook Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array('callback' => array($this, 'onProcess'))); return; } $user = $this->_registry->user; $data = $this->getSession()->data; $form = $this->getForm(); if (!$this->_skip && !$this->getSession()->skip) { if ($form->isValid($data)) { $values = $form->getValues(); Engine_Api::_()->getDbtable('invites', 'invite')->sendInvites($user, @$values['recipients'], @$values['message']); } } }
public function indexAction() { // License info $this->view->site = Engine_Api::_()->getApi('settings', 'core')->core_site; $this->view->license = Engine_Api::_()->getApi('settings', 'core')->core_license; // check if it is a trial license if (!Core_Form_Admin_Settings_License::validateKey($this->view->license['key'])) { $this->view->license['key'] = $this->view->htmlLink(array('action' => 'license-key'), $this->view->translate('Update License Key'), array('class' => 'smoothbox')); } // Get the core module version $this->view->coreVersion = Engine_Api::_()->getDbtable('modules', 'core')->select()->from('engine4_core_modules', 'version')->where('name = ?', 'core')->query()->fetchColumn(); // Statistics $statistics = array(); // views $statistics['core.views'] = array('label' => 'Page Views', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.views', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.views')); // signups $statistics['user.creations'] = array('label' => 'Members', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.creations', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.creations')); // logins $statistics['user.logins'] = array('label' => 'Sign-ins', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.logins', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.logins')); // messages $statistics['messages.creations'] = array('label' => 'Private Messages', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('messages.creations', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('messages.creations')); // friendships // @todo this only works properly for two-way, verified friendships for now $statistics['user.friendships'] = array('label' => 'Friendships', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.friendships', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('user.friendships')); // comments // @todo this doesn't include activity feed, users, group, or events for now $statistics['core.comments'] = array('label' => 'Comments', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.comments', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.comments')); // reports $statistics['core.reports'] = array('label' => 'Abuse Reports', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.reports', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.reports')); // announcements $statistics['announcement.creations'] = array('label' => 'Announcements', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('announcement.creations', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('announcement.creations')); // emails $statistics['core.emails'] = array('label' => 'Emails Sent', 'today' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.emails', 'day'), 'total' => Engine_Api::_()->getDbtable('statistics', 'core')->getTotal('core.emails')); // Hooks $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onAdminStatistics'); $statistics += (array) $event->getResponses(); // Online users $onlineTable = Engine_Api::_()->getDbtable('online', 'user'); $onlineUserCount = $onlineTable->select()->from($onlineTable->info('name'), new Zend_Db_Expr('COUNT(DISTINCT user_id)'))->where('user_id > ?', 0)->where('active > ?', new Zend_Db_Expr('DATE_SUB(NOW(),INTERVAL 20 MINUTE)'))->query()->fetchColumn(0); $statistics['users.online'] = array('label' => 'Online Members', 'today' => null, 'total' => $onlineUserCount); // Assign $this->view->statistics = $statistics; }
/** * onBeforeActivityNotificationsUpdate */ public function hookRouter(Zend_Controller_Request_Abstract $request) { $api = Engine_Api::_(); $module = $request -> getModuleName(); $controller = $request -> getControllerName(); $action = $request -> getActionName(); $allows = array('onBeforeActivityNotificationsUpdate' => 1, ); $eventName = sprintf('onBefore%s%s%s', $api -> inflect($module), $api -> inflect($controller), $api -> inflect($action)); if (isset($allows[$eventName]) && $allows[$eventName]) { //@header('X-Event:' . $eventName); $event = Engine_Hooks_Dispatcher::getInstance() -> callEvent($eventName, $request); } return; }
public function indexAction() { // Notifications $event = Engine_Hooks_Dispatcher::_()->callEvent('getAdminNotifications'); $this->view->notifications = $event->getResponses(); // Users $userTable = Engine_Api::_()->getItemTable('user'); $select = new Zend_Db_Select($userTable->getAdapter()); $select->from($userTable->info('name'), 'COUNT(user_id) as count'); $data = $select->query()->fetch(); $this->view->userCount = (int) $data['count']; // Reports $reportTable = Engine_Api::_()->getDbtable('reports', 'core'); $select = new Zend_Db_Select($reportTable->getAdapter()); $select->from($reportTable->info('name'), 'COUNT(report_id) as count')->where('`read` = ?', 0); $data = $select->query()->fetch(); $this->view->reportCount = (int) $data['count']; // Plugins $moduleTable = Engine_Api::_()->getDbtable('modules', 'core'); $select = new Zend_Db_Select($moduleTable->getAdapter()); $select->from($moduleTable->info('name'), 'COUNT(TRUE) as count')->where('type = ?', 'extra'); $data = $select->query()->fetch(); $this->view->pluginCount = (int) $data['count']; }
public function editAction() { $id = $this->_getParam('id', null); $user = Engine_Api::_()->getItem('user', $id); $userLevel = Engine_Api::_()->getItem('authorization_level', $user->level_id); $viewer = Engine_Api::_()->user()->getViewer(); $viewerLevel = Engine_Api::_()->getItem('authorization_level', $viewer->level_id); $superAdminLevels = Engine_Api::_()->getItemTable('authorization_level')->fetchAll(array('flag = ?' => 'superadmin')); if (!$user || !$userLevel || !$viewer || !$viewerLevel) { return $this->_helper->redirector->gotoRoute(array('action' => 'index')); } $this->view->user = $user; $this->view->form = $form = new User_Form_Admin_Manage_Edit(array('userIdentity' => $id)); // Do not allow editing level if the last superadmin if ($userLevel->flag == 'superadmin' && count(Engine_Api::_()->user()->getSuperAdmins()) == 1) { $form->removeElement('level_id'); } // Do not allow admins to change to super admin if ($viewerLevel->flag != 'superadmin' && $form->getElement('level_id')) { if ($userLevel->flag == 'superadmin') { $form->removeElement('level_id'); } else { foreach ($superAdminLevels as $superAdminLevel) { unset($form->getElement('level_id')->options[$superAdminLevel->level_id]); } } } // Get values $values = $user->toArray(); unset($values['password']); if (_ENGINE_ADMIN_NEUTER) { unset($values['email']); } // Get networks $select = Engine_Api::_()->getDbtable('membership', 'network')->getMembershipsOfSelect($user); $networks = Engine_Api::_()->getDbtable('networks', 'network')->fetchAll($select); $values['network_id'] = $oldNetworks = array(); foreach ($networks as $network) { $values['network_id'][] = $oldNetworks[] = $network->getIdentity(); } $table = Engine_Api::_()->getApi('core', 'fields')->getTable('user', 'values'); $select = $table->select(); $select->where('field_id = ?', 1); $select->where('item_id = ?', $user->getIdentity()); $value_profile = $table->fetchRow($select); if ($value_profile) { $profile_id = $value_profile->value; } if ($profile_id == null) { $profile_id = 1; } $values['profile_type'] = $profile_id; // Populate form $form->populate($values); // Check method/valid if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($this->getRequest()->getPost())) { return; } $values = $form->getValues(); // Check password validity if (empty($values['password']) && empty($values['password_conf'])) { unset($values['password']); unset($values['password_conf']); } else { if ($values['password'] != $values['password_conf']) { return $form->getElement('password')->addError('Passwords do not match.'); } else { unset($values['password_conf']); } } // Process $oldValues = $user->toArray(); // Set new network $userNetworks = $values['network_id']; unset($values['network_id']); if ($userNetworks == NULL) { $userNetworks = array(); } $joinIds = array_diff($userNetworks, $oldNetworks); foreach ($joinIds as $id) { $network = Engine_Api::_()->getItem('network', $id); $network->membership()->addMember($user)->setUserApproved($user)->setResourceApproved($user); } $leaveIds = array_diff($oldNetworks, $userNetworks); foreach ($leaveIds as $id) { $network = Engine_Api::_()->getItem('network', $id); if (!is_null($network)) { $network->membership()->removeMember($user); } } // Check for null usernames if ($values['username'] == '') { // If value is "NULL", then set to zend Null $values['username'] = new Zend_Db_Expr("NULL"); } $user->setFromArray($values); $user->save(); // Send a notification that the account has been approved if (!$oldValues['enabled'] && $values['enabled']) { Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'user_account_approved', array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => time(), 'recipient_title' => $user->getTitle(), 'recipient_link' => $user->getHref(), 'recipient_photo' => $user->getPhotoUrl('thumb.icon'), 'object_link' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true))); // Send hook to add activity Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserEnable', $user); } else { if ($oldValues['enabled'] && !$values['enabled']) { // @todo ? } } $newProfileType = $values['profile_type']; if ($value_profile) { $value_profile->value = $newProfileType; $value_profile->save(); } // Forward return $this->_forward('success', 'utility', 'core', array('smoothboxClose' => true, 'parentRefresh' => true, 'format' => 'smoothbox', 'messages' => array('Your changes have been saved.'))); }
public function verifyAction() { $verify = $this->_getParam('verify'); $email = $this->_getParam('email'); $settings = Engine_Api::_()->getApi('settings', 'core'); // No code or email if (!$verify || !$email) { $this->view->status = false; $this->view->error = $this->view->translate('The email or verification code was not valid.'); return; } // Get verify user $userTable = Engine_Api::_()->getDbtable('users', 'user'); $user = $userTable->fetchRow($userTable->select()->where('email = ?', $email)); if (!$user || !$user->getIdentity()) { $this->view->status = false; $this->view->error = $this->view->translate('The email does not match an existing user.'); return; } // If the user is already verified, just redirect if ($user->verified) { $this->view->status = true; return; } // Get verify row $verifyTable = Engine_Api::_()->getDbtable('verify', 'user'); $verifyRow = $verifyTable->fetchRow($verifyTable->select()->where('user_id = ?', $user->getIdentity())); if (!$verifyRow || $verifyRow->code != $verify) { $this->view->status = false; $this->view->error = $this->view->translate('There is no verification info for that user.'); return; } // Process $db = $verifyTable->getAdapter(); $db->beginTransaction(); try { $verifyRow->delete(); $user->verified = 1; $user->save(); if ($user->enabled) { Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserEnable', $user); } $db->commit(); } catch (Exception $e) { $db->rollBack(); throw $e; } $this->view->status = true; }
public function logoutAction() { // Check if already logged out $viewer = Engine_Api::_()->user()->getViewer(); if (!$viewer->getIdentity()) { $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('You are already logged out.'); if (null === $this->_helper->contextSwitch->getCurrentContext()) { $this->_helper->redirector->gotoRoute(array(), 'default', true); } return; } // Run logout hook $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLogoutBefore', $viewer); // Test activity @todo remove Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $viewer, 'logout'); // Update online status $onlineTable = Engine_Api::_()->getDbtable('online', 'user')->delete(array('user_id = ?' => $viewer->getIdentity())); // Logout Engine_Api::_()->user()->getAuth()->clearIdentity(); if (!empty($_SESSION['login_id'])) { Engine_Api::_()->getDbtable('logins', 'user')->update(array('active' => false), array('login_id = ?' => $_SESSION['login_id'])); unset($_SESSION['login_id']); } // Run logout hook $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLogoutAfter', $viewer); $doRedirect = true; // Clear twitter/facebook session info // facebook api $facebookTable = Engine_Api::_()->getDbtable('facebook', 'user'); $facebook = $facebookTable->getApi(); $settings = Engine_Api::_()->getDbtable('settings', 'core'); if ($facebook && 'none' != $settings->core_facebook_enable) { /* $logoutUrl = $facebook->getLogoutUrl(array( 'next' => 'http://' . $_SERVER['HTTP_HOST'] . $this->view->url(array(), 'default', true), )); */ if (method_exists($facebook, 'getAccessToken') && ($access_token = $facebook->getAccessToken())) { $doRedirect = false; // javascript will run to log them out of fb $this->view->appId = $facebook->getAppId(); $access_array = explode("|", $access_token); if ($session_key = $access_array[1]) { $this->view->fbSession = $session_key; } } try { $facebook->clearAllPersistentData(); } catch (Exception $e) { // Silence } } unset($_SESSION['facebook_lock']); unset($_SESSION['facebook_uid']); // twitter api /* $twitterTable = Engine_Api::_()->getDbtable('twitter', 'user'); $twitter = $twitterTable->getApi(); $twitterOauth = $twitterTable->getOauth(); if( $twitter && $twitterOauth ) { try { $result = $accountInfo = $twitter->account->end_session(); } catch( Exception $e ) { // Silence echo $e;die(); } } */ unset($_SESSION['twitter_lock']); unset($_SESSION['twitter_token']); unset($_SESSION['twitter_secret']); unset($_SESSION['twitter_token2']); unset($_SESSION['twitter_secret2']); // Response $this->view->status = true; $this->view->message = Zend_Registry::get('Zend_Translate')->_('You are now logged out.'); if ($doRedirect && null === $this->_helper->contextSwitch->getCurrentContext()) { return $this->_helper->redirector->gotoRoute(array(), 'default', true); } }
/** * Sets (or if param is not specified, resets) the current singleton instance * * @param Core_Model_Hooks_Dispatcher $instance - OPTIONAL * @return Core_Model_Hooks_Dispatcher */ public static function setInstance(Engine_Hooks_Dispatcher $instance = null) { if (null === $instance) { $instance = new self(); } self::$_instance = $instance; return self::$_instance; }
public function externalPhotoAction() { if (!$this->_helper->requireSubject()->isValid()) { return; } $user = Engine_Api::_()->core()->getSubject(); // Get photo $photo = Engine_Api::_()->getItemByGuid($this->_getParam('photo')); if (!$photo || !$photo instanceof Core_Model_Item_Collectible || empty($photo->photo_id)) { $this->_forward('requiresubject', 'error', 'core'); return; } if (!$photo->getCollection()->authorization()->isAllowed(null, 'view')) { $this->_forward('requireauth', 'error', 'core'); return; } // Make form $this->view->form = $form = new User_Form_Edit_ExternalPhoto(); $this->view->photo = $photo; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($this->getRequest()->getPost())) { return; } // Process $db = $user->getTable()->getAdapter(); $db->beginTransaction(); $photo_id; try { $photo_id = $photo->owner_id; } catch (Exception $e) { $photo_id = $photo->user_id; } try { if ($photo_id == $user->user_id) { // if it is your own album do not make copies of the image $user->photo_id = $photo->file_id; $user->save(); $newStorageFile = Engine_Api::_()->getItem('storage_file', $user->photo_id); } else { // else copy the photo into your own collection $user->setPhoto($photo); $newStorageFile = Engine_Api::_()->getItem('storage_file', $user->photo_id); // Insert activity $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $user, 'profile_photo_update', '{item:$subject} added a new profile photo.'); // Hooks to enable albums to work $event = Engine_Hooks_Dispatcher::_()->callEvent('onUserProfilePhotoUpload', array('user' => $user, 'file' => $newStorageFile)); $attachment = $event->getResponse(); if (!$attachment) { $attachment = $newStorageFile; } // We have to attach the user himself w/o album plugin Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $attachment); } $db->commit(); return $this->_forward('success', 'utility', 'core', array('messages' => array(Zend_Registry::get('Zend_Translate')->_('Set as profile photo')), 'smoothboxClose' => true)); } catch (Exception $e) { $db->rollBack(); throw $e; } }
protected function createAccount() { if (!isset($_SESSION['SocialConnect_SignUp_Data'])) { return; } $data = $_SESSION['SocialConnect_SignUp_Data']; unset($_SESSION['SocialConnect_SignUp_Data']); unset($_SESSION['User_Plugin_Signup_Account']); unset($_SESSION['User_Plugin_Signup_Fields']); unset($_SESSION['User_Plugin_Signup_Photo']); unset($_SESSION['User_Plugin_Signup_Invite']); unset($_SESSION['Contactimporter_Plugin_Signup_Invite']); try { $settings = Engine_Api::_()->getApi('settings', 'core'); $userTable = Engine_Api::_()->getItemTable('user'); // check username if (isset($data['username'])) { $select = $userTable->select()->where('username = ?', $data['username']); $accountExist = $userTable->fetchRow($select); if ($accountExist) { $data['username'] = $data['username'] . '_' . time(); } } $emailadmin = $settings->getSetting('user.signup.adminemail', 0) == 1; if ($emailadmin) { // the signup notification is emailed to the first SuperAdmin by default $users_select = $userTable->select()->where('level_id = ?', 1)->where('enabled >= ?', 1); $super_admin = $userTable->fetchRow($users_select); } $random = false; if (!$settings->getSetting('socialconnect.inputpassword', 0)) { $data['password'] = Engine_Api::_()->user()->randomPass(10); $random = true; } $core_locale = $settings->core_locale; $data['timezone'] = $core_locale['timezone']; //creating user model $user = $userTable->createRow(); $user->setFromArray($data); $user->save(); $user->setDisplayName(array('first_name' => $data['first_name'], 'last_name' => $data['last_name'])); Engine_Api::_()->user()->setViewer($user); // Increment signup counter Engine_Api::_()->getDbtable('statistics', 'core')->increment('user.creations'); if ($user->verified && $user->enabled) { // Create activity for them Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $user, 'signup'); // Set user as logged in if not have to verify email Engine_Api::_()->user()->getAuth()->getStorage()->write($user->getIdentity()); } foreach ($data as $k => $v) { if (is_string($v)) { $data[$k] = html_entity_decode($v, ENT_QUOTES, 'UTF-8'); } } $topStructure = Engine_Api::_()->fields()->getFieldStructureTop('user'); $formArgs = array(); if (count($topStructure) >= 1 && $topStructure[0]->getChild()->type == 'profile_type') { $profileTypeField = $topStructure[0]->getChild(); $options = $profileTypeField->getOptions(); $formArgs = array('topLevelId' => $profileTypeField->field_id, 'topLevelValue' => $options[0]->option_id); } if ($formArgs) { $struct = Engine_Api::_()->fields()->getFieldsStructureFull($user, $formArgs['topLevelId'], $formArgs['topLevelValue']); $arr_data = array(); foreach ($struct as $fskey => $map) { if (isset($data[$fskey])) { $arr_data[$fskey] = $data[$fskey]; } } $profileTypeValue = $formArgs['topLevelValue']; $values = Engine_Api::_()->fields()->getFieldsValues($user); $valueRow = $values->createRow(); $valueRow->field_id = $profileTypeField->field_id; $valueRow->item_id = $user->getIdentity(); $valueRow->value = $profileTypeValue; $valueRow->save(); foreach ($arr_data as $key => $value) { $parts = explode('_', $key); if (count($parts) != 3) { continue; } list($parent_id, $option_id, $field_id) = $parts; // Array mode if (is_array($value)) { // Lookup $valueRows = $values->getRowsMatching(array('field_id' => $field_id, 'item_id' => $user->getIdentity())); // Delete all $prevPrivacy = null; foreach ($valueRows as $valueRow) { if (!empty($valueRow->privacy)) { $prevPrivacy = $valueRow->privacy; } $valueRow->delete(); } // Insert all $indexIndex = 0; if (is_array($value) || !empty($value)) { foreach ((array) $value as $singleValue) { $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $user->getIdentity(); $valueRow->index = $indexIndex++; $valueRow->value = $singleValue; $valueRow->save(); } } else { $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $user->getIdentity(); $valueRow->index = 0; $valueRow->value = ''; $valueRow->save(); } } else { // Lookup $valueRow = $values->getRowMatching(array('field_id' => $field_id, 'item_id' => $user->getIdentity(), 'index' => 0)); // Create if missing $isNew = false; if (!$valueRow) { $isNew = true; $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $user->getIdentity(); } $valueRow->value = htmlspecialchars($value); $valueRow->save(); } } // Update search table Engine_Api::_()->getApi('core', 'fields')->updateSearch($user, $values); // Fire on save hook Engine_Hooks_Dispatcher::getInstance()->callEvent('onFieldsValuesSave', array('item' => $user, 'values' => $values)); // Run post signup hook $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserSignupAfter', $user); $mailType = null; $mailParams = array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => time(), 'recipient_title' => $user->getTitle(), 'recipient_link' => $user->getHref(), 'recipient_photo' => $user->getPhotoUrl('thumb.icon'), 'object_link' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true)); // Add password to email if necessary if ($random) { $mailParams['password'] = $data['password']; } // Mail stuff switch ($settings->getSetting('user.signup.verifyemail', 0)) { case 0: if ($random) { $mailType = 'core_welcome_password'; } if ($emailadmin) { $mailAdminType = 'notify_admin_user_signup'; $mailAdminParams = array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => date("F j, Y, g:i a"), 'recipient_title' => $super_admin->displayname, 'object_title' => $user->displayname, 'object_link' => $user->getHref()); } break; case 1: // send welcome email $mailType = $random ? 'core_welcome_password' : 'core_welcome'; if ($emailadmin) { $mailAdminType = 'notify_admin_user_signup'; $mailAdminParams = array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => date("F j, Y, g:i a"), 'recipient_title' => $super_admin->displayname, 'object_title' => $user->getTitle(), 'object_link' => $user->getHref()); } break; case 2: // verify email before enabling account $verify_table = Engine_Api::_()->getDbtable('verify', 'user'); $verify_row = $verify_table->createRow(); $verify_row->user_id = $user->getIdentity(); $verify_row->code = md5($user->email . $user->creation_date . $settings->getSetting('core.secret', 'staticSalt') . (string) rand(1000000, 9999999)); $verify_row->date = $user->creation_date; $verify_row->save(); $mailType = $random ? 'core_verification_password' : 'core_verification'; $mailParams['object_link'] = Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'verify', 'email' => $user->email, 'verify' => $verify_row->code), 'user_signup', true); if ($emailadmin) { $mailAdminType = 'notify_admin_user_signup'; $mailAdminParams = array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => date("F j, Y, g:i a"), 'recipient_title' => $super_admin->displayname, 'object_title' => $user->getTitle(), 'object_link' => $user->getHref()); } break; default: // do nothing break; } // Send Welcome E-mail if (isset($mailType) && $mailType) { Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, $mailType, $mailParams); } // Send Notify Admin E-mail if (isset($mailAdminType) && $mailAdminType) { Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, $mailAdminType, $mailAdminParams); } } return $user; } catch (Exception $e) { return; } }
public function onProcess() { // In this case, the step was placed before the account step. // Register a hook to this method for onUserCreateAfter if (!$this->_registry->user) { // Register temporary hook Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array('callback' => array($this, 'onProcess'))); return; } $user = $this->_registry->user; // Preload profile type field stuff $profileTypeField = $this->getProfileTypeField(); if ($profileTypeField) { $accountSession = new Zend_Session_Namespace('User_Plugin_Signup_Account'); $profileTypeValue = @$accountSession->data['profile_type']; if ($profileTypeValue) { $values = Engine_Api::_()->fields()->getFieldsValues($user); $valueRow = $values->createRow(); $valueRow->field_id = $profileTypeField->field_id; $valueRow->item_id = $user->getIdentity(); $valueRow->value = $profileTypeValue; $valueRow->save(); } else { $topStructure = Engine_Api::_()->fields()->getFieldStructureTop('user'); if (count($topStructure) == 1 && $topStructure[0]->getChild()->type == 'profile_type') { $profileTypeField = $topStructure[0]->getChild(); $options = $profileTypeField->getOptions(); if (count($options) == 1) { $values = Engine_Api::_()->fields()->getFieldsValues($user); $valueRow = $values->createRow(); $valueRow->field_id = $profileTypeField->field_id; $valueRow->item_id = $user->getIdentity(); $valueRow->value = $options[0]->option_id; $valueRow->save(); } } } } // Save them values $form = $this->getForm()->setItem($user); $form->setProcessedValues($this->getSession()->data); $form->saveValues(); $aliasValues = Engine_Api::_()->fields()->getFieldsValuesByAlias($user); $user->setDisplayName($aliasValues); $user->save(); // Send Welcome E-mail if (isset($this->_registry->mailType) && $this->_registry->mailType) { $mailType = $this->_registry->mailType; $mailParams = $this->_registry->mailParams; Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, $mailType, $mailParams); } // Send Notify Admin E-mail if (isset($this->_registry->mailAdminType) && $this->_registry->mailAdminType) { $mailAdminType = $this->_registry->mailAdminType; $mailAdminParams = $this->_registry->mailAdminParams; Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, $mailAdminType, $mailAdminParams); } }
public function onProcess() { // In this case, the step was placed before the account step. // Register a hook to this method for onUserCreateAfter if (!$this->_registry->user) { // Register temporary hook Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array('callback' => array($this, 'onProcess'))); return; } $user = $this->_registry->user; // Remove old key unset($_SESSION['TemporaryProfileImg']); unset($_SESSION['TemporaryProfileImgProfile']); unset($_SESSION['TemporaryProfileImgSquare']); // Process $data = $this->getSession()->data; $params = array('parent_type' => 'user', 'parent_id' => $user->user_id); if (!$this->_skip && !$this->getSession()->skip && !empty($this->getSession()->tmp_file_id)) { // Save $storage = Engine_Api::_()->getItemTable('storage_file'); // Update info $iMain = $storage->getFile($this->getSession()->tmp_file_id); $iMain->setFromArray($params); $iMain->save(); $iMain->updatePath(); $iProfile = $storage->getFile($this->getSession()->tmp_file_id, 'thumb.profile'); $iProfile->setFromArray($params); $iProfile->save(); $iProfile->updatePath(); $iNormal = $storage->getFile($this->getSession()->tmp_file_id, 'thumb.normal'); $iNormal->setFromArray($params); $iNormal->save(); $iNormal->updatePath(); $iSquare = $storage->getFile($this->getSession()->tmp_file_id, 'thumb.icon'); $iSquare->setFromArray($params); $iSquare->save(); $iSquare->updatePath(); // Update row $user->photo_id = $iMain->file_id; $user->save(); if ($this->getSession()->coordinates) { $this->_resizeThumbnail($user); } } }
/** * Add an action-privacy binding * * @param int $action_id * @param string $type * @param Core_Model_Item_Abstract $subject * @param Core_Model_Item_Abstract $object * @return int The insert id */ public function addActivityBindings($action) { // Get privacy bindings $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('addActivity', array('subject' => $action->getSubject(), 'object' => $action->getObject(), 'type' => $action->type)); // Add privacy bindings $streamTable = Engine_Api::_()->getDbtable('stream', 'activity'); foreach ((array) $event->getResponses() as $response) { if (isset($response['target'])) { $target_type = $response['target']; $target_id = 0; } else { if (isset($response['type']) && isset($response['identity'])) { $target_type = $response['type']; $target_id = $response['identity']; } else { continue; } } $streamTable->insert(array('action_id' => $action->action_id, 'type' => $action->type, 'target_type' => (string) $target_type, 'target_id' => (int) $target_id, 'subject_type' => $action->subject_type, 'subject_id' => $action->subject_id, 'object_type' => $action->object_type, 'object_id' => $action->object_id)); } return $this; }
public function editMeta($field, $params) { if (!$field instanceof Fields_Model_Meta) { throw new Fields_Model_Exception('Not a field'); } // Get info $info = Engine_Api::_()->fields()->getFieldInfo($params['type']); // Set some other stuff if (@$info['category'] != 'generic') { $params['alias'] = $params['type']; } else { $params['alias'] = ""; } // Diff $params['config'] = array_diff_key($params, $field->toArray()); // Get keys not in row for config //die(print_r($params,true)); $field->setFromArray($params); $field->save(); // Do search Engine_Api::_()->fields()->getTable($this->getFieldType(), 'search')->checkSearchIndex($field); // Events $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onFieldMetaEdit', $field); $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onFieldMetaEdit_' . $this->getFieldType(), $field); // Update cache //$this->_setCache($this->_fieldMeta); // Eh, just flush cache $this->_flushCache(); return $field; }
public function multiModifyAction() { $this->view->form = $form = new User_Form_Admin_Manage_Delete(); if ($this->getRequest()->isPost()) { $values = $this->getRequest()->getPost(); foreach ($values as $key => $value) { if ($key == 'modify_' . $value) { $user = Engine_Api::_()->getItem('user', (int) $value); if ($values['submit_button'] == 'delete') { if ($user->level_id != 1) { $bannedUsernamesTable = Engine_Api::_()->getDbtable('bannedusernames', 'ynbanmem'); $bannedEmailsTable = Engine_Api::_()->getDbtable('bannedemails', 'ynbanmem'); $bannedIpsTable = Engine_Api::_()->getDbtable('bannedips', 'ynbanmem'); $extraInfoTable = Engine_Api::_()->getDbtable('extrainfo', 'ynbanmem'); $bannedUsername = $bannedUsernamesTable->select()->where('username = ?', $user->username)->query()->fetchAll(); $bannedEmail = $bannedEmailsTable->select()->where('email = ?', $user->email)->query()->fetchAll(); if (count($bannedUsername) != 0) { $exist1 = $extraInfoTable->select()->where('banned_id = ?', $bannedUsername[0]['bannedusername_id'])->where('banned_type = ?', 0)->query()->fetch(); if (count($exist1) != 0) { $extraInfoTable->delete(array('banned_id = ?' => $bannedUsername[0]['bannedusername_id'], 'banned_type = ?' => 0)); } $bannedUsernamesTable->delete(array('bannedusername_id = ?' => $bannedUsername[0]['bannedusername_id'])); } if (count($bannedEmail) != 0) { $exist2 = $extraInfoTable->select()->where('banned_id = ?', $bannedEmail[0]['bannedemail_id'])->where('banned_type = ?', 2)->query()->fetch(); if (count($exist2) != 0) { $extraInfoTable->delete(array('banned_id = ?' => $bannedEmail[0]['bannedemail_id'], 'banned_type = ?' => 2)); } $bannedEmailsTable->delete(array('bannedemail_id = ?' => $bannedEmail[0]['bannedemail_id'])); } $user->delete(); } } else { if ($values['submit_button'] == 'approve') { $old_status = $user->enabled; $user->enabled = 1; $user->approved = 1; $user->save(); // ORIGINAL WAY // Send a notification that the account was not approved previously if ($old_status == 0) { Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'user_account_approved', array('host' => $_SERVER['HTTP_HOST'], 'email' => $user->email, 'date' => time(), 'recipient_title' => $user->getTitle(), 'recipient_link' => $user->getHref(), 'recipient_photo' => $user->getPhotoUrl('thumb.icon'), 'object_link' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true))); // Send hook to add activity Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserEnable', $user); } } } } } } return $this->_helper->redirector->gotoRoute(array('controller' => 'index', 'action' => 'users'), 'ynbanmem_general'); }
public function getActivityAbout(Core_Model_Item_Abstract $about, User_Model_User $user, array $params = array()) { // Proc args extract($this->_getInfo($params)); // action_id, limit, min_id, max_id, actionFilter, filterValue // Prepare main query $streamTable = Engine_Api::_()->getDbtable('stream', 'activity'); $streamName = $streamTable->info('name'); $actionTableName = $this->info('name'); $db = $streamTable->getAdapter(); $union = new Zend_Db_Select($db); // Prepare action types $masterActionTypes = Engine_Api::_()->getDbtable('actionTypes', 'activity')->getActionTypes(); $subjectActionTypes = array(); $objectActionTypes = array(); // Filter types based on displayable foreach ($masterActionTypes as $type) { if ($about->getType() == 'event' && Engine_Api::_()->hasItemType('event') || $about->getType() == 'group' && Engine_Api::_()->hasItemType('group') || $about->getType() == 'ynbusinesspages_business' && Engine_Api::_()->hasItemType('ynbusinesspages_business')) { if ($actionFilter == 'owner' && isset($type->is_object_thumb) && !$type->is_object_thumb) { continue; } if ($actionFilter == 'membership' && isset($type->is_object_thumb) && $type->is_object_thumb) { continue; } } if ($type->displayable & 1) { $subjectActionTypes[] = $type->type; } if ($type->displayable & 2) { $objectActionTypes[] = $type->type; } } // Filter types based on user request if (isset($showTypes) && is_array($showTypes) && !empty($showTypes)) { $subjectActionTypes = array_intersect($subjectActionTypes, $showTypes); $objectActionTypes = array_intersect($objectActionTypes, $showTypes); } else { if (isset($hideTypes) && is_array($hideTypes) && !empty($hideTypes)) { $subjectActionTypes = array_diff($subjectActionTypes, $hideTypes); $objectActionTypes = array_diff($objectActionTypes, $hideTypes); } } // Nothing to show if (empty($subjectActionTypes) && empty($objectActionTypes)) { return null; } if (empty($subjectActionTypes)) { $subjectActionTypes = null; } else { if (count($subjectActionTypes) == count($masterActionTypes)) { $subjectActionTypes = true; } else { $subjectActionTypes = "'" . join("', '", $subjectActionTypes) . "'"; } } if (empty($objectActionTypes)) { $objectActionTypes = null; } else { if (count($objectActionTypes) == count($masterActionTypes)) { $objectActionTypes = true; } else { $objectActionTypes = "'" . join("', '", $objectActionTypes) . "'"; } } // Prepare sub queries $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('getActivity', array('for' => $user, 'about' => $about)); $responses = (array) $event->getResponses(); if (empty($responses)) { return null; } $friendsFlage = false; $action_ids = array(); // Filter by hashtag if ($actionFilter == 'hashtag' && !empty($filterValue)) { $action_ids = Engine_Api::_()->getDbtable('hashtags', 'ynfeed')->getHashtagFeeds($filterValue, array(), array('limit' => $limit, 'max_id' => $max_id)); if (empty($action_ids)) { return null; } } // Filter by login as business post if ($actionFilter == 'business') { $select = $this->select()->where('`subject_type` = ?', 'ynbusinesspages_business')->where('subject_id', $about->getIdentity())->limit($limit); if (null !== $max_id) { $select->where('action_id <= ?', $max_id); } $data = $select->query()->fetchAll(); foreach ($data as $row) { $action_ids[] = $row['action_id']; } if (empty($action_ids)) { return null; } } $member_ids = array(); if ($actionFilter == 'owner') { if ($about instanceof User_Model_User) { $member_ids[] = $about->getIdentity(); } elseif ($about instanceof Group_Model_Group || $about instanceof Advgroup_Model_Group) { $objectParent = $about->getParent('user'); if ($objectParent instanceof User_Model_User) { $member_ids[] = $objectParent->getIdentity(); } } else { $objectParent = $about->getParent('user'); if ($objectParent instanceof User_Model_User) { $member_ids[] = $objectParent->getIdentity(); } } } elseif ($actionFilter == 'officers') { if ($about instanceof Group_Model_Group || $about instanceof Advgroup_Model_Group) { $objectParent = $about->getParent('user'); if ($objectParent instanceof User_Model_User) { $member_ids[] = $objectParent->getIdentity(); } foreach ($about->getOfficerList()->getAll() as $value) { $member_ids[] = $value->child_id; } } } elseif ($actionFilter == 'admins') { if ($about instanceof Ynbusinesspages_Model_Business) { $objectParent = $about->getParent('user'); if ($objectParent instanceof User_Model_User) { $member_ids[] = $objectParent->getIdentity(); } foreach ($about->getAdminList()->getAll() as $value) { $member_ids[] = $value->child_id; } } } elseif ($actionFilter == 'membership') { if (in_array($about->getType(), array('event', 'group', 'ynbusinesspages_business'))) { $members = $about->membership()->getMembers(true); foreach ($members as $member) { $member_ids[] = $member->getIdentity(); } } else { $member_ids = $user->membership()->getMembershipsOfIds(); } if (empty($member_ids)) { return array(); } } foreach ($responses as $response) { if (empty($response)) { continue; } // Target info $select = $streamTable->select()->from($streamTable->info('name'), 'action_id')->where('target_type = ?', $response['type']); if (empty($response['data'])) { // Simple $select->where('target_id = ?', 0); } else { if (is_scalar($response['data']) || count($response['data']) === 1) { // Single if (is_array($response['data'])) { list($response['data']) = $response['data']; } $select->where('target_id = ?', $response['data']); } else { if (is_array($response['data'])) { // Array $select->where('target_id IN(?)', (array) $response['data']); } else { // Unknown continue; } } } // Add action_id/max_id/min_id if (null !== $action_id) { $select->where('action_id = ?', $action_id); } else { if (null !== $min_id) { $select->where('action_id >= ?', $min_id); } else { if (null !== $max_id) { $select->where('action_id <= ?', $max_id); } } } // Add order/limit $select->order('action_id DESC')->limit($limit); if (!empty($action_ids)) { $select->where($streamName . '.action_id IN(?)', (array) $action_ids); } // Add subject to main query $selectSubject = clone $select; if ($subjectActionTypes !== null) { if ($subjectActionTypes !== true) { $selectSubject->where('type IN(' . $subjectActionTypes . ')'); } $selectSubject->where('subject_type = ?', $about->getType())->where('subject_id = ?', $about->getIdentity()); if (!empty($member_ids)) { $selectSubject->where('object_type = ?', 'user')->where('object_id IN (?)', (array) $member_ids); } $union->union(array('(' . $selectSubject->__toString() . ')')); } // Add object to main query $selectObject = clone $select; if ($objectActionTypes !== null) { if ($objectActionTypes !== true) { $selectObject->where('type IN(' . $objectActionTypes . ')'); } $selectObject->where('object_type = ?', $about->getType())->where('object_id = ?', $about->getIdentity()); if (!empty($member_ids)) { $selectObject->where('subject_type = ?', 'user')->where('subject_id IN (?)', (array) $member_ids); } $union->union(array('(' . $selectObject->__toString() . ')')); // (string) not work before PHP 5.2.0 } } // Finish main query $union->order('action_id DESC')->limit($limit); // Get actions $actions = $db->fetchAll($union); // Process ids $ids = array(); if (in_array($actionFilter, array('all', 'posts')) && $action_id) { $tag_ids = Engine_Api::_()->ynfeed()->getTaggedBaseActionIds($user, array('min' => $min_id, 'max' => $max_id)); if (in_array($action_id, $tag_ids)) { $ids[] = $action_id; } } // No visible actions if (empty($actions) && empty($ids)) { return null; } // Process ids foreach ($actions as $data) { $ids[] = $data['action_id']; } $ids = array_unique($ids); // Finally get activity return $this->fetchAll($this->select()->where('action_id IN(' . join(',', $ids) . ')')->order('action_id DESC')->limit($limit)); }
/** * Process an IPN * * @param Engine_Payment_Ipn $ipn * @return Engine_Payment_Plugin_Abstract */ public function onIpn(Engine_Payment_Ipn $ipn) { $rawData = $ipn->getRawData(); $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment'); $transactionsTable = Engine_Api::_()->getDbtable('transactions', 'payment'); // Find transactions ------------------------------------------------------- $transactionId = null; $transaction = null; // Fetch by invoice_id if (!empty($rawData['invoice_id'])) { $transaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $rawData['invoice_id'])); } if ($transaction && !empty($transaction->gateway_transaction_id)) { $transactionId = $transaction->gateway_transaction_id; } else { $transactionId = @$rawData['invoice_id']; } // Fetch order ------------------------------------------------------------- $order = null; // Get order by vendor_order_id if (!$order && !empty($rawData['vendor_order_id'])) { $order = $ordersTable->find($rawData['vendor_order_id'])->current(); } // Get order by invoice_id if (!$order && $transactionId) { $order = $ordersTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $transactionId)); } // Get order by sale_id if (!$order && !empty($rawData['sale_id'])) { $order = $ordersTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_order_id = ?' => $rawData['sale_id'])); } // Get order by order_id through transaction if (!$order && $transaction && !empty($transaction->order_id)) { $order = $ordersTable->find($transaction->order_id)->current(); } // Update order with order/transaction id if necessary $orderUpdated = false; if (!empty($rawData['invoice_id']) && empty($order->gateway_transaction_id)) { $orderUpdated = true; $order->gateway_transaction_id = $rawData['invoice_id']; } if (!empty($rawData['sale_id']) && empty($order->gateway_order_id)) { $orderUpdated = true; $order->gateway_order_id = $rawData['sale_id']; } if ($orderUpdated) { $order->save(); } // Process generic IPN data ------------------------------------------------ // Build transaction info if (!empty($rawData['invoice_id'])) { $transactionData = array('gateway_id' => $this->_gatewayInfo->gateway_id); // Get timestamp if (!empty($rawData['payment_date'])) { $transactionData['timestamp'] = date('Y-m-d H:i:s', strtotime($rawData['timestamp'])); } else { $transactionData['timestamp'] = new Zend_Db_Expr('NOW()'); } // Get amount if (!empty($rawData['invoice_list_amount'])) { $transactionData['amount'] = $rawData['invoice_list_amount']; } else { if ($transaction) { $transactionData['amount'] = $transaction->amount; } else { if (!empty($rawData['item_list_amount_1'])) { // For recurring success $transactionData['amount'] = $rawData['item_list_amount_1']; } } } // Get currency if (!empty($rawData['list_currency'])) { $transactionData['currency'] = $rawData['list_currency']; } else { if ($transaction) { $transactionData['currency'] = $transaction->currency; } } // Get order/user if ($order) { $transactionData['user_id'] = $order->user_id; $transactionData['order_id'] = $order->order_id; } // Get transactions if ($transactionId) { $transactionData['gateway_transaction_id'] = $transactionId; } if (!empty($rawData['sale_id'])) { $transactionData['gateway_order_id'] = $rawData['sale_id']; } // Get payment_status if (!empty($rawData['invoice_status'])) { if ($rawData['invoice_status'] == 'declined') { $transactionData['type'] = 'payment'; $transactionData['state'] = 'failed'; } else { if ($rawData['fraud_status'] == 'fail') { $transactionData['type'] = 'payment'; $transactionData['state'] = 'failed-fraud'; } else { if ($rawData['fraud_status'] == 'wait') { $transactionData['type'] = 'payment'; $transactionData['state'] = 'pending-fraud'; } else { $transactionData['type'] = 'payment'; $transactionData['state'] = 'okay'; } } } } if ($transaction && ($transaction->type == 'refund' || $transaction->state == 'refunded')) { $transactionData['type'] = $transaction->type; $transactionData['state'] = $transaction->state; } // Special case for refund_issued $childTransactionData = array(); if ($rawData['message_type'] == 'REFUND_ISSUED') { $childTransactionData = $transactionData; $childTransactionData['gateway_parent_transaction_id'] = $childTransactionData['gateway_transaction_id']; //unset($childTransactionData['gateway_transaction_id']); // Should we unset this? $childTransactionData['amount'] = -$childTransactionData['amount']; $childTransactionData['type'] = 'refund'; $childTransactionData['state'] = 'refunded'; // Update parent transaction $transactionData['state'] = 'refunded'; } // Insert or update transactions if (!$transaction) { $transactionsTable->insert($transactionData); } else { unset($transactionData['timestamp']); $transaction->setFromArray($transactionData); $transaction->save(); } // Insert new child transaction if ($childTransactionData) { $childTransactionExists = $transactionsTable->select()->from($transactionsTable, new Zend_Db_Expr('TRUE'))->where('gateway_transaction_id = ?', $childTransactionData['gateway_transaction_id'])->where('type = ?', $childTransactionData['type'])->where('state = ?', $childTransactionData['state'])->limit(1)->query()->fetchColumn(); if (!$childTransactionExists) { $transactionsTable->insert($childTransactionData); } } } // Process specific IPN data ----------------------------------------------- if ($order) { $ipnProcessed = false; // Subscription IPN if ($order->source_type == 'payment_subscription') { $this->onSubscriptionTransactionIpn($order, $ipn); $ipnProcessed = true; } else { // Custom item-type IPN if (Engine_Api::_()->hasItemType($order->source_type) && !empty($order->source_id)) { $orderSourceObject = Engine_Api::_()->getItem($order->source_type, $order->source_id); if (method_exists($orderSourceObject, 'onPaymentIpn')) { $ipnProcessed = (bool) $orderSourceObject->onPaymentIpn($order, $ipn); } else { throw new Engine_Payment_Plugin_Exception(sprintf('Custom order ' . 'item "%s" does not implement onPaymentIpn() method', $order->source_type)); } } else { $eventName = 'onPaymentIpn_' . Engine_Api::inflect($order->source_type); $response = Engine_Hooks_Dispatcher::getInstance()->callEvent($eventName, array('order' => $order, 'ipn' => $ipn)); if (false != $response->getResponse()) { // Okay $ipnProcessed = true; } } } // Unknown IPN - could not be processed if (!$ipnProcessed) { throw new Engine_Payment_Plugin_Exception('Unknown order type for IPN'); } } else { throw new Engine_Payment_Plugin_Exception('Unknown or unsupported IPN ' . 'type, or missing transaction or order ID'); } return $this; }
protected function _initHooks() { $hooks = Engine_Hooks_Dispatcher::getInstance(); // Add module-configured routes $manifest = Zend_Registry::get('Engine_Manifest'); foreach ($manifest as $module => $config) { if (!isset($config['hooks'])) { continue; } $hooks->addEvents($config['hooks']); } return $hooks; }
public function externalPhotoAction() { if (!$this->_helper->requireSubject()->isValid()) { return; } $user = Engine_Api::_()->core()->getSubject(); // Get photo $photo = Engine_Api::_()->getItemByGuid($this->_getParam('photo')); if (!$photo || !$photo instanceof Core_Model_Item_Abstract || empty($photo->photo_id)) { $this->_forward('requiresubject', 'error', 'core'); return; } if (!$photo->authorization()->isAllowed(null, 'view')) { $this->_forward('requireauth', 'error', 'core'); return; } // Make form $this->view->form = $form = new User_Form_Edit_ExternalPhoto(); $this->view->photo = $photo; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($this->getRequest()->getPost())) { return; } // Process $db = $user->getTable()->getAdapter(); $db->beginTransaction(); try { // Get the owner of the photo $photoOwnerId = null; if (isset($photo->user_id)) { $photoOwnerId = $photo->user_id; } else { if (isset($photo->owner_id) && (!isset($photo->owner_type) || $photo->owner_type == 'user')) { $photoOwnerId = $photo->owner_id; } } // if it is from your own profile album do not make copies of the image if ($photo instanceof Album_Model_Photo && ($photoParent = $photo->getParent()) instanceof Album_Model_Album && $photoParent->owner_id == $photoOwnerId && $photoParent->type == 'profile') { // ensure thumb.icon and thumb.profile exist $newStorageFile = Engine_Api::_()->getItem('storage_file', $photo->file_id); $filesTable = Engine_Api::_()->getDbtable('files', 'storage'); if ($photo->file_id == $filesTable->lookupFile($photo->file_id, 'thumb.profile')) { try { $tmpFile = $newStorageFile->temporary(); $image = Engine_Image::factory(); $image->open($tmpFile)->resize(200, 400)->write($tmpFile)->destroy(); $iProfile = $filesTable->createFile($tmpFile, array('parent_type' => $user->getType(), 'parent_id' => $user->getIdentity(), 'user_id' => $user->getIdentity(), 'name' => basename($tmpFile))); $newStorageFile->bridge($iProfile, 'thumb.profile'); @unlink($tmpFile); } catch (Exception $e) { echo $e; die; } } if ($photo->file_id == $filesTable->lookupFile($photo->file_id, 'thumb.icon')) { try { $tmpFile = $newStorageFile->temporary(); $image = Engine_Image::factory(); $image->open($tmpFile); $size = min($image->height, $image->width); $x = ($image->width - $size) / 2; $y = ($image->height - $size) / 2; $image->resample($x, $y, $size, $size, 48, 48)->write($tmpFile)->destroy(); $iSquare = $filesTable->createFile($tmpFile, array('parent_type' => $user->getType(), 'parent_id' => $user->getIdentity(), 'user_id' => $user->getIdentity(), 'name' => basename($tmpFile))); $newStorageFile->bridge($iSquare, 'thumb.icon'); @unlink($tmpFile); } catch (Exception $e) { echo $e; die; } } // Set it $user->photo_id = $photo->file_id; $user->save(); // Insert activity // @todo maybe it should read "changed their profile photo" ? $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $user, 'profile_photo_update', '{item:$subject} changed their profile photo.'); if ($action) { // We have to attach the user himself w/o album plugin Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $photo); } } else { $user->setPhoto($photo); // Insert activity $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $user, 'profile_photo_update', '{item:$subject} added a new profile photo.'); // Hooks to enable albums to work $newStorageFile = Engine_Api::_()->getItem('storage_file', $user->photo_id); $event = Engine_Hooks_Dispatcher::_()->callEvent('onUserProfilePhotoUpload', array('user' => $user, 'file' => $newStorageFile)); $attachment = $event->getResponse(); if (!$attachment) { $attachment = $newStorageFile; } if ($action) { // We have to attach the user himself w/o album plugin Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $attachment); } } $db->commit(); } catch (Exception $e) { $db->rollBack(); throw $e; } return $this->_forward('success', 'utility', 'core', array('messages' => array(Zend_Registry::get('Zend_Translate')->_('Set as profile photo')), 'smoothboxClose' => true)); }
/** * Process an IPN * * @param Engine_Payment_Ipn $ipn * @return Engine_Payment_Plugin_Abstract */ public function onIpn(Engine_Payment_Ipn $ipn) { $rawData = $ipn->getRawData(); $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment'); $transactionsTable = Engine_Api::_()->getDbtable('transactions', 'payment'); // Find transactions ------------------------------------------------------- $transactionId = null; $parentTransactionId = null; $transaction = null; $parentTransaction = null; // Fetch by txn_id if (!empty($rawData['txn_id'])) { $transaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $rawData['txn_id'])); $parentTransaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_parent_transaction_id = ?' => $rawData['txn_id'])); } // Fetch by parent_txn_id if (!empty($rawData['parent_txn_id'])) { if (!$transaction) { $parentTransaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_parent_transaction_id = ?' => $rawData['parent_txn_id'])); } if (!$parentTransaction) { $parentTransaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $rawData['parent_txn_id'])); } } // Fetch by transaction->gateway_parent_transaction_id if ($transaction && !$parentTransaction && !empty($transaction->gateway_parent_transaction_id)) { $parentTransaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_parent_transaction_id = ?' => $transaction->gateway_parent_transaction_id)); } // Fetch by parentTransaction->gateway_transaction_id if ($parentTransaction && !$transaction && !empty($parentTransaction->gateway_transaction_id)) { $transaction = $transactionsTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_parent_transaction_id = ?' => $parentTransaction->gateway_transaction_id)); } // Get transaction id if ($transaction) { $transactionId = $transaction->gateway_transaction_id; } else { if (!empty($rawData['txn_id'])) { $transactionId = $rawData['txn_id']; } } // Get parent transaction id if ($parentTransaction) { $parentTransactionId = $parentTransaction->gateway_transaction_id; } else { if ($transaction && !empty($transaction->gateway_parent_transaction_id)) { $parentTransactionId = $transaction->gateway_parent_transaction_id; } else { if (!empty($rawData['parent_txn_id'])) { $parentTransactionId = $rawData['parent_txn_id']; } } } // Fetch order ------------------------------------------------------------- $order = null; // Transaction IPN - get order by invoice if (!$order && !empty($rawData['invoice'])) { $order = $ordersTable->find($rawData['invoice'])->current(); } // Subscription IPN - get order by recurring_payment_id if (!$order && !empty($rawData['recurring_payment_id'])) { // Get attached order $order = $ordersTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_order_id = ?' => $rawData['recurring_payment_id'])); } // Subscription IPN - get order by rp_invoice_id //if( !$order && !empty($rawData['rp_invoice_id']) ) { // //} // Transaction IPN - get order by parent_txn_id if (!$order && $parentTransactionId) { $order = $ordersTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $parentTransactionId)); } // Transaction IPN - get order by txn_id if (!$order && $transactionId) { $order = $ordersTable->fetchRow(array('gateway_id = ?' => $this->_gatewayInfo->gateway_id, 'gateway_transaction_id = ?' => $transactionId)); } // Transaction IPN - get order through transaction if (!$order && !empty($transaction->order_id)) { $order = $ordersTable->find($parentTransaction->order_id)->current(); } // Transaction IPN - get order through parent transaction if (!$order && !empty($parentTransaction->order_id)) { $order = $ordersTable->find($parentTransaction->order_id)->current(); } // Process generic IPN data ------------------------------------------------ // Build transaction info if (!empty($rawData['txn_id'])) { $transactionData = array('gateway_id' => $this->_gatewayInfo->gateway_id); // Get timestamp if (!empty($rawData['payment_date'])) { $transactionData['timestamp'] = date('Y-m-d H:i:s', strtotime($rawData['payment_date'])); } else { $transactionData['timestamp'] = new Zend_Db_Expr('NOW()'); } // Get amount if (!empty($rawData['mc_gross'])) { $transactionData['amount'] = $rawData['mc_gross']; } // Get currency if (!empty($rawData['mc_currency'])) { $transactionData['currency'] = $rawData['mc_currency']; } // Get order/user if ($order) { $transactionData['user_id'] = $order->user_id; $transactionData['order_id'] = $order->order_id; } // Get transactions if ($transactionId) { $transactionData['gateway_transaction_id'] = $transactionId; } if ($parentTransactionId) { $transactionData['gateway_parent_transaction_id'] = $parentTransactionId; } // Get payment_status switch ($rawData['payment_status']) { case 'Canceled_Reversal': // @todo make sure this works // @todo make sure this works case 'Completed': case 'Created': case 'Processed': $transactionData['type'] = 'payment'; $transactionData['state'] = 'okay'; break; case 'Denied': case 'Expired': case 'Failed': case 'Voided': $transactionData['type'] = 'payment'; $transactionData['state'] = 'failed'; break; case 'Pending': $transactionData['type'] = 'payment'; $transactionData['state'] = 'pending'; break; case 'Refunded': $transactionData['type'] = 'refund'; $transactionData['state'] = 'refunded'; break; case 'Reversed': $transactionData['type'] = 'reversal'; $transactionData['state'] = 'reversed'; break; default: $transactionData = 'unknown'; break; } // Insert new transaction if (!$transaction) { $transactionsTable->insert($transactionData); } else { unset($transactionData['timestamp']); $transaction->setFromArray($transactionData); $transaction->save(); } // Update parent transaction on refund? if ($parentTransaction && in_array($transactionData['type'], array('refund', 'reversal'))) { $parentTransaction->state = $transactionData['state']; $parentTransaction->save(); } } // Process specific IPN data ----------------------------------------------- if ($order) { $ipnProcessed = false; // Subscription IPN if ($order->source_type == 'payment_subscription') { $this->onSubscriptionTransactionIpn($order, $ipn); $ipnProcessed = true; } else { // Custom item-type IPN if (Engine_Api::_()->hasItemType($order->source_type) && !empty($order->source_id)) { $orderSourceObject = Engine_Api::_()->getItem($order->source_type, $order->source_id); if (method_exists($orderSourceObject, 'onPaymentIpn')) { $ipnProcessed = (bool) $orderSourceObject->onPaymentIpn($order, $ipn); } else { throw new Engine_Payment_Plugin_Exception(sprintf('Custom order ' . 'item "%s" does not implement onPaymentIpn() method', $order->source_type)); } } else { $eventName = 'onPaymentIpn_' . Engine_Api::inflect($order->source_type); $response = Engine_Hooks_Dispatcher::getInstance()->callEvent($eventName, array('order' => $order, 'ipn' => $ipn)); if (false != $response->getResponse()) { // Okay $ipnProcessed = true; } } } // Unknown IPN - could not be processed if (!$ipnProcessed) { throw new Engine_Payment_Plugin_Exception('Unknown order type for IPN'); } } else { throw new Engine_Payment_Plugin_Exception('Unknown or unsupported IPN ' . 'type, or missing transaction or order ID'); } return $this; }
public function activateAction() { $this->_helper->layout->setLayout('default-simple'); $user = Engine_Api::_()->core()->getSubject(); if (!$user->deactive) { return $this->_forward('success', 'utility', 'core', array('messages' => array(Zend_Registry::get('Zend_Translate')->_('Your request is invalid.')), 'redirect' => $this->getFrontController()->getRouter()->assemble(array('action' => 'home'), 'user_general', true))); } // Form $this->view->form = $form = new User_Form_Settings_Active(); if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($this->getRequest()->getPost())) { return; } // Process $db = Engine_Api::_()->getDbtable('users', 'user')->getAdapter(); $db->beginTransaction(); try { $user->user_id = $user->deactive; $user->deactive = 0; $user->save(); $db->commit(); } catch (Exception $e) { $db->rollBack(); throw $e; } Zend_Auth::getInstance()->getStorage()->write($user->user_id); Engine_Api::_()->user()->setViewer(); // Register login $loginTable = Engine_Api::_()->getDbtable('logins', 'user'); $ipObj = new Engine_IP(); $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary()))); $loginTable->insert(array('user_id' => $user->getIdentity(), 'email' => $user->email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'success', 'active' => true)); $_SESSION['login_id'] = $login_id = $loginTable->getAdapter()->lastInsertId(); // Increment sign-in count Engine_Api::_()->getDbtable('statistics', 'core')->increment('user.logins'); // Test activity @todo remove $viewer = Engine_Api::_()->user()->getViewer(); if ($viewer->getIdentity()) { $viewer->lastlogin_date = date("Y-m-d H:i:s"); if ('cli' !== PHP_SAPI) { $viewer->lastlogin_ip = $ipExpr; } $viewer->save(); Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $viewer, 'login'); } // Assign sid to view for json context $this->view->status = true; $this->view->message = Zend_Registry::get('Zend_Translate')->_('Login successful'); $this->view->sid = Zend_Session::getId(); $this->view->sname = Zend_Session::getOptions('name'); // Run post login hook $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLoginAfter', $viewer); // Do redirection only if normal context if (null === $this->_helper->contextSwitch->getCurrentContext()) { // Redirect by form $uri = $form->getValue('return_url'); if ($uri) { if (substr($uri, 0, 3) == '64-') { $uri = base64_decode(substr($uri, 3)); } return $this->_redirect($uri, array('prependBase' => false)); } // Redirect by session $session = new Zend_Session_Namespace('Redirect'); if (isset($session->uri)) { $uri = $session->uri; $opts = $session->options; $session->unsetAll(); return $this->_redirect($uri, $opts); } else { if (isset($session->route)) { $session->unsetAll(); return $this->_helper->redirector->gotoRoute($session->params, $session->route, $session->reset); } } // Redirect by hook foreach ((array) $event->getResponses() as $response) { if (is_array($response)) { if (!empty($response['error']) && !empty($response['message'])) { return $form->addError($response['message']); } else { if (!empty($response['redirect'])) { return $this->_helper->redirector->gotoUrl($response['redirect'], array('prependBase' => false)); } } } } // Just redirect to home return $this->_helper->redirector->gotoRoute(array('action' => 'home'), 'user_general', true); } }
/** * Post-insert hook. If overridden, should be called at end of function. * * @return void */ protected function _postDelete() { if ($this->_disableHooks) { return; } parent::_postDelete(); Engine_Hooks_Dispatcher::getInstance()->callEvent('on' . $this->getType(true) . 'DeleteAfter', array('type' => $this->getType(), 'identity' => $this->getIdentity())); Engine_Hooks_Dispatcher::getInstance()->callEvent('onItemDeleteAfter', array('type' => $this->getType(), 'identity' => $this->getIdentity())); }
public function saveValues() { // An id must be set to save data (duh) if (is_null($this->getItem())) { throw new Exception("Cannot save data when no identity has been specified"); } // Iterate over values $values = Engine_Api::_()->fields()->getFieldsValues($this->getItem()); $fVals = $this->getValues(); if ($this->_elementsBelongTo) { if (isset($fVals[$this->_elementsBelongTo])) { $fVals = $fVals[$this->_elementsBelongTo]; } } $privacyOptions = Fields_Api_Core::getFieldPrivacyOptions(); foreach ($fVals as $key => $value) { $parts = explode('_', $key); if (count($parts) != 3) { continue; } list($parent_id, $option_id, $field_id) = $parts; // Whoops no headings if ($this->getElement($key) instanceof Engine_Form_Element_Heading) { continue; } // Array mode if (is_array($value) || $this->getElement($key)->isArray()) { // Lookup $valueRows = $values->getRowsMatching(array('field_id' => $field_id, 'item_id' => $this->getItem()->getIdentity())); // Delete all $prevPrivacy = null; foreach ($valueRows as $valueRow) { if (!empty($valueRow->privacy)) { $prevPrivacy = $valueRow->privacy; } $valueRow->delete(); } if ($this->_hasPrivacy && !empty($this->_privacyValues[$key]) && !empty($privacyOptions[$this->_privacyValues[$key]])) { $prevPrivacy = $this->_privacyValues[$key]; } // Insert all $indexIndex = 0; if (is_array($value) || !empty($value)) { foreach ((array) $value as $singleValue) { $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $this->getItem()->getIdentity(); $valueRow->index = $indexIndex++; $valueRow->value = $singleValue; if ($this->_hasPrivacy && $prevPrivacy) { $valueRow->privacy = $prevPrivacy; } $valueRow->save(); } } else { $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $this->getItem()->getIdentity(); $valueRow->index = 0; $valueRow->value = ''; if ($this->_hasPrivacy && $prevPrivacy) { $valueRow->privacy = $prevPrivacy; } $valueRow->save(); } } else { // Lookup $valueRow = $values->getRowMatching(array('field_id' => $field_id, 'item_id' => $this->getItem()->getIdentity(), 'index' => 0)); // Remove value row if empty // if( empty($value) ) { // if( $valueRow ) { // $valueRow->delete(); // } // continue; // } // Create if missing $isNew = false; if (!$valueRow) { $isNew = true; $valueRow = $values->createRow(); $valueRow->field_id = $field_id; $valueRow->item_id = $this->getItem()->getIdentity(); } $valueRow->value = htmlspecialchars($value); if ($this->_hasPrivacy && !empty($this->_privacyValues[$key]) && !empty($privacyOptions[$this->_privacyValues[$key]])) { $valueRow->privacy = $this->_privacyValues[$key]; } $valueRow->save(); /* // Insert activity if being changed (and publish is enabled) if( !$isNew ) { $field = Engine_Api::_()->fields()->getFieldsMeta($this->getItem())->getRowMatching('field_id', $field_id); if( is_object($field) && !empty($field->publish) ) { $helper = new Fields_View_Helper_FieldValueLoop(); $helper->view = Zend_Registry::get('Zend_View'); $actionTable = Engine_Api::_()->getDbtable('actions', 'activity'); if( $field->type ) $actionTable->addActivity($this->getItem(), $this->getItem(), 'fields_change_generic', null, array( 'label' => $field->label, 'value' => $helper->getFieldValueString($field, $valueRow, $this->getItem()), //$value, )); } } * */ } } // Update search table Engine_Api::_()->getApi('core', 'fields')->updateSearch($this->getItem(), $values); // Fire on save hook Engine_Hooks_Dispatcher::getInstance()->callEvent('onFieldsValuesSave', array('item' => $this->getItem(), 'values' => $values)); // Regenerate form $this->generate(); }
public function onProcess() { // In this case, the step was placed before the account step. // Register a hook to this method for onUserCreateAfter if (!$this->_registry->user) { // Register temporary hook Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array('callback' => array($this, 'onProcess'))); return; } $viewer = $this->_registry->user; //IF MANUAL INVITE if (isset($this->getSession()->manual_invite)) { $form = new User_Form_Signup_Invite(); $data = $this->getSession()->manual_invite; foreach ($data as $key => $val) { $el = $form->getElement($key); if ($el) { $el->setValue($val); } } if (!$this->_skip && !$this->getSession()->skip) { if ($form->isValid($data)) { $form->sendInvites(); } } return; } // ADD FRIEND IF EXIST $add_data = $this->getSession()->Contactimporter_add; if ($add_data) { foreach ($add_data as $email => $name) { $user = Engine_Api::_()->getApi('core', 'user')->getUser($email); $db = Engine_Api::_()->getDbtable('membership', 'user')->getAdapter(); $db->beginTransaction(); try { // check friendship verification settings // add membership if allowed to have unverified friendships // else send request $user->membership()->addMember($viewer)->setUserApproved($viewer); // if one way friendship and verification not required if (!$user->membership()->isUserApprovalRequired() && !$user->membership()->isReciprocal()) { // Add activity Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $viewer, 'friends_follow', '{item:$object} is now following {item:$subject}.'); // Add notification Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_follow'); $message = "You are now following this member."; } else { if (!$user->membership()->isUserApprovalRequired() && $user->membership()->isReciprocal()) { // Add activity Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($user, $viewer, 'friends', '{item:$object} is now friends with {item:$subject}.'); Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $user, 'friends', '{item:$object} is now friends with {item:$subject}.'); // Add notification Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_accepted'); $message = "You are now friends with this member."; } else { if (!$user->membership()->isReciprocal()) { // Add notification Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_follow_request'); $message = "Your friend request has been sent."; } else { if ($user->membership()->isReciprocal()) { // Add notification Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, 'friend_request'); $message = "Your friend request has been sent."; } } } } $this->view->status = true; $db->commit(); $this->view->message = Zend_Registry::get('Zend_Translate')->_('Your friend request has been sent.'); } catch (Exception $e) { $db->rollBack(); $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('An error has occurred.'); $this->view->exception = $e->__toString(); } } } // INVITE FRIEND IF EXIST $invite_data = $this->getSession()->Contactimporter_invite; if ($invite_data) { // Get the already invited contacts $invites_table = Engine_Api::_()->getDbTable('invites', 'invite'); $settings = Engine_Api::_()->getApi('settings', 'core'); $translate = Zend_Registry::get('Zend_Translate'); $message = $invite_data['message']; $message = trim($message); if (is_array($invite_data['contacts']) && !empty($invite_data['contacts'])) { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $link = $pageURL . "://" . $_SERVER['HTTP_HOST'] . Zend_Controller_Front::getInstance()->getRouter()->assemble(array('user_id' => $viewer->getIdentity()), 'contactimporter_ref'); if (isset($invite_data['provider']) && !empty($invite_data['provider'])) { if ($invite_data['provider'] == 'twitter') { $obj = Engine_Api::_()->socialbridge()->getInstance('twitter'); $params = $_SESSION['socialbridge_session']['twitter']; $params['list'] = $invite_data['contacts']; $params['link'] = $link; $params['message'] = $message; $params['user_id'] = $viewer->getIdentity(); $params['uid'] = $obj->getOwnerId(); $obj->sendInvites($params); } } else { // Initiate objects to be used below $table = Engine_Api::_()->getDbtable('invites', 'invite'); // Iterate through each recipient //IF PLUGIN IS EMAIL THEN SEND VIA EMAIL if ($invite_data['plugin_type'] == 'email') { $api = Engine_Api::_()->getApi('core', 'Contactimporter'); $result_message = $api->sendInvitationEmail($viewer, $invite_data['contacts'], $message); } } } $viewer->save(); } }