public function testMakeDefault() { $cred = $this->credentials('testUser'); $cred->makeDefault($this->users('testUser')->id, 'email'); $defaults = $cred->getDefaultCredentials(true); $default = Credentials::model()->findDefault($this->users('testUser')->id, 'email'); $this->assertEquals($cred->id, $default->id, 'Failed asserting proper function of set-as-default method.'); }
public function actionTwitterIntegration() { $credId = Yii::app()->settings->twitterCredentialsId; if ($credId && ($cred = Credentials::model()->findByPk($credId))) { $params = array('id' => $credId); } else { $params = array('class' => 'TwitterApp'); } $url = Yii::app()->createUrl('/profile/createUpdateCredentials', $params); $this->redirect($url); }
protected function renderCredentials($field, $makeLinks, $textOnly, $encode) { $fieldName = $field->fieldName; $sysleg = Yii::t('app', 'System default (legacy)'); if ($this->owner->{$fieldName} == -1) { return $sysleg; } else { $creds = Credentials::model()->findByPk($this->owner->{$fieldName}); if (!empty($creds)) { return $this->render($creds->name, $encode); } else { return $sysleg; } } }
<div class="page-title icon profile"> <h2><?php echo Yii::t('profile', 'Manage Passwords for Third-Party Applications'); ?> </h2> </div> <div class="credentials-storage"> <?php $crit = new CDbCriteria(array('condition' => '(userId=:uid OR userId=-1) AND modelClass != "TwitterApp" AND modelClass != "GoogleProject"', 'order' => 'name ASC', 'params' => array(':uid' => $profile->user->id))); $staticModel = Credentials::model(); $staticModel->private = 0; if (Yii::app()->user->checkAccess('CredentialsSelectNonPrivate', array('model' => $staticModel))) { $crit->addCondition('private=0', 'OR'); } $dp = new CActiveDataProvider('Credentials', array('criteria' => $crit)); $this->widget('zii.widgets.CListView', array('dataProvider' => $dp, 'itemView' => '_credentialsView', 'itemsCssClass' => 'credentials-list', 'summaryText' => '', 'emptyText' => '')); ?> <?php echo CHtml::beginForm(array('/profile/createUpdateCredentials'), 'get', array('onSubmit' => 'return validate ();')); echo CHtml::submitButton(Yii::t('app', 'Add New'), array('class' => 'x2-button', 'style' => 'float:left;margin-top:0')); $modelLabels = Credentials::model()->authModelLabels; unset($modelLabels['TwitterApp']); $types = array_merge(array(null => '- ' . Yii::t('app', 'select a type') . ' -'), $modelLabels); echo CHtml::dropDownList('class', 'EmailAccount', $types, array('options' => array_merge(array(null => array('selected' => 'selected')), array_fill_keys(array_keys($modelLabels), array('selected' => false))), 'class' => 'left x2-select')); echo CHtml::endForm(); ?> </div>
/** * Send an email from X2Engine, returns an array with status code/message * * @param array addresses * @param string $subject the subject for the email * @param string $message the body of the email * @param array $attachments array of attachments to send * @param array|integer $from from and reply to address for the email array(name, address) * or, if integer, the ID of a email credentials record to use for delivery. * @return array */ public function sendUserEmail($addresses, $subject, $message, $attachments = null, $from = null) { $eml = new InlineEmail(); if (is_array($addresses) ? count($addresses) == 0 : true) { throw new Exception('Invalid argument 1 sent to x2base.sendUserEmail(); expected a non-empty array, got instead: ' . var_export($addresses, 1)); } // Set recipients: if (array_key_exists('to', $addresses) || array_key_exists('cc', $addresses) || array_key_exists('bcc', $addresses)) { $eml->mailingList = $addresses; } else { return array('code' => 500, 'message' => 'No recipients specified for email; array given for argument 1 of x2base.sendUserEmail does not have a "to", "cc" or "bcc" key.'); } // Resolve sender (use stored email credentials or system default): if ($from === null || in_array($from, Credentials::$sysUseId)) { $from = (int) Credentials::model()->getDefaultUserAccount($from); // Set to the user's name/email if no valid defaults found: if ($from == Credentials::LEGACY_ID) { $from = array('name' => Yii::app()->params->profile->fullName, 'address' => Yii::app()->params->profile->emailAddress); } } if (is_numeric($from)) { $eml->credId = $from; } else { $eml->from = $from; } // Set other attributes $eml->subject = $subject; $eml->message = $message; $eml->attachments = $attachments; return $eml->deliver(); }
public function actionInviteUsers() { if (isset($_POST['emails'])) { $list = $_POST['emails']; $body = "Hello,\n\nYou are receiving this email because your X2Engine administrator has invited you to create an account.\nPlease click on the link below to create an account at X2Engine!\n\n"; $subject = "Create Your X2Engine User Account"; $list = trim($list); $emails = explode(',', $list); foreach ($emails as &$email) { $key = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 16)), 0, 16); $user = new User('invite'); $email = trim($email); $user->inviteKey = $key; $user->temporary = 1; $user->emailAddress = $email; $user->status = 0; $userList = User::model()->findAllByAttributes(array('emailAddress' => $email, 'temporary' => 1)); foreach ($userList as $userRecord) { if (isset($userRecord)) { $userRecord->delete(); } } $user->save(); $link = CHtml::link('Create Account', (@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $this->createUrl('/users/users/createAccount', array('key' => $key))); $mail = new InlineEmail(); $mail->to = $email; // Get email password $cred = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemResponseEmail'], 'email'); if ($cred == Credentials::LEGACY_ID) { $cred = Credentials::model()->getDefaultUserAccount(Yii::app()->user->id, 'email'); } if ($cred != Credentials::LEGACY_ID) { $mail->credId = $cred; } $mail->subject = $subject; $mail->message = $body . "<br><br>" . $link; $mail->contactFlag = false; if ($mail->prepareBody()) { $mail->deliver(); } else { } } $this->redirect('admin'); } $this->render('inviteUsers'); }
/** * Generates an email template to share Contact data * @param int $id The ID of the Contact */ public function actionShareContact($id) { $users = User::getNames(); $model = $this->loadModel($id); $body = "\n\n\n\n" . Yii::t('contacts', '{module} Record Details', array('{module}' => Modules::displayName(false))) . " <br />\n<br />" . Yii::t('contacts', 'Name') . ": {$model->firstName} {$model->lastName}\n<br />" . Yii::t('contacts', 'E-Mail') . ": {$model->email}\n<br />" . Yii::t('contacts', 'Phone') . ": {$model->phone}\n<br />" . Yii::t('contacts', 'Account') . ": {$model->company}\n<br />" . Yii::t('contacts', 'Address') . ": {$model->address}\n<br />{$model->city}, {$model->state} {$model->zipcode}\n<br />" . Yii::t('contacts', 'Background Info') . ": {$model->backgroundInfo}\n<br />" . Yii::t('app', 'Link') . ": " . CHtml::link($model->name, $this->createAbsoluteUrl('/contacts/contacts/view', array('id' => $model->id))); $body = trim($body); $errors = array(); $hasError = false; $status = array(); $email = array(); if (isset($_POST['email'], $_POST['body'])) { $subject = Yii::t('contacts', 'Contact Record Details'); $email['to'] = $this->parseEmailTo($this->decodeQuotes($_POST['email'])); $body = $_POST['body']; // if(empty($email) || !preg_match("/[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/",$email)) if ($email['to'] === false) { $errors[] = 'email'; } if (empty($body)) { $errors[] = 'body'; } $emailFrom = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email'); if ($emailFrom == Credentials::LEGACY_ID) { if (!Yii::app()->params->profile->emailAddress) { Yii::app()->user->setFlash('error', Yii::t('app', 'Email could not be sent: user profile does not have an email address.')); $hasError = true; } else { $emailFrom = array('name' => Yii::app()->params->profile->fullName, 'address' => Yii::app()->params->profile->emailAddress); } } if (empty($errors) && !$hasError) { $status = $this->sendUserEmail($email, $subject, $body, null, $emailFrom); } if (array_search('200', $status)) { $this->redirect(array('view', 'id' => $model->id)); return; } if ($email['to'] === false) { $email = $_POST['email']; } else { $email = $this->mailingListToString($email['to']); } } $this->render('shareContact', array('model' => $model, 'users' => $users, 'body' => $body, 'currentWorkflow' => $this->getCurrentWorkflow($model->id, 'contacts'), 'email' => $email, 'status' => $status, 'errors' => $errors)); }
public function actionDeleteCredentials($id) { $cred = Credentials::model()->findByPk($id); if (empty($cred)) { throw new CHttpException(404); } if (!Yii::app()->user->checkAccess('CredentialsDelete', array('model' => $cred))) { $this->denied(); } $cred->delete(); $this->redirect(array('/profile/manageCredentials')); }
public function setDefaultEmailAccount($attribute, $params) { if ($this->{$attribute} != Credentials::LEGACY_ID) { $cred = Credentials::model()->findByPk($this->{$attribute}); if ($cred) { $cred->makeDefault(Credentials::$sysUseId[$params['alias']], 'email', false); } } else { Yii::app()->db->createCommand()->delete('x2_credentials_default', 'userId=:uid AND serviceType=:st', array(':uid' => Credentials::$sysUseId[$params['alias']], ':st' => 'email')); } }
/** * Creates a new record. * * This method allows for the creation of new records via API request. * Requests should be made of the following format: * www.[server].com/index.php/path/to/x2/index.php/api/create/model/[modelType] * With the model's attributes as $_POST data. Furthermore, in the post array * a valid username and API key must be submitted under the indices * 'user' and 'userKey' for the request to be authenticated. */ public function actionCreate() { // Get an instance of the respective model $model = $this->getModel(true); $model->setX2Fields($_POST); if ($this->modelClass === 'Contacts') { if (isset($_POST['trackingKey'])) { // key is read-only, won't be set by setX2Fields $model->trackingKey = $_POST['trackingKey']; } if (isset($_POST['_leadRouting']) && $_POST['_leadRouting']) { $model->assignedTo = $this->getNextAssignee(); } } $setUserFields = false; // $scenario = 'Changelog behavior in effect.'; if (!empty($_POST['createDate'])) { // If create date is being manually set, i.e. an import, don't overwrite $model->disableBehavior('changelog'); $setUserFields = true; // $scenario = 'Changelog behavior disabled; create date not empty.'; } try { $editingUsername = $model->editingUsername; // $scenario .= ' Model or one of its behaviors has a property "editingUsername".'; } catch (Exception $e) { $setUserFields = true; // $scenario .= ' Model nor its behaviors have a property "editingUsername".'; } // $this->response['scenario'] = $scenario; if ($setUserFields) { $this->modelSetUsernameFields($model); } // Attempt to save the model, and perform special post-save (or error) // operations based on the model type: if ($model->save()) { // New record successfully created $this->response['model'] = $model->attributes; $message = "A {$this->modelClass} type record was created"; //sprintf(' <b>%s</b> was created',$this->modelClass); switch ($this->modelClass) { // Special extra actions to take for each model type: case 'Actions': // Set actionDescription manually since it's stored in a different table // which is updated using the magic getter: if (isset($_POST['actionDescription'])) { $model->actionDescription = $_POST['actionDescription']; } $message .= " with description {$model->actionDescription}"; $model->syncGoogleCalendar('create'); break; case 'Contacts': $message .= " with name {$model->name}"; break; } $this->_sendResponse(200, $message); } else { // API model creation failure $this->response['modelErrors'] = $model->errors; switch ($this->modelClass) { case 'Contacts': $this->log(sprintf('Failed to save record of type %s due to errors: %s', $this->modelClass, CJSON::encode($model->errors))); $msg = $this->validationMsg('create', $model); // Special lead failure notification in the app and through email: $notif = new Notification(); $notif->user = '******'; $notif->type = 'lead_failure'; $notif->createdBy = $this->user->username; $notif->createDate = time(); $notif->save(); $to = Yii::app()->settings->webLeadEmail; $subject = "Web Lead Failure"; if (!Yii::app()->params->automatedTesting) { // Send notification of failure $responderId = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email'); if ($responderId != Credentials::LEGACY_ID) { // Using configured 3rd-party email account $this->sendUserEmail(array('to' => array(array($to, 'X2Engine Administrator'))), $subject, $msg, null, $responderId); } else { // Using plain old PHP mail $phpMail = $this->getPhpMailer(); $fromEmail = Yii::app()->settings->emailFromAddr; $fromName = Yii::app()->settings->emailFromName; $phpMail->AddReplyTo($fromEmail, $fromName); $phpMail->SetFrom($fromEmail, $fromName); $phpMail->Subject = $subject; $phpMail->AddAddress($to, 'X2Engine Administrator'); $phpMail->MsgHTML($msg . "<br />JSON Encoded Attributes:<br /><br />" . json_encode($model->attributes)); $phpMail->Send(); } } $attributes = $model->attributes; ksort($attributes); if (file_exists($flCsv = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'data', 'failed_leads.csv')))) { $fp = fopen($flCsv, 'a+'); fputcsv($fp, $attributes); } else { $fp = fopen($flCsv, 'w+'); fputcsv($fp, array_keys($attributes)); fputcsv($fp, $attributes); } $this->_sendResponse(500, $msg); break; default: $this->log(sprintf('Failed to save record of type %s due to errors: %s', $this->modelClass, CJSON::encode($model->errors))); // Errors occurred $msg = "<h1>Error</h1>"; $msg .= sprintf("Couldn't create model <b>%s</b> due to errors:", $this->modelClass); $msg .= "<ul>"; foreach ($model->errors as $attribute => $attr_errors) { $msg .= "<li>Attribute: {$attribute}</li>"; $msg .= "<ul>"; foreach ($attr_errors as $attr_error) { $msg .= "<li>{$attr_error}</li>"; } $msg .= "</ul>"; } $msg .= "</ul>"; $this->_sendResponse(500, $msg); } } }
/** * Reset a user's password via a really basic email verification process * * @param type $id ID/key of the password recovery record */ public function actionResetPassword($id = null) { if (!Yii::app()->user->isGuest) { $this->redirect(array('/profile/changePassword', 'id' => Yii::app()->user->id)); } $this->layout = '//layouts/login'; $scenario = 'new'; $title = Yii::t('app', 'Reset Password'); $this->pageTitle = $title; $message = Yii::t('app', 'Enter the email address associated with your user account to request a new password and username reminder.'); $request = new PasswordReset(); $resetForm = null; if (isset($_POST['PasswordReset'])) { // Submitting a password reset request $request->setAttributes($_POST['PasswordReset']); if ($request->save()) { $request->setScenario('afterSave'); if (!$request->validate(array('email'))) { // Create a new model. It is done this way (adding the // validation error to a new model) so that there is a trail // of reset request attempts that can be counted to determine // if the user has made too many. $oldRequest = $request; $request = new $request(); $request->setAttributes($oldRequest->getAttributes(array('email')), false); $request->addErrors($oldRequest->getErrors()); } else { // A user with the corresponding email was found. Attempt to // send the email and whatever happens, don't display the // form again. $scenario = 'message'; $mail = new EmailDeliveryBehavior(); $mail->credId = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email'); // Compose the message & headers $message = Yii::t('users', "You have requested to reset the password for user {user} in {appName}.", array('{user}' => $request->user->alias, '{appName}' => Yii::app()->settings->appName)); $message .= ' ' . Yii::t('users', "To finish resetting your password, please open the following link: "); $message .= "<br /><br />" . $this->createAbsoluteUrl('/site/resetPassword') . '?' . http_build_query(array('id' => $request->id)); $message .= "<br /><br />" . Yii::t('users', "If you did not make this request, please disregard this email."); $recipients = array('to' => array(array('', $request->email))); // Send the email $status = $mail->deliverEmail($recipients, Yii::app()->settings->appName . " password reset", $message); // Set the response message accordingly. if ($status['code'] == 200) { $title = Yii::t('users', 'Almost Done!'); $message = Yii::t('users', 'Check your email at {email} for ' . 'further instructions to finish resetting your password.', array('{email}' => $request->email)); } else { $title = Yii::t('users', 'Could not send email.'); $message = Yii::t('users', 'Sending of the password reset verification email failed with message: {message}', array('{message}' => $status['message'])); } } } else { if ($request->limitReached) { $scenario = 'message'; $message = Yii::t('app', 'You have made too many requests to reset passwords. ' . 'Please wait one hour before trying again.'); } } } else { if ($id !== null) { // User might have arrived here through the link in a reset email. $scenario = 'apply'; $request = PasswordReset::model()->findByPk($id); if ($request instanceof PasswordReset && !$request->isExpired) { // Reset request record exists. $user = $request->user; if ($user instanceof User) { // ...and is valid (points to an existing user) // // Default message: the password entry form (initial request) $message = Yii::t('users', 'Enter a new password for user "{user}" ({name}):', array('{user}' => $user->alias, '{name}' => CHtml::encode($user->firstName . ' ' . $user->lastName))); $resetForm = new PasswordResetForm($user); if (isset($_POST['PasswordResetForm'])) { // Handle the form submission: $resetForm->setAttributes($_POST['PasswordResetForm']); if ($resetForm->save()) { // Done, success. $scenario = 'message'; $title = Yii::t('users', 'Password Has Been Reset'); $message = Yii::t('users', 'You should now have access ' . 'as "{user}" with the new password specified.', array('{user}' => $user->alias)); } } } else { // Invalid request record; it does not correspond to an // existing user, i.e. it's an "attempt" (entering an email // address to see if that sticks). $scenario = 'message'; $title = Yii::t('users', 'Access Denied'); $message = Yii::t('users', 'Invalid reset key.'); } } else { $scenario = 'message'; $title = Yii::t('users', 'Access Denied'); if ($request->isExpired) { $message = Yii::t('users', 'The password reset link has expired.'); } else { $message = Yii::t('users', 'Invalid reset link.'); } } } } $this->render('resetPassword', compact('scenario', 'title', 'message', 'request', 'resetForm')); }
public function getTwitterCredentials() { if (!isset($this->_credentials)) { $credId = Yii::app()->settings->twitterCredentialsId; if ($credId && ($credentials = Credentials::model()->findByPk($credId))) { $this->_credentials = array('oauth_access_token' => $credentials->auth->oauthAccessToken, 'oauth_access_token_secret' => $credentials->auth->oauthAccessTokenSecret, 'consumer_key' => $credentials->auth->consumerKey, 'consumer_secret' => $credentials->auth->consumerSecret); } } return $this->_credentials; }
/** * Getter for {@link credentials} * returns Credentials */ public function getCredentials() { if (!isset($this->_credentials)) { if ($this->credId == Credentials::LEGACY_ID) { $this->_credentials = false; } else { $cred = Credentials::model()->findByPk($this->credId); $this->_credentials = empty($cred) ? false : $cred; } } return $this->_credentials; }
private function handleWebleadFormSubmission(X2Model $model, $extractedParams) { $newRecord = $model->isNewRecord; if (isset($_POST['Contacts'])) { $model->createEvent = false; $model->setX2Fields($_POST['Contacts'], true); // Extra sanitizing $p = Fields::getPurifier(); foreach ($model->attributes as $name => $value) { if ($name != $model->primaryKey() && !empty($value)) { $model->{$name} = $p->purify($value); } } $now = time(); //require email field, check format /*if(preg_match( "/[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/", $_POST['Contacts']['email']) == 0) { $this->renderPartial('application.components.views.webFormSubmit', array ( 'type' => 'weblead', 'error' => Yii::t('contacts', 'Invalid Email Address') ) ); return; }*/ if (empty($model->visibility)) { $model->visibility = 1; } $model->validate(null, false); if (!$model->hasErrors()) { $duplicates = array(); if (!empty($model->email)) { //find any existing contacts with the same contact info $criteria = new CDbCriteria(); $criteria->compare('email', $model->email, false, "OR"); $emailFields = Yii::app()->db->createCommand()->select('fieldName')->from('x2_fields')->where('modelName = "Contacts" AND type = "email"')->queryColumn(); foreach ($emailFields as $field) { $criteria->compare($field, $model->email, false, "OR"); } $duplicates = $model->findAll($criteria); } if (count($duplicates) > 0) { //use existing record, update background info $newBgInfo = $model->backgroundInfo; $model = $duplicates[0]; $oldBgInfo = $model->backgroundInfo; if ($newBgInfo !== $oldBgInfo) { $model->backgroundInfo .= ($oldBgInfo && $newBgInfo ? "\n" : '') . $newBgInfo; } $success = $model->save(); } else { //create new record $model->assignedTo = $this->controller->getNextAssignee(); $model->visibility = 1; $model->createDate = $now; $model->lastUpdated = $now; $model->updatedBy = 'admin'; $success = $model->save(); //TODO: upload profile picture url from webleadfb } if ($success) { if ($extractedParams['generateLead']) { self::generateLead($model, $extractedParams['leadSource']); } if ($extractedParams['generateAccount']) { self::generateAccount($model); } self::addTags($model); $tags = !isset($_POST['tags']) || empty($_POST['tags']) ? array() : explode(',', $_POST['tags']); if ($newRecord) { X2Flow::trigger('WebleadTrigger', array('model' => $model, 'tags' => $tags)); } //use the submitted info to create an action $action = new Actions(); $action->actionDescription = Yii::t('contacts', 'Web Lead') . "\n\n" . Yii::t('contacts', 'Name') . ': ' . CHtml::decode($model->firstName) . " " . CHtml::decode($model->lastName) . "\n" . Yii::t('contacts', 'Email') . ": " . CHtml::decode($model->email) . "\n" . Yii::t('contacts', 'Phone') . ": " . CHtml::decode($model->phone) . "\n" . Yii::t('contacts', 'Background Info') . ": " . CHtml::decode($model->backgroundInfo); // create action $action->type = 'note'; $action->assignedTo = $model->assignedTo; $action->visibility = '1'; $action->associationType = 'contacts'; $action->associationId = $model->id; $action->associationName = $model->name; $action->createDate = $now; $action->lastUpdated = $now; $action->completeDate = $now; $action->complete = 'Yes'; $action->updatedBy = 'admin'; $action->save(); // create a notification if the record is assigned to someone $event = new Events(); $event->associationType = 'Contacts'; $event->associationId = $model->id; $event->user = $model->assignedTo; $event->type = 'weblead_create'; $event->save(); if ($model->assignedTo != 'Anyone' && $model->assignedTo != '') { $notif = new Notification(); $notif->user = $model->assignedTo; $notif->createdBy = 'API'; $notif->createDate = time(); $notif->type = 'weblead'; $notif->modelType = 'Contacts'; $notif->modelId = $model->id; $notif->save(); $profile = Profile::model()->findByAttributes(array('username' => $model->assignedTo)); /* send user that's assigned to this weblead an email if the user's email address is set and this weblead has a user email template */ if ($profile !== null && !empty($profile->emailAddress)) { $subject = Yii::t('marketing', 'New Web Lead'); $message = Yii::t('marketing', 'A new web lead has been assigned to you: ') . CHtml::link($model->firstName . ' ' . $model->lastName, array('/contacts/contacts/view', 'id' => $model->id)) . '.'; $address = array('to' => array(array('', $profile->emailAddress))); $emailFrom = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email'); if ($emailFrom == Credentials::LEGACY_ID) { $emailFrom = array('name' => $profile->fullName, 'address' => $profile->emailAddress); } $status = $this->controller->sendUserEmail($address, $subject, $message, null, $emailFrom); } } } else { $errMsg = 'Error: WebListenerAction.php: model failed to save'; /**/ AuxLib::debugLog($errMsg); Yii::log($errMsg, '', 'application.debug'); } $this->controller->renderPartial('application.components.views.webFormSubmit', array('type' => 'weblead')); Yii::app()->end(); // success! } } $sanitizedGetParams = self::sanitizeGetParams(); $this->controller->renderPartial('application.components.views.webForm', array_merge(array('type' => 'weblead'), $sanitizedGetParams)); }
private function handleWebleadFormSubmission(X2Model $model, $extractedParams) { $newRecord = $model->isNewRecord; if (isset($_POST['Contacts'])) { $model->createEvent = false; $model->setX2Fields($_POST['Contacts'], true); // Extra sanitizing $p = Fields::getPurifier(); foreach ($model->attributes as $name => $value) { if ($name != $model->primaryKey() && !empty($value)) { $model->{$name} = $p->purify($value); } } $now = time(); $model->visibility = 1; $model->validate(null, false); if (!$model->hasErrors()) { $model->lastUpdated = $now; $model->updatedBy = 'admin'; if ($model->asa('X2DuplicateBehavior') && $model->checkForDuplicates()) { $duplicates = $model->getDuplicates(); $oldest = $duplicates[0]; $fields = $model->getFields(true); foreach ($fields as $field) { if (!in_array($field->fieldName, $model->X2MergeableBehavior->restrictedFields) && !is_null($model->{$field->fieldName})) { if ($field->type === 'text' && !empty($oldest->{$field->fieldName})) { $oldest->{$field->fieldName} .= "\n--\n" . $model->{$field->fieldName}; } else { $oldest->{$field->fieldName} = $model->{$field->fieldName}; } } } $model = $oldest; $newRecord = $model->isNewRecord; } if ($newRecord) { $model->createDate = $now; $model->assignedTo = $this->controller->getNextAssignee(); } $success = $model->save(); //TODO: upload profile picture url from webleadfb if ($success) { if ($extractedParams['generateLead']) { self::generateLead($model, $extractedParams['leadSource']); } if ($extractedParams['generateAccount']) { self::generateAccount($model); } self::addTags($model); $tags = !isset($_POST['tags']) || empty($_POST['tags']) ? array() : explode(',', $_POST['tags']); if ($newRecord) { X2Flow::trigger('WebleadTrigger', array('model' => $model, 'tags' => $tags)); } //use the submitted info to create an action Actions::associateAction($model, array('actionDescription' => Yii::t('contacts', 'Web Lead') . "\n\n" . Yii::t('contacts', 'Name') . ': ' . CHtml::decode($model->firstName) . " " . CHtml::decode($model->lastName) . "\n" . Yii::t('contacts', 'Email') . ": " . CHtml::decode($model->email) . "\n" . Yii::t('contacts', 'Phone') . ": " . CHtml::decode($model->phone) . "\n" . Yii::t('contacts', 'Background Info') . ": " . CHtml::decode($model->backgroundInfo), 'type' => 'note')); // create a notification if the record is assigned to someone $event = new Events(); $event->associationType = 'Contacts'; $event->associationId = $model->id; $event->user = $model->assignedTo; $event->type = 'weblead_create'; $event->save(); if ($model->assignedTo != 'Anyone' && $model->assignedTo != '') { $notif = new Notification(); $notif->user = $model->assignedTo; $notif->createdBy = 'API'; $notif->createDate = time(); $notif->type = 'weblead'; $notif->modelType = 'Contacts'; $notif->modelId = $model->id; $notif->save(); $profile = Profile::model()->findByAttributes(array('username' => $model->assignedTo)); /* send user that's assigned to this weblead an email if the user's email address is set and this weblead has a user email template */ if ($profile !== null && !empty($profile->emailAddress)) { $subject = Yii::t('marketing', 'New Web Lead'); $message = Yii::t('marketing', 'A new web lead has been assigned to you: ') . CHtml::link($model->firstName . ' ' . $model->lastName, array('/contacts/contacts/view', 'id' => $model->id)) . '.'; $address = array('to' => array(array('', $profile->emailAddress))); $emailFrom = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email'); if ($emailFrom == Credentials::LEGACY_ID) { $emailFrom = array('name' => $profile->fullName, 'address' => $profile->emailAddress); } $status = $this->controller->sendUserEmail($address, $subject, $message, null, $emailFrom); } } } else { $errMsg = 'Error: WebListenerAction.php: model failed to save'; /**/ AuxLib::debugLog($errMsg); Yii::log($errMsg, '', 'application.debug'); } $this->controller->renderPartial('application.components.views.webFormSubmit', array('type' => 'weblead', 'redirectUrl' => $extractedParams['redirectUrl'])); Yii::app()->end(); // success! } } $sanitizedGetParams = self::sanitizeGetParams(); $this->controller->renderPartial('application.components.views.webForm', array_merge(array('type' => 'weblead'), $sanitizedGetParams)); }