public function testDebug() { Logger::debug('foo'); $this->assertEquals(1, preg_match('/DEBUG \\(' . Zend_Log::DEBUG . '\\): foo/', file_get_contents(Logger::$logStream))); }
/** * Send email address verification email to user * * @param User $user * @param Zend_Mail_Transport_Abstract $transport [Optional] Zend mail transport class * @return void */ public static function sendVerificationEmail(User $user, Zend_Mail_Transport_Abstract $transport = null) { $serverUrlHelper = new Zend_View_Helper_ServerUrl(); $urlHelper = HelperBroker::getStaticHelper('url'); $siteDomain = preg_replace('/^https?:\\/\\//', '', $serverUrlHelper->serverUrl()); $siteName = Zend_Registry::get('siteName'); $config = Zend_Registry::get('config'); $from = 'noreply@' . $siteDomain; if (!empty($config->mail) && !empty($config->mail->from)) { $from = $config->mail->from; } if (null === $transport) { if (Zend_Session::$_unitTestEnabled) { $transport = new MockMailTransport(); } else { if (!empty($config->mail) && !empty($config->mail->smtp) && !empty($config->mail->smtp->host)) { $options = $config->mail->smtp->toArray(); unset($options['host']); $transport = new Zend_Mail_Transport_Smtp($config->mail->smtp->host, $options); } } } UserEmailVerificationService::collectGarbage(); // @todo cronjob?; should also remove any unverified user accounts $verificationToken = sha1(mt_rand() . $user->getEmail() . mt_rand()); if (APPLICATION_ENV === 'testing') { $verificationLink = $serverUrlHelper->serverUrl() . '/verifyEmail/' . $verificationToken; } else { // @codeCoverageIgnoreStart $verificationLink = $serverUrlHelper->serverUrl() . $urlHelper->url(array('token' => $verificationToken), 'verifyEmail'); } // @codeCoverageIgnoreEnd UserEmailVerificationService::create(new UserEmailVerification(array('user' => $user, 'token' => $verificationToken, 'requestDate' => new DateTime()))); $text = 'Hello ' . $user->getUsername() . ', Thank you for registering with ' . $siteName . '. To activate your account and complete the registration process, please click the following link: ' . $verificationLink . '. You are receiving this email because someone recently registered on our site and provided <' . $user->getEmail() . '> as their ema il address. If you did not recently register at ' . $siteDomain . ', then please ignore this email. Your information will be remov ed from our system within 24 hours. Thank you, The ' . $siteName . ' Team '; $html = '<p>Hello ' . $user->getUsername() . ',</p> <p>Thank you for registering with ' . $siteName . '. To activate your account and complete the registration process, please click the following link: <a href="' . $verificationLink . '" title="Verify your email address">' . $verificationLink . '</a>.</p> <p>You are receiving this email because someone recently registered on our site and provided <' . $user->getEmail() . '> as their email address. If you did not recently register at ' . $siteDomain . ', then please ignore this email. Your information will be removed from our system within 24 hours.</p> <p>Thank you,<br> The ' . $siteName . ' Team</p> '; try { Logger::info('Attempting to send email to \'' . $user->getEmail() . '\'.'); $mail = new Zend_Mail('utf-8'); $mail->setFrom($from, $siteName)->setSubject('[' . $siteName . '] Email Verification')->setBodyText($text)->setBodyHtml($html)->addTo($user->getEmail()); $mail->send($transport); } catch (Exception $e) { Logger::crit($e->getMessage()); throw $e; } }
/** * Returns TRUE if user is has the given permission related to the given resource * * @param string $resource Requested resource * @param string $permission Requested permission * @return bool TRUE if current user is allowed, FALSE if not. */ public function isUserAllowed($resource = null, $permission = null) { $result = $this->has($resource) && $this->isAllowed($this->getUser()->getUsername(), $resource, $permission); if (false === $result) { if (preg_match('/^(mvc:[^:]+):/', $resource, $matches)) { $resource = $matches[1] . ':all'; \Rexmac\Zyndax\Log\Logger::debug(__METHOD__ . ':: Testing resource: ' . $resource); $result = $this->has($resource) && $this->isAllowed($this->getUser()->getUsername(), $resource, $permission); } } return $result; }
/** * Error action * * @return void */ public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case ErrorHandler::EXCEPTION_NO_ROUTE: case ErrorHandler::EXCEPTION_NO_CONTROLLER: case ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 404; break; default: // application error $this->getResponse()->setHttpResponseCode(500); if ($errors->exception instanceof ApiControllerException) { $this->view->message = $errors->exception->getMessage(); } elseif ($errors->exception) { $this->view->message = 'Application error: ' . $errors->exception->getMessage(); } else { $this->view->message = 'Application error: Unknown error'; } } // Log exception, if logger available Logger::crit(__METHOD__ . ':: ' . $this->view->message . ' - ' . $errors->exception); // Conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } if (null === $this->getRequest()->getParam('format')) { $this->view->request = $errors->request; } if ($this->view->message === 404) { $this->view->pageTitle(' - Page not found'); } else { $this->view->pageTitle(' - An error occurred'); } $this->getRequest()->setParams(array('controller' => 'error', 'action' => 'error')); }
/** * Resize image * * @param array $image Array of image info * @param int $width Desired image width * @param int $height Desired image height * @return void */ private function _resizeImage(array $image, $width, $height) { $pathToConvert = '/usr/bin/convert'; /* $quality = ''; $sharpen = ''; if($image['mime'] === 'image/jpeg') { $quality = '-quality 80'; if((($width + $height) / ($image['width'] + $image['height'])) < 0.85) { $sharpen = '-sharpen 0x0.4'; } } elseif($image['mime'] === 'image/png') { $quality = '-quality 95'; } elseif($image['mime'] === 'image/gif') { } $cmd = escapeshellcmd($pathToConvert) . " {$quality} -background white -size {$image['width']} " . escapeshellarg($image['path']) . " -thumbnail " . escapeshellarg("{$width}x{$height}!") . " -depth 8 {$sharpen}" . escapeshellarg($image['path']) . ' 2>&1'; */ $cmd = escapeshellcmd($pathToConvert) . ' ' . escapeshellarg($image['path']) . ' -resize ' . escapeshellarg("{$width}x{$height}>") . ' ' . escapeshellarg($image['path']); Logger::debug(__METHOD__ . ':: cmd = ' . $cmd); exec($cmd); }
/** * Update user * * @param User $user User to be updated * @param array $data User data to be updated * @throws Exception * @return bool True if changes were made */ private function _updateUser(User $user, array $data) { Logger::debug(__METHOD__ . '::' . var_export($data, true)); #if(isset($data['email']) && '' != $data['email'] && $data['email'] != $user->getEmail()) { # $user->setEmail($data['email']); #} $profile = $user->getProfile(); $social = $profile->getSocialNetworkIdentities(); // Track changes $changes = array(PROFILE_EDIT => array(), SOCIAL_EDIT => array(), USER_EDIT => array()); foreach ($data as $key => $newValue) { Logger::debug(__METHOD__ . ":: {$key}"); if (in_array($key, array('firstName', 'lastName', 'phone'))) { Logger::debug(__METHOD__ . ':: Profile key'); $type = PROFILE_EDIT; $oldValue = $profile->{'get' . ucfirst($key)}(); } elseif (preg_match('/^social(\\d+)$/', $key, $matches)) { Logger::debug(__METHOD__ . ':: Social key: social' . $matches[1]); $type = SOCIAL_EDIT; $oldValue = $social[$matches[1] - 1]; } else { Logger::debug(__METHOD__ . ':: User key'); $type = USER_EDIT; $oldValue = $user->{'get' . ucfirst($key)}(); } Logger::debug(__METHOD__ . ":: OLD => " . (is_object($oldValue) ? get_class($oldValue) : var_export($oldValue, true))); Logger::debug(__METHOD__ . ":: NEW => " . (is_object($newValue) ? get_class($newValue) : var_export($newValue, true))); // Only update changed properties, and keep track of the changes as well if ($this->_valueChanged($oldValue, $newValue)) { Logger::debug(__METHOD__ . ":: {$key} has changed"); Logger::debug(__METHOD__ . ":: OLD => " . (is_object($oldValue) ? get_class($oldValue) : var_export($oldValue, true))); Logger::debug(__METHOD__ . ":: NEW => " . (is_object($newValue) ? get_class($newValue) : var_export($newValue, true))); $oldVal = $oldValue; $newVal = $newValue; if ($newValue instanceof Rexmac\Zyndax\Form\Element\SocialNetworkIdentity && $oldValue instanceof Rexmac\Zyndax\Entity\UserSocialNetworkIdentity) { $newVal = $newValue->getIdentityName() . '@' . SocialNetworkService::findOneById($newValue->getNetwork())->getName(); $oldVal = $oldValue->getName() . '@' . $oldValue->getSocialNetwork()->getName(); } elseif (is_object($newValue)) { if (isset($oldValue)) { $oldVal = $oldValue->getName(); } else { $oldVal = ''; } $newVal = $newValue->getName(); } elseif (is_object($oldValue)) { $oldVal = $oldValue->getName(); } $changes[$type][] = array('item' => $key, 'oldValue' => $oldVal, 'newValue' => $newVal); // Set new value if ($type === SOCIAL_EDIT) { if ('' === $newValue->getIdentityName()) { $removed = $profile->removeSocialNetworkIdentity($oldValue); Logger::debug(__METHOD__ . ':: Removed? ' . var_export($removed, true)); UserSocialNetworkIdentityService::delete($oldValue); #$profile->setSocialNetworkIdentities(UserSocialNetworkIdentityService::findBy(array('userProfile', $profile->getId()))); } else { $oldValue->setSocialNetwork(SocialNetworkService::findOneById($newValue->getNetwork())); $oldValue->setName($newValue->getIdentityName()); } } elseif ($type === PROFILE_EDIT) { $profile->{'set' . ucfirst($key)}($newValue); } else { $user->{'set' . ucfirst($key)}($newValue); } } } UserService::update(); UserProfileService::update(); UserSocialNetworkIdentityService::update(); // Any changes to record? $changed = false; foreach (array(PROFILE_EDIT, SOCIAL_EDIT, USER_EDIT) as $type) { Logger::debug(__METHOD__ . ':: Examining ' . $type . ' changes...'); if (count($changes[$type]) > 0) { Logger::debug(__METHOD__ . ':: changes[\'' . $type . '\'] = ' . var_export($changes[$type], true)); $description = ''; foreach ($changes[$type] as $change) { Logger::debug(__METHOD__ . ':: change = ' . var_export($change, true)); $description .= sprintf('%s changed from "%s" to "%s".', $change['item'], $change['oldValue'] === 0 ? '0' : $change['oldValue'], $change['newValue']) . PHP_EOL; Logger::debug(__METHOD__ . ':: description = ' . $description); } UserEditEventService::create(array('user' => $user, 'editor' => $this->_user, 'ip' => $this->getRequest()->getServer('REMOTE_ADDR'), 'date' => new DateTime(), 'description' => rtrim($description))); $changed = true; } } return $changed; }
/** * Update User entity * * @param User $user * @param array $data * @return void */ private function _updateUser(User $user, array $data) { if (isset($data['newPassword']) && '' != $data['newPassword']) { // Verify old password #if(!UserService::verifyPassword($this->_user, $data['password'])) { # throw new Exception('Current password is invalid'); #} $data['password'] = UserService::encryptPassword($data['newPassword']); } else { $data['password'] = $user->getPassword(); } unset($data['newPassword']); unset($data['newPasswordConfirm']); if (isset($data['role'])) { $data['role'] = AclRoleService::findOneById($data['role']); } if (isset($data['timeZone'])) { $data['timeZone'] = TimeZoneService::findOneById($data['timeZone']); } // Track changes $changes = array(); foreach ($data as $key => $newValue) { if ($key === 'userId') { continue; } $oldValue = $user->{'get' . ucfirst($key)}(); Logger::debug(__METHOD__ . ":: {$key}"); Logger::debug(__METHOD__ . ":: OLD => " . (is_object($oldValue) ? get_class($oldValue) : var_export($oldValue, true))); Logger::debug(__METHOD__ . ":: NEW => " . (is_object($newValue) ? get_class($newValue) : var_export($newValue, true))); // Only update changed properties, and keep track of the changes as well if ($this->_valueChanged($oldValue, $newValue)) { Logger::debug(__METHOD__ . ":: {$key} has changed"); Logger::debug(__METHOD__ . ":: OLD => " . (is_object($oldValue) ? get_class($oldValue) : var_export($oldValue, true))); Logger::debug(__METHOD__ . ":: NEW => " . (is_object($newValue) ? get_class($newValue) : var_export($newValue, true))); $oldVal = $oldValue; $newVal = $newValue; if (is_object($newValue)) { if (isset($oldValue)) { $oldVal = $oldValue->getName(); } else { $oldVal = ''; } $newVal = $newValue->getName(); } elseif (is_object($oldValue)) { $oldVal = $oldValue->getName(); } $changes[] = array('item' => $key, 'oldValue' => $oldVal, 'newValue' => $newVal); // Set new value $user->{'set' . ucfirst($key)}($newValue); } } UserService::update(); // Any changes to record? if (count($changes) > 0) { $description = ''; foreach ($changes as $change) { $description .= sprintf('%s changed from "%s" to "%s".', $change['item'], $change['oldValue'] === 0 ? '0' : $change['oldValue'], $change['newValue']) . PHP_EOL; } UserEditEventService::create(array('user' => $user, 'editor' => $this->_user, 'ip' => $this->getRequest()->getServer('REMOTE_ADDR'), 'date' => new DateTime(), 'description' => rtrim($description))); return true; } return false; }
/** * Called before an action is dispatched by Zend_Controller_Dispatcher. * Does nothing if current request matches a whitelisted route, or if * request is authenticated. Otherwise, redirects to login page. * * @param AbstractRequest $request * @throws Zend_Controller_Dispatcher_Exception * @throws Zend_Controller_Action_Exception * @return void */ public function preDispatch(AbstractRequest $request) { $route = strtolower(sprintf('%s/%s/%s', $request->getModuleName(), $request->getControllerName(), $request->getActionName())); Logger::debug(__METHOD__ . ':: route = ' . $route); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { Logger::debug(__METHOD__ . ":: Auth has identity..."); $user = UserService::find($auth->getIdentity()); $user->setLastConnect(new DateTime()); UserService::update(); Zend_Registry::set('user', $user); Logger::debug(__METHOD__ . ':: logged in as user: '******' - ' . $user->getUsername()); if (!Zend_Session::$_unitTestEnabled) { // @codeCoverageIgnoreStart // If accessing non-admin UI and currently using LoginAs feature, then overwrite 'user' in registry $authCookieName = Zend_Registry::get('config')->session->auth->name; $ssa = new Zend_Session_Namespace($authCookieName); if (isset($ssa->loginAsUser) && 'admin' !== strtolower($request->getModuleName())) { $user = UserService::find($ssa->loginAsUser); #Logger::debug(__METHOD__.':: admin using login-as user: '******' - ' . $user->getUsername()); Zend_Registry::set('loginAs', true); Zend_Registry::set('user', $user); } } // @codeCoverageIgnoreEnd } $this->_isDispatchable($request); if (null === $this->_whitelist) { $this->_whitelist = Zend_Registry::get('config')->auth->whitelist->toArray(); } foreach ($this->_whitelist as $whitelistedRoute) { if (preg_match('|^' . $whitelistedRoute . '$|', $route)) { return; } } $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { Logger::debug(__METHOD__ . ":: Auth has identity..."); #if(isset($_SERVER["REMOTE_ADDR"])) { $ip = $_SERVER["REMOTE_ADDR"]; } #elseif(isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } #elseif(isset($_SERVER["HTTP_CLIENT_IP"])) { $ip = $_SERVER["HTTP_CLIENT_IP"]; } #else { $ip = null; } return; } #$request->setDispatched(false); // Cancel the current action // Handle unauthorized request... Logger::debug(__METHOD__ . ":: Unauthorized request. Redirecting..."); if (!Zend_Session::$_unitTestEnabled) { // @codeCoverageIgnoreStart $session = new Zend_Session_Namespace('referrer'); $session->uri = $request->getRequestUri(); } // @codeCoverageIgnoreEnd if ($request->isXmlHttpRequest()) { return $this->getResponse()->setHttpResponseCode(500)->setBody(json_encode(array('redirect' => '/user/login')))->sendResponse(); } $helper = HelperBroker::getStaticHelper('redirector'); $helper->gotoUrl('/user/login'); }