/** * Process the page when its submitted * * @author kuma, salvipascual * @version 1.0 * */ public function processAction() { // get the values from the post $captcha = trim($this->request->getPost('captcha')); $name = trim($this->request->getPost('name')); $inviter = trim($this->request->getPost('email')); $guest = trim($this->request->getPost('guest')); if (!isset($_SESSION['phrase'])) { $_SESSION['phrase'] = uniqid(); } // throw a die() // check all values passed are valid if (strtoupper($captcha) != strtoupper($_SESSION['phrase']) || $name == "" || !filter_var($inviter, FILTER_VALIDATE_EMAIL) || !filter_var($guest, FILTER_VALIDATE_EMAIL)) { die("Error procesando, por favor valla atras y comience nuevamente."); } // params for the response $this->view->name = $name; $this->view->email = $inviter; // create classes needed $connection = new Connection(); $email = new Email(); $utils = new Utils(); $render = new Render(); // do not invite people who are already using Apretaste if ($utils->personExist($guest)) { $this->view->already = true; return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index")); } // send notification to the inviter $response = new Response(); $response->setResponseSubject("Gracias por darle internet a un Cubano"); $response->setEmailLayout("email_simple.tpl"); $response->createFromTemplate("invitationThankYou.tpl", array('num_notifications' => 0)); $response->internal = true; $html = $render->renderHTML(new Service(), $response); $email->sendEmail($inviter, $response->subject, $html); // send invitations to the guest $response = new Response(); $response->setResponseSubject("{$name} le ha invitado a revisar internet desde su email"); $responseContent = array("host" => $name, "guest" => $guest, 'num_notifications' => 0); $response->createFromTemplate("invitation.tpl", $responseContent); $response->internal = true; $html = $render->renderHTML(new Service(), $response); $email->sendEmail($guest, $response->subject, $html); // save all the invitations into the database at the same time $connection->deepQuery("INSERT INTO invitations (email_inviter,email_invited,source) VALUES ('{$inviter}','{$guest}','abroad')"); // redirect to the invite page $this->view->message = true; return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index")); }
public function forgotPassword($data) { $saveData = array(); $email = $data['email']; $respone = array(); $options = array('conditions' => array('User.email' => $email)); $user = $this->find("first", $options); if ($user) { $resetCode = Security::hash(String::uuid(), 'sha1', true); $url = Router::url(array('controller' => 'users', 'action' => 'resetPassword'), true) . '?code=' . $resetCode; //Removing any previously generated $this->ResetPassword->deleteAll(array('ResetPassword.user_id' => $user['User']['id']), false); //saving validation code $saveData['ResetPassword'] = array('user_id' => $user['User']['id'], 'reset_code' => $resetCode); $status = $this->ResetPassword->saveAll($saveData, array('validate' => false)); if ($status) { $Email = new Email(); $message = 'Reset password'; $message .= "Copy and Paste following url in your browser:\n"; $message .= $url; if (SEND_EMAIL) { $emailStatus = $Email->sendEmail($email, $message, EMAIL_TPL_RESET_PASSWORD); } else { $emailStatus = true; } if ($emailStatus) { return array('status' => true, 'success_msg' => USER_RESET_PASSWORD_SUCCESS); } } else { return array('status' => false, 'errors' => USER_ERR_RESET_PASSWORD_FAILED); } } else { return array('status' => false, 'errors' => USER_ERR_EMAIL_NOT_REGISTERED); } }
/** * Crear un nuevo usuario en la BBDD con los datos de LDAP. * Esta función crea los usuarios de LDAP en la BBDD para almacenar infomación del mismo * y utilizarlo en caso de fallo de LDAP * * @param User $User * @return bool */ public static function newUserLDAP(User $User) { $passdata = UserPass::makeUserPassHash($User->getUserPass()); $groupId = Config::getValue('ldap_defaultgroup', 0); $profileId = Config::getValue('ldap_defaultprofile', 0); $query = 'INSERT INTO usrData SET ' . 'user_name = :name,' . 'user_groupId = :groupId,' . 'user_login = :login,' . 'user_pass = :pass,' . 'user_hashSalt = :hashSalt,' . 'user_email = :email,' . 'user_notes = :notes,' . 'user_profileId = :profileId,' . 'user_isLdap = 1,' . 'user_isDisabled = :isDisabled'; $data['name'] = $User->getUserName(); $data['login'] = $User->getUserLogin(); $data['pass'] = $passdata['pass']; $data['hashSalt'] = $passdata['salt']; $data['email'] = $User->getUserEmail(); $data['notes'] = _('Usuario de LDAP'); $data['groupId'] = $groupId; $data['profileId'] = $profileId; $data['isDisabled'] = $groupId === 0 || $profileId === 0 ? 1 : 0; if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } if (!$groupId || !$profileId) { $Log = new Log(_('Activación Cuenta')); $Log->addDescription(_('Su cuenta está pendiente de activación.')); $Log->addDescription(_('En breve recibirá un email de confirmación.')); $Log->writeLog(); Email::sendEmail($Log, $User->getUserEmail(), false); } Log::writeNewLogAndEmail(_('Nuevo usuario de LDAP'), sprintf("%s (%s)", $User->getUserName(), $User->getUserLogin())); return true; }
/** * 增加系统账户页面 */ public function ActionAddAccount() { $account_model = new Account(); if (isset($_POST['Account'])) { // 密码要md5加密 if (isset($_POST['Account']['PassWord']) && !empty($_POST['Account']['PassWord']) && isset($_POST['Account']['PassWord2']) && !empty($_POST['Account']['PassWord2'])) { $password = $_POST['Account']['PassWord']; $_POST['Account']['PassWord'] = md5($password); $_POST['Account']['PassWord2'] = md5($_POST['Account']['PassWord2']); } $account_model->attributes = $_POST['Account']; // 执行添加 if ($account_model->save()) { // 添加操作日志 [S] $log = Yii::app()->user->name . '于 ' . date('Y-m-d H:i:s', time()) . ' 添加了一个名为 【' . $_POST['Account']['UserName'] . '】 的账户'; OperationLogManage::AddOperationLog($log); // 添加日志 // 添加操作日志 [E] // 发送通知邮件 $email_content = '用户名:' . $_POST['Account']['UserName'] . '<br />密 码:' . $password; Email::sendEmail($_POST['Account']['Email'], '百城资源后台管理系统账户已开通', $email_content, 'smtp.baicheng.com', CARRENTALAPI_SENDEMAIL_USERNAME, CARRENTALAPI_SENDEMAIL_PASSWORD); Yii::app()->user->setFlash('save_sign', '添加成功'); $this->redirect(Yii::app()->createUrl('Account/RestrictAccount', array('account_id' => $account_model->attributes['ID']))); } else { Yii::app()->user->setFlash('save_sign', '添加失败'); $this->renderPartial('add_account', array('account_model' => $account_model)); } } else { $this->renderPartial('add_account', array('account_model' => $account_model)); } }
public function mainAction() { // inicialize supporting classes $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = false; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; // get valid people $people = $connection->deepQuery("\n\t\t\tSELECT email, username, first_name, last_access\n\t\t\tFROM person\n\t\t\tWHERE active=1\n\t\t\tAND email not in (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND DATE(last_access) > DATE('2016-05-01')\n\t\t\tAND email like '%.cu'\n\t\t\tAND email not like '*****@*****.**'"); // send the remarketing $log = ""; foreach ($people as $person) { // get the email address $newEmail = "apretaste+{$person->username}@gmail.com"; // create the variabels to pass to the template $content = array("newemail" => $newEmail, "name" => $person->first_name); // create html response $response->setEmailLayout("email_simple.tpl"); $response->createFromTemplate('newEmail.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the email $email->sendEmail($person->email, "Sorteando las dificultades, un email lleno de alegria", $html); $log .= $person->email . "\n"; } // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/newemail.log"); $logger->log($log); $logger->close(); }
/** * public queueNewUser($email, $password) * * Creates a new user and stores it in the TEMP database, setting * the local object's data. It then sends an email with an activation links. * * Returns true on success. */ public function queueNewUser($email, $username, $pw) { // Send back a return code to state whether its success/fail // eg 1 would be success // 2 means "email already registered" $db = Database::getInstance(); $query = "\n\t\t\t\tINSERT INTO users_confirm (\n\t\t\t\t\temail,\n\t\t\t\t\tusername,\n\t\t\t\t\tpassword,\n\t\t\t\t\tsalt,\n\t\t\t\t\tactivation_key\n\t\t\t\t) VALUES (\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?\n\t\t\t\t)\n\t\t\t"; $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); // This hashes the password with the salt so it can be stored securely. $password = hash('sha256', $pw . $salt); // Next we hash the hash value 65536 more times. The purpose of this is to // protect against brute force attacks. Now an attacker must compute the hash 65537 // times for each guess they make against a password, whereas if the password // were hashed only once the attacker would have been able to make 65537 different // guesses in the same amount of time instead of only one. for ($round = 0; $round < 65536; $round++) { $password = hash('sha256', $password . $salt); } // Uncomment to actually register accounts $key = md5(time()); $db->query($query, array($email, $username, $password, $salt, $key)); $result = $db->firstResult(); // Send email $em = new Email(); $em->sendEmail($email, "Confirm your account", "This is an email test, please use this key to register: " . $key, true); return true; }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = true; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people who were invited but never used Apretaste $invitedPeople = $connection->deepQuery("\n\t\t\tSELECT invitation_time, email_inviter, email_invited\n\t\t\tFROM invitations \n\t\t\tWHERE used=0 \n\t\t\tAND DATEDIFF(CURRENT_DATE, invitation_time) > 15 \n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from delivery_dropped)\n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tORDER BY invitation_time DESC\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nINVITATIONS (" . count($invitedPeople) . ")\n"; foreach ($invitedPeople as $person) { // check number of days since the invitation was sent $datediff = time() - strtotime($person->invitation_time); $daysSinceInvitation = floor($datediff / (60 * 60 * 24)); // validate old invitations to avoid bounces if ($daysSinceInvitation > 60) { // re-validate the email $res = $utils->deepValidateEmail($person->email_invited); // if response not ok or temporal, delete from invitations list if ($res[0] != "ok" && $res[0] != "temporal") { $connection->deepQuery("DELETE FROM invitations WHERE email_invited = '{$person->email_invited}'"); $log .= "\t --skiping {$person->email_invited}\n"; continue; } } // send data to the template $content = array("date" => $person->invitation_time, "inviter" => $person->email_inviter, "invited" => $person->email_invited, "expires" => strtotime('next month')); // create html response $response->createFromTemplate('pendinginvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the invitation email $subject = "Su amigo {$person->email_inviter} esta esperando por usted!"; $email->sendEmail($person->email_invited, $subject, $html); // insert into remarketing table $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$person->email_invited}', 'INVITE')"); // display notifications $log .= "\t{$person->email_invited}\n"; } // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // printing log $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n"; echo $log; // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/remarketing_invitation.log"); $logger->log($log); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='invitation'"); }
function email($subject, $body) { require_once "../includes/email.php"; $email = new Email(); $email->subject = $subject; $email->body = $body; $email->sendEmail(); }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $utils = new Utils(); $connection = new Connection(); $sender = new Email(); // get the first campaign created that is waiting to be sent $campaign = $connection->deepQuery("\n\t\t\tSELECT id, subject, content\n\t\t\tFROM campaign\n\t\t\tWHERE sending_date < CURRENT_TIMESTAMP\n\t\t\tAND status = 'WAITING'\n\t\t\tGROUP BY sending_date ASC\n\t\t\tLIMIT 1"); // check if there are not campaigns if (empty($campaign)) { return; } else { $campaign = $campaign[0]; } // check campaign as SENDING $connection->deepQuery("UPDATE campaign SET status='SENDING' WHERE id = {$campaign->id}"); // get the list of people in the list who hsa not receive this campaign yet // so in case the campaign fails when it tries again starts from the same place $people = $connection->deepQuery("\n\t\t\tSELECT email FROM person\n\t\t\tWHERE mail_list=1 AND active=1\n\t\t\tAND email NOT IN (SELECT email FROM campaign_sent WHERE campaign={$campaign->id})"); // show initial message $total = count($people); echo "\nSTARTING COUNT: {$total}\n"; // email people one by one $counter = 1; foreach ($people as $person) { // show message echo "{$counter}/{$total} - {$person->email}\n"; $counter++; // replace the template variables $content = $utils->campaignReplaceTemplateVariables($person->email, $campaign->content, $campaign->id); // send test email $sender->trackCampaign = $campaign->id; $result = $sender->sendEmail($person->email, $campaign->subject, $content); // add to bounced and unsubscribe if there are issues sending $bounced = ""; $status = "SENT"; if (!$result) { $utils->unsubscribeFromEmailList($person->email); $bounced = "bounced=bounced+1,"; $status = "BOUNCED"; } // save status before moving to the next email $connection->deepQuery("\n\t\t\t\tINSERT INTO campaign_sent (email, campaign, status) VALUES ('{$person->email}', '{$campaign->id}', '{$status}');\n\t\t\t\tUPDATE campaign SET {$bounced} sent=sent+1 WHERE id='{$campaign->id}'"); } // set the campaign as SENT $connection->deepQuery("UPDATE campaign SET status='SENT' WHERE id='{$campaign->id}'"); // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // saving the log $wwwroot = $this->di->get('path')['root']; $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/campaigns.log"); $logger->log("ID: {$campaign->id}, RUNTIME: {$timeDiff}, SUBJECT: {$campaign->subject}"); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='campaign'"); }
public function indexAction() { $email = new Email(); $images = array("/home/salvipascual/Pictures/pascuals.jpg", "/home/salvipascual/Pictures/pascuals.png"); $body = '<html>Inline image:<img alt="image1" src="cid:pascuals.jpg"><br/><img alt="image2" src="cid:pascuals.png"></html>'; echo $email->deliveryStatus("*****@*****.**"); exit; $email->sendEmail("*****@*****.**", "Test", $body); echo "Email sent"; }
public function sendPasswordLink($email) { try { $mailer = new Email(); $this->email['body'] .= $this->email['reset_link'] . $this->token; if ($mailer->sendEmail($email, $this->email['subject'], $this->email['body'])) { $this->saveToken($email); } return true; } catch (Swift_SwiftException $e) { return false; } }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = true; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people in the list to be automatically invited $people = $connection->deepQuery("\n\t\t\tSELECT * FROM autoinvitations\n\t\t\tWHERE email NOT IN (SELECT email FROM person)\n\t\t\tAND email NOT IN (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND email NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tAND error=0\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nAUTOMATIC INVITATIONS (" . count($people) . ")\n"; foreach ($people as $person) { // if response not ok, check the email as error $res = $utils->deepValidateEmail($person->email); if ($res[0] != "ok") { $connection->deepQuery("UPDATE autoinvitations SET error=1, processed=CURRENT_TIMESTAMP WHERE email='{$person->email}'"); $log .= "\t --skiping {$person->email}\n"; continue; } // create html response $content = array("email" => $person->email); $response->createFromTemplate('autoinvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send invitation email $subject = "Dos problemas, y una solucion"; $email->sendEmail($person->email, $subject, $html); // mark as sent $connection->deepQuery("\n\t\t\t\tSTART TRANSACTION;\n\t\t\t\tDELETE FROM autoinvitations WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'AUTOINVITE');\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\n"; } // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // printing log $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n"; echo $log; // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/remarketing_autoinvitation.log"); $logger->log($log); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='autoinvitation'"); }
/** * Migrar los perfiles con formato anterior a v1.2 * * @return bool */ public static function migrateProfiles() { $query = 'SELECT userprofile_id AS id,' . 'userprofile_name AS name,' . 'BIN(userProfile_pView) AS pView,' . 'BIN(userProfile_pViewPass) AS pViewPass,' . 'BIN(userProfile_pViewHistory) AS pViewHistory,' . 'BIN(userProfile_pEdit) AS pEdit,' . 'BIN(userProfile_pEditPass) AS pEditPass,' . 'BIN(userProfile_pAdd) AS pAdd,' . 'BIN(userProfile_pDelete) AS pDelete,' . 'BIN(userProfile_pFiles) AS pFiles,' . 'BIN(userProfile_pConfig) AS pConfig,' . 'BIN(userProfile_pConfigMasterPass) AS pConfigMasterPass,' . 'BIN(userProfile_pConfigBackup) AS pConfigBackup,' . 'BIN(userProfile_pAppMgmtCategories) AS pAppMgmtCategories,' . 'BIN(userProfile_pAppMgmtCustomers) AS pAppMgmtCustomers,' . 'BIN(userProfile_pUsers) AS pUsers,' . 'BIN(userProfile_pGroups) AS pGroups,' . 'BIN(userProfile_pProfiles) AS pProfiles,' . 'BIN(userProfile_pEventlog) AS pEventlog ' . 'FROM usrProfiles'; DB::setReturnArray(); $queryRes = DB::getResults($query, __FUNCTION__); if ($queryRes === false) { Log::writeNewLog(_('Migrar Perfiles'), _('Error al obtener perfiles')); return false; } foreach ($queryRes as $oldProfile) { $profile = new Profile(); $profile->setId($oldProfile->id); $profile->setName($oldProfile->name); $profile->setAccAdd($oldProfile->pAdd); $profile->setAccView($oldProfile->pView); $profile->setAccViewPass($oldProfile->pViewPass); $profile->setAccViewHistory($oldProfile->pViewHistory); $profile->setAccEdit($oldProfile->pEdit); $profile->setAccEditPass($oldProfile->pEditPass); $profile->setAccDelete($oldProfile->pDelete); $profile->setConfigGeneral($oldProfile->pConfig); $profile->setConfigEncryption($oldProfile->pConfigMasterPass); $profile->setConfigBackup($oldProfile->pConfigBackup); $profile->setMgmCategories($oldProfile->pAppMgmtCategories); $profile->setMgmCustomers($oldProfile->pAppMgmtCustomers); $profile->setMgmUsers($oldProfile->pUsers); $profile->setMgmGroups($oldProfile->pGroups); $profile->setMgmProfiles($oldProfile->pProfiles); $profile->setEvl($oldProfile->pEventlog); if ($profile->profileUpdate() === false) { return false; } } $query = 'ALTER TABLE usrProfiles ' . 'DROP COLUMN userProfile_pAppMgmtCustomers,' . 'DROP COLUMN userProfile_pAppMgmtCategories,' . 'DROP COLUMN userProfile_pAppMgmtMenu,' . 'DROP COLUMN userProfile_pUsersMenu,' . 'DROP COLUMN userProfile_pConfigMenu,' . 'DROP COLUMN userProfile_pFiles,' . 'DROP COLUMN userProfile_pViewHistory,' . 'DROP COLUMN userProfile_pEventlog,' . 'DROP COLUMN userProfile_pEditPass,' . 'DROP COLUMN userProfile_pViewPass,' . 'DROP COLUMN userProfile_pDelete,' . 'DROP COLUMN userProfile_pProfiles,' . 'DROP COLUMN userProfile_pGroups,' . 'DROP COLUMN userProfile_pUsers,' . 'DROP COLUMN userProfile_pConfigBackup,' . 'DROP COLUMN userProfile_pConfigMasterPass,' . 'DROP COLUMN userProfile_pConfig,' . 'DROP COLUMN userProfile_pAdd,' . 'DROP COLUMN userProfile_pEdit,' . 'DROP COLUMN userProfile_pView'; $queryRes = DB::getQuery($query, __FUNCTION__); $log = new Log(_('Migrar Perfiles')); if ($queryRes) { $log->addDescription(_('Operación realizada correctamente')); } else { $log->addDescription(_('Migrar Perfiles'), _('Fallo al realizar la operación')); } $log->writeLog(); Email::sendEmail($log); return $queryRes; }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = true; $render = new Render(); $response = new Response(); $wwwroot = $this->di->get('path')['root']; $log = ""; // get people who did not finish a survey for the last 3 days $surveys = $connection->deepQuery("\n\t\t\tSELECT A.*, B.title, B.deadline, B.value FROM \n\t\t\t(\n\t\t\t\tSELECT email, survey, \n\t\t\t\tDATEDIFF(CURRENT_DATE, MAX(date_choosen)) as days_since,\n\t\t\t\t(\n\t\t\t\t\tSELECT COUNT(*) \n\t\t\t\t\tFROM _survey_question \n\t\t\t\t\tWHERE _survey_question.survey = _survey_answer_choosen.survey\n\t\t\t\t) as total, \n\t\t\t\tCOUNT(question) as choosen from _survey_answer_choosen GROUP BY email, survey\n\t\t\t) A\n\t\t\tJOIN _survey B\n\t\t\tON A.survey = B.id\n\t\t\tWHERE A.total > A.choosen \n\t\t\tAND A.days_since >= 7\n\t\t\tAND B.active = 1\n\t\t\tAND DATEDIFF(B.deadline, B.date_created) > 0\n\t\t\tAND A.email NOT IN (SELECT DISTINCT email FROM remarketing WHERE type='SURVEY')"); // send emails to users $log .= "\nSURVEY REMARKETING (" . count($surveys) . ")\n"; foreach ($surveys as $survey) { $content = array("survey" => $survey->survey, "days" => $survey->days_since, "missing" => $survey->total - $survey->choosen, "title" => $survey->title, "deadline" => $survey->deadline, "value" => $survey->value); // create html response $response->setResponseSubject("No queremos que pierda \${$survey->value}"); $response->createFromTemplate('surveyReminder.tpl', $content); $response->internal = true; // send email to the person $html = $render->renderHTML($service, $response); $email->sendEmail($survey->email, $response->subject, $html); // add entry to remarketing $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$survey->email}', 'SURVEY');"); // display notifications $log .= "\t{$survey->email} | surveyID: {$survey->survey} \n"; } // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // printing log $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n"; echo $log; // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/surveyreminder.log"); $logger->log($log); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='survey'"); }
public function actionSendEmail() { $sendType = Yii::app()->request->getParam('sendType'); if (empty($sendType)) { exit; } $startTime = time(); if ($sendType === 'daytime') { $startTime = time() - 60 * 5; //8-23点,每5分钟触发一次 } elseif ($sendType === 'night') { $startTime = time() - 60 * 60 * 8; //晚上23-8点 在8点触发一次 } $status = 10; //取某个状态下的日志 $rentalcarsApiLog_model = RentalcarsApiLog::model()->findAll("ReturnTime>:returnTime and Status =:status", array(":returnTime" => $startTime, ":status" => $status)); $rentalcarsApiLog_count = count($rentalcarsApiLog_model); if ($rentalcarsApiLog_count > 0) { $message = '<b>来自:百程资源系统-生产环境</b><br/><br/>'; foreach ($rentalcarsApiLog_model as $key => $value) { $message .= '<b>编号:' . $value['Id'] . '<br/>'; $message .= '接口名称:' . $value['InterfaceName'] . '<br/>'; $message .= '请求时间:' . date('Y-m-d H:i:s', $value['RequestTime']) . '<br/>'; $message .= '返回状态:异常状态-' . $value['Status'] . '</b><br/>'; //$message.='<b>请求参数:</b><br/>'.$value['RequestParam'].'<br/>'; //$message.='<b>返回值(Xml格式):</b><br/>'.$value['ReturnXml'].'<br/>'; //$message.='<b>返回值(Json格式):</b><br/>'.$value['ReturnParam'].'<br/>'; $message .= '======================================================================='; $message .= '<br/>'; } //发送邮件 // $emailStatus= Email::sendEmail(CARRENTALAPI_REQUESTEMAIL,'国际租车日志',$message); $emailStatus = Email::sendEmail(CARRENTALAPI_REQUESTEMAIL, '国际租车日志', $message, "smtp.baicheng.com", CARRENTALAPI_SENDEMAIL_USERNAME, CARRENTALAPI_SENDEMAIL_PASSWORD, $attachment = false); if ($emailStatus) { echo 'send success!'; } else { echo 'send error!'; } } else { echo 'send content is null!'; } }
/** * Actualizar la clave de un usuario desde phpPMS. * * @param string $userLogin con el login del usuario * @param string $userPass con la clave del usuario * @return bool * * Esta función actualiza la clave de un usuario que ha sido migrado desde phpPMS */ public static function migrateUser($userLogin, $userPass) { $passdata = UserPass::makeUserPassHash($userPass); $query = 'UPDATE usrData SET ' . 'user_pass = :pass,' . 'user_hashSalt = :salt,' . 'user_lastUpdate = NOW(),' . 'user_isMigrate = 0 ' . 'WHERE user_login = :login ' . 'AND user_isMigrate = 1 ' . 'AND (user_pass = SHA1(CONCAT(user_hashSalt,:passOld)) ' . 'OR user_pass = MD5(:passOldMd5)) LIMIT 1'; $data['pass'] = $passdata['pass']; $data['salt'] = $passdata['salt']; $data['login'] = $userLogin; $data['passOld'] = $userPass; $data['passOldMd5'] = $userPass; if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } $log = new Log(__FUNCTION__); $log->addDescription(_('Usuario actualizado')); $log->addDescription('Login: ' . $userLogin); $log->writeLog(); Email::sendEmail($log); return true; }
/** * Function used for contact us page * @author Gaurav Bhandari */ public function contactUs() { $titleForLayout = "FoxHopr : Contact"; $this->set(compact('titleForLayout')); if ($this->request->is('post')) { $userData = $this->request->data['Page']; $emailLib = new Email(); $to = '*****@*****.**'; $subject = 'User Feedback'; $template = 'userFeedback'; $variable = array('name' => 'Saraswati', 'data' => $userData); $success = $emailLib->sendEmail($to, $subject, $variable, $template); if ($success) { $this->Session->setFlash(__('Your feedback has been submitted successfully'), 'flash_good'); $this->redirect(array('controller' => 'pages', 'action' => 'contactUs')); } else { $this->Session->setFlash(__('Some error, please try again.'), 'flash_bad'); } } }
/** * Function for sending resetting goals * */ public function goalsResetCron() { $first_day_prev_month = date('Y-m-01 H:i:s', strtotime("-1 months", strtotime(date('Y-m-d H:i:s')))); $last_day_prev_month = date('Y-m-t H:i:s', strtotime("-1 months", strtotime(date('Y-m-d H:i:s')))); $first_day_third_month = date('Y-m-01 H:i:s', strtotime("-3 months", strtotime(date('Y-m-d H:i:s')))); $conditions = array('Goal.created BETWEEN ? AND ?' => array($first_day_prev_month, $last_day_prev_month), 'Goal.goal_type IN' => array('individual_goals', 'group_member_goals')); $userGoalData = $this->Goal->find('all', array('conditions' => $conditions)); $conditions = array('Goal.created BETWEEN ? AND ?' => array($first_day_third_month, $last_day_prev_month), 'Goal.goal_type ' => 'group_goals'); $groupGoalData = $this->Goal->find('all', array('conditions' => $conditions)); //pr($userGoalData); $emailPost = array_merge($userGoalData, $groupGoalData); if (!empty($emailPost)) { foreach ($emailPost as $row) { $emailLib = new Email(); $to = $userInfo['BusinessOwner']['email']; $subject = 'FoxHopr: Your Goals have been reset'; $template = 'group_goals_reset'; $variable = array('name' => $row['BusinessOwner']['fname'] . " " . $row['BusinessOwner']['lname']); $success = $emailLib->sendEmail($to, $subject, $variable, $template, 'both'); } } }
public function payAction() { // See your keys here https://dashboard.stripe.com/account/apikeys $stripeSecretKey = $this->di->get('config')['stripe']['secret']; \Stripe\Stripe::setApiKey($stripeSecretKey); // stored on setup.php // Get the credit card details submitted by the form $token = $_POST['stripeToken']; $amount = $_POST['amount']; $email = $_POST['email']; // Create the charge on Stripe's servers - this will charge the user's card try { $charge = \Stripe\Charge::create(array("amount" => $amount, "currency" => "usd", "source" => $token, "description" => "Example charge")); } catch (\Stripe\Error\Card $e) { // The card has been declined die("Sorry, your card was declined. Please go back and try again."); } // get the path to the www folder $wwwroot = $this->di->get('path')['root']; // get the key from the config $mailerLiteKey = $this->di->get('config')['mailerlite']['key']; // adding the new Donor to the list include_once "{$wwwroot}/lib/mailerlite-api-php-v1/ML_Subscribers.php"; $ML_Subscribers = new ML_Subscribers($mailerLiteKey); $subscriber = array('email' => $email); $result = $ML_Subscribers->setId("2225307")->add($subscriber); // adding to Donors list // send email with the donor's info $dollarsAmount = $amount / 100; $today = date('l jS \\of F Y h:i:s A'); $message = "Date: {$today}<br/>Donor: {$email}<br/>Amount: {$dollarsAmount}"; $emailObj = new Email(); $emailObj->sendEmail("*****@*****.**", "Apretaste: New donation", $message); // Send to the ThankYou page return $this->response->redirect("welcome/thankyou&email={$email}&amount={$dollarsAmount}"); }
} else { if (strpos($ReceiverString, ':') > 0) { $receiverName .= '; ' . $modulemessages->msgGroupNameSplit($ReceiverString); } else { $user = new User($gDb, $gProfileFields, $ReceiverString); $receiverName .= '; ' . $user->getValue('FIRST_NAME') . ' ' . $user->getValue('LAST_NAME'); } } $receiverName = substr($receiverName, 2); $emailTemplate = str_replace('#receiver#', $receiverName, $emailTemplate); // prepare body of email with note of sender and homepage $email->setSenderInText($postName, $receiverName); // set Text $email->setText($emailTemplate); // finally send the mail $sendResult = $email->sendEmail(); } else { // if $postTo is not an Array, it is send from the hidden field. if (!is_array($postTo)) { $postTo = array($postTo); } // get user data from Database $user = new User($gDb, $gProfileFields, $postTo[0]); // check if it is allowed to send to this user if (!$gCurrentUser->editUsers() && !isMember($user->getValue('usr_id')) || $user->getValue('usr_id') === '') { $gMessage->show($gL10n->get('SYS_USER_ID_NOT_FOUND')); } // check if receiver of message has valid login if ($user->getValue('usr_login_name') === '') { $gMessage->show($gL10n->get('SYS_FIELD_EMPTY', $gL10n->get('SYS_TO'))); }
* Send out email notifications to reviewers */ $file_obj = new FileData($id, $GLOBALS['connection'], DB_NAME); $get_full_name = $user_obj->getFullName(); $full_name = $get_full_name[0] . ' ' . $get_full_name[1]; $department = $file_obj->getDepartment(); $reviewer_obj = new Reviewer($id, $GLOBALS['connection'], DB_NAME); $reviewer_list = $reviewer_obj->getReviewersForDepartment($department); $date = date('Y-m-d H:i:s T'); // Build email for general notices $mail_subject = msg('checkinpage_file_was_checked_in'); $mail_body2 = msg('checkinpage_file_was_checked_in') . "\n\n"; $mail_body2 .= msg('label_filename') . ': ' . $file_obj->getName() . "\n\n"; $mail_body2 .= msg('label_status') . ': ' . msg('addpage_new') . "\n\n"; $mail_body2 .= msg('date') . ': ' . $date . "\n\n"; $mail_body2 .= msg('addpage_uploader') . ': ' . $full_name . "\n\n"; $mail_body2 .= msg('email_thank_you') . ',' . "\n\n"; $mail_body2 .= msg('email_automated_document_messenger') . "\n\n"; $mail_body2 .= $GLOBALS['CONFIG']['base_url'] . "\n\n"; $email_obj = new Email(); $email_obj->setFullName($full_name); $email_obj->setSubject($mail_subject); $email_obj->setFrom($full_name . ' <' . $user_obj->getEmailAddress() . '>'); $email_obj->setRecipients($reviewer_list); $email_obj->setBody($mail_body2); $email_obj->sendEmail(); // clean up and back to main page $last_message = msg('message_document_checked_in'); header('Location: out.php?last_message=' . urlencode($last_message)); } }
/** * What if user forgot his password? * * @param string $email * @return bool */ public function forgotPassword($email) { $validation = new Validation(); if (!$validation->validate(['Email' => [$email, 'required|email']])) { $this->errors = $validation->errors(); return false; } if ($this->isEmailExists($email)) { //depends on the last query made by isEmailExists() $database = Database::openConnection(); $user = $database->fetchAssociative(); //If no previous records in forgotten_passwords, So, $forgottenPassword will be FALSE. $database->getByUserId("forgotten_passwords", $user["id"]); $forgottenPassword = $database->fetchAssociative(); $last_time = isset($forgottenPassword["password_last_reset"]) ? $forgottenPassword["password_last_reset"] : null; $count = isset($forgottenPassword["forgotten_password_attempts"]) ? $forgottenPassword["forgotten_password_attempts"] : null; if (!$validation->validate(['Failed Login' => [["last_time" => $last_time, "count" => $count], 'attempts']])) { $this->errors = $validation->errors(); return false; } //You need to get the new password token from the database after updating/inserting it $newPasswordToken = $this->generateForgottenPasswordToken($user["id"], $forgottenPassword); Email::sendEmail(Config::get('EMAIL_PASSWORD_RESET'), $user["email"], ["id" => $user["id"], "name" => $user["name"]], $newPasswordToken); } //This will return true even if the email doesn't exists, //because you don't want to give any clue //to (un)authenticated user if email is actually exists or not return true; }
/** * 30 发送用户订单的提车单邮件 * @param $arr_params * @return bool */ public static function SendCarOrderMail($arr_params) { $request_time = time(); $Email = new Email(); $criteria = new CDbCriteria(); $criteria->select = 'ID,OrderID,CustCode,CarOrderSite,ContactMan,DriverEmail,ContactEmail,ContactMobile,Status,VehicleID,Doors,Aircon,Seats,PickupTime,DropOffTime,PickupShopName,DropOffShopName,Company,CarType,Automatic,UnlimitedMileage,Insurance,Expense,ExtraService'; if (empty($arr_params['UserId']) || empty($arr_params['OuterOrderCode'])) { return array('status' => false, 'error_msg' => '0x300001_用户ID 和外部订单号不可为空!'); } else { $criteria->condition = ' OrderID=:OrderID and CustCode =:userID and STATUS <>2 AND STATUS <>0 '; $criteria->params = array(':userID' => $arr_params['UserId'], ':OrderID' => $arr_params['OuterOrderCode']); } $criteria->order = 'ID desc'; $Ro_val = RentalcarsOrdervehicle::model()->find($criteria); if (count($Ro_val)) { //生成提车单[E] if (!empty($Ro_val['CarOrderSite'])) { //发送邮件 $message = '提车单邮件正文!!!!!!!!!!!!!!!!!!!!!!!!!'; // $emailStatus= Email::sendEmail(CARRENTALAPI_REQUESTEMAIL, '提车单', $message, "smtp.baicheng.com", CARRENTALAPI_SENDEMAIL_USERNAME, CARRENTALAPI_SENDEMAIL_PASSWORD, array($Ro_val['CarOrderSite'],'提车单.xls')); $emailStatus = Email::sendEmail($Ro_val['ContactEmail'], '提车单', $message, "smtp.baicheng.com", CARRENTALAPI_SENDEMAIL_USERNAME, CARRENTALAPI_SENDEMAIL_PASSWORD, array($Ro_val['CarOrderSite'], '提车单.xls')); if ($emailStatus) { ApiLogManage::addRentalcars('SendCarOrderMail', json_encode($arr_params), '', json_encode(array('提车单邮件发送成功')), $request_time, time(), 1); //记录日志 return array('status' => true, 'error_msg' => '提车单邮件发送成功!'); } else { ApiLogManage::addRentalcars('SendCarOrderMail', json_encode($arr_params), '', json_encode(array('提车单邮件发送失败')), $request_time, time(), 10); //记录日志 return array('status' => false, 'error_msg' => '提车单邮件发送失败!'); } } else { return array('status' => false, 'error_msg' => '0x300002_提车单号 .xls文件地址为空!'); $arr_confirmation['note'] = '提车单附件地址为空!'; ApiLogManage::addRentalcars('SendCarOrderMail', json_encode($arr_confirmation), '', '', $request_time, time(), 10); //记录日志 } } else { return array('status' => false, 'error_msg' => '0x300001_订单未找到!'); } }
/** * Guardar un parámetro de configuración en la BBDD. * * @param string $param con el parámetro a guardar * @param string $value con el valor a guardar * @param bool $email enviar email? * @return bool */ public static function setValue($param, $value, $email = true) { $query = "INSERT INTO config " . "SET config_parameter = :param," . "config_value = :value " . "ON DUPLICATE KEY UPDATE config_value = :valuedup"; $data['param'] = $param; $data['value'] = $value; $data['valuedup'] = $value; if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } $log = new Log(_('Configuración')); $log->addDescription(_('Modificar configuración')); $log->addDescription(_('Parámetro') . ': ' . $param); $log->addDescription(_('Valor') . ': ' . $value); $log->writeLog(); if ($email === true) { Email::sendEmail($log); } return true; }
/** * Proceso para la recuperación de clave. * * @param string $login con el login del usuario * @param string $email con el email del usuario * @return bool */ public static function mailPassRecover($login, $email) { if (UserUtil::checkUserMail($login, $email) && !UserUtil::checkUserIsDisabled($login) && !UserLdap::checkUserIsLDAP($login) && !UserPassRecover::checkPassRecoverLimit($login)) { $hash = Util::generate_random_bytes(); $log = new Log(_('Cambio de Clave')); $log->addDescription(Html::strongText(_('Se ha solicitado el cambio de su clave de usuario.'))); $log->addDescription(); $log->addDescription(_('Para completar el proceso es necesario que acceda a la siguiente URL:')); $log->addDescription(); $log->addDescription(Html::anchorText(Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time())); $log->addDescription(''); $log->addDescription(_('Si no ha solicitado esta acción, ignore este mensaje.')); return Email::sendEmail($log, $email, false) && UserPassRecover::addPassRecover($login, $hash); } else { return false; } }
/** * view kicked off user information in detail * @param $bid : encrypted kicked off user id * @author Priti Kabra */ public function admin_kickedOffUserInfo($bid = null) { $this->layout = 'admin'; $this->set('title_for_layout', 'Business Owners'); if (!$bid) { $this->Session->setFlash(__('Invalid business owner'), 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUsers', 'admin' => true)); } $this->set('id', $bid); $id = $this->Encryption->decode($bid); if (!is_numeric($id)) { $this->Session->setFlash(__('Invalid business Owner'), 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'index', 'admin' => true)); } $businessOwnerData = $this->BusinessOwner->findById($id); if (empty($businessOwnerData['BusinessOwner']['is_kicked'])) { $this->Session->setFlash(__('Kick Off request does not exist.'), 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUsers', 'admin' => true)); } $groupSuggestion = array(); $leaderName = $this->BusinessOwner->find('first', array('conditions' => array('BusinessOwner.user_id' => $businessOwnerData['Group']['group_leader_id']), 'fields' => array('BusinessOwner.fname', 'BusinessOwner.lname'))); $firstMeetingDate = $businessOwnerData['Group']['first_meeting_date']; $secondMeetingDate = $businessOwnerData['Group']['second_meeting_date']; $meetingTime = $businessOwnerData['Group']['meeting_time']; $sameTimeAvailableGroups = $this->Group->find('list', array('fields' => array('Group.id'), 'conditions' => array('meeting_time' => $meetingTime, 'OR' => array('second_meeting_date' => array($firstMeetingDate, $secondMeetingDate), 'first_meeting_date' => array($firstMeetingDate, $secondMeetingDate)), 'Group.id !=' => $this->Encryption->decode($businessOwnerData['Group']['id']), 'Group.group_type' => $businessOwnerData['Group']['group_type']))); if (!empty($sameTimeAvailableGroups)) { $userProfessionId = $businessOwnerData['BusinessOwner']['profession_id']; foreach ($sameTimeAvailableGroups as $key => $availableGroup) { if ($this->Group->isProfessionOccupiedInGroup($this->Encryption->decode($key), $userProfessionId)) { $cannotDelete = 'not be deleted'; } else { $businessOwnerData['BusinessOwner']['Group'][$this->Encryption->decode($key)] = Configure::read('GROUP_PREFIX') . ' ' . $this->Encryption->decode($availableGroup); $groupSuggestion[$key] = 'Group ' . $this->Encryption->decode($key); } } } $this->set(compact('businessOwnerData', 'groupSuggestion', 'leaderName')); if ($this->request->is('post')) { $checkUserIsKicked = $this->BusinessOwner->find('first', array('conditions' => array('BusinessOwner.id' => $this->Encryption->decode($businessOwnerData['BusinessOwner']['id']), 'BusinessOwner.is_kicked' => 1))); if (empty($checkUserIsKicked)) { $this->Session->setFlash('Message for shuffled user?', 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUsers', 'admin' => true)); } $groupId = $this->Encryption->decode($this->request->data['Group']['group_id']); $businessOwnerId = $this->Encryption->decode($bid); if ($businessOwnerData['BusinessOwner']['group_id'] == $groupId) { $this->Session->setFlash(__('Please try again'), 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUsers', 'admin' => true)); } $userProfessionId = $businessOwnerData['BusinessOwner']['profession_id']; if ($this->Group->isProfessionOccupiedInGroup($this->Encryption->decode($this->request->data['Group']['group_id']), $userProfessionId)) { $this->Session->setFlash(__('The group member cannot be moved, due to group unavailability.'), 'flash_bad'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUserInfo', 'admin' => true, $businessOwnerData['BusinessOwner']['id'])); } else { $this->Groups->savePrevGroupData($businessOwnerData['BusinessOwner']['group_id'], $businessOwnerData['BusinessOwner']['user_id']); $postEmails = $this->Groups->updateGroupInfo($businessOwnerData['BusinessOwner']['group_id'], $groupId, $businessOwnerData['BusinessOwner']['user_id']); //Post emails is necessary if (!empty($postEmails)) { foreach ($postEmails as $row) { $emailLib = new Email(); $emailLib->sendEmail($row['to'], $row['subject'], $row['variable'], $row['template'], 'both'); } } $newGroupRole = $this->BusinessOwner->find('first', array('conditions' => array('BusinessOwner.user_id' => $businessOwnerData['BusinessOwner']['user_id']), 'fields' => array('BusinessOwner.group_role'))); $groupMailData['role'] = $newGroupRole['BusinessOwner']['group_role']; $groupMailData['id'] = $groupId; if (strtotime($businessOwnerData['Group']['first_meeting_date']) > strtotime(date('Y-m-d'))) { $meetingDate = $businessOwnerData['Group']['first_meeting_date']; } else { $meetingDate = $businessOwnerData['Group']['second_meeting_date']; } $groupMailData['date'] = date('m-d-Y', strtotime($meetingDate)); $groupMailData['time'] = date('h:i A', strtotime($businessOwnerData['Group']['meeting_time'])); $name = $businessOwnerData['BusinessOwner']['fname'] . " " . $businessOwnerData['BusinessOwner']['lname']; $emailLib = new Email(); $to = $businessOwnerData['BusinessOwner']['email']; $subject = 'FoxHopr: Group replaced successfully'; $template = 'kick_off_confirmation_email'; $format = 'both'; $variable = array('name' => $name, 'groupMailData' => $groupMailData); $emailLib->sendEmail($to, $subject, $variable, $template, $format); $this->Session->setFlash(__('Group Member has been moved successfully.'), 'flash_good'); $this->redirect(array('controller' => 'businessOwners', 'action' => 'kickedOffUsers', 'admin' => true)); } } }
/** * Actualiza la BBDD según la versión. * * @param int $version con la versión a actualizar * @returns bool */ private static function upgradeTo($version) { $log = new Log(_('Actualizar BBDD')); switch ($version) { case 110: $queries[] = 'ALTER TABLE `accFiles` CHANGE COLUMN `accfile_name` `accfile_name` VARCHAR(100) NOT NULL'; $queries[] = 'ALTER TABLE `accounts` ADD COLUMN `account_otherGroupEdit` BIT(1) NULL DEFAULT 0 AFTER `account_dateEdit`, ADD COLUMN `account_otherUserEdit` BIT(1) NULL DEFAULT 0 AFTER `account_otherGroupEdit`;'; $queries[] = 'CREATE TABLE `accUsers` (`accuser_id` INT NOT NULL AUTO_INCREMENT,`accuser_accountId` INT(10) UNSIGNED NOT NULL,`accuser_userId` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`accuser_id`), INDEX `idx_account` (`accuser_accountId` ASC)) DEFAULT CHARSET=utf8;'; $queries[] = 'ALTER TABLE `accHistory` ADD COLUMN `accHistory_otherUserEdit` BIT NULL AFTER `acchistory_mPassHash`, ADD COLUMN `accHistory_otherGroupEdit` VARCHAR(45) NULL AFTER `accHistory_otherUserEdit`;'; $queries[] = 'ALTER TABLE `accFiles` CHANGE COLUMN `accfile_type` `accfile_type` VARCHAR(100) NOT NULL ;'; break; case 1121: $queries[] = 'ALTER TABLE `categories` ADD COLUMN `category_description` VARCHAR(255) NULL AFTER `category_name`;'; $queries[] = 'ALTER TABLE `usrProfiles` ADD COLUMN `userProfile_pAppMgmtMenu` BIT(1) NULL DEFAULT b\'0\' AFTER `userProfile_pUsersMenu`,CHANGE COLUMN `userProfile_pConfigCategories` `userProfile_pAppMgmtCategories` BIT(1) NULL DEFAULT b\'0\' AFTER `userProfile_pAppMgmtMenu`,ADD COLUMN `userProfile_pAppMgmtCustomers` BIT(1) NULL DEFAULT b\'0\' AFTER `userProfile_pAppMgmtCategories`;'; break; case 1122: $queries[] = 'ALTER TABLE `usrData` CHANGE COLUMN `user_login` `user_login` VARCHAR(50) NOT NULL ,CHANGE COLUMN `user_email` `user_email` VARCHAR(80) NULL DEFAULT NULL ;'; break; case 1123: $queries[] = 'CREATE TABLE `usrPassRecover` (`userpassr_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `userpassr_userId` SMALLINT UNSIGNED NOT NULL,`userpassr_hash` VARBINARY(40) NOT NULL,`userpassr_date` INT UNSIGNED NOT NULL,`userpassr_used` BIT(1) NOT NULL DEFAULT b\'0\', PRIMARY KEY (`userpassr_id`),INDEX `IDX_userId` (`userpassr_userId` ASC, `userpassr_date` ASC)) DEFAULT CHARSET=utf8;'; $queries[] = 'ALTER TABLE `log` ADD COLUMN `log_ipAddress` VARCHAR(45) NOT NULL AFTER `log_userId`;'; $queries[] = 'ALTER TABLE `usrData` ADD COLUMN `user_isChangePass` BIT(1) NULL DEFAULT b\'0\' AFTER `user_isMigrate`;'; break; case 11213: $queries[] = 'ALTER TABLE `usrData` CHANGE COLUMN `user_mPass` `user_mPass` VARBINARY(32) NULL DEFAULT NULL ,CHANGE COLUMN `user_lastLogin` `user_lastLogin` DATETIME NULL DEFAULT NULL ,CHANGE COLUMN `user_lastUpdate` `user_lastUpdate` DATETIME NULL DEFAULT NULL, CHANGE COLUMN `user_mIV` `user_mIV` VARBINARY(32) NULL ;'; $queries[] = 'ALTER TABLE `accounts` CHANGE COLUMN `account_login` `account_login` VARCHAR(50) NULL DEFAULT NULL ;'; break; case 11219: $queries[] = 'ALTER TABLE `accounts` CHANGE COLUMN `account_pass` `account_pass` VARBINARY(255) NOT NULL ;'; $queries[] = 'ALTER TABLE `accHistory` CHANGE COLUMN `acchistory_pass` `acchistory_pass` VARBINARY(255) NOT NULL ;'; break; case 11220: $queries[] = 'ALTER TABLE `usrData` CHANGE COLUMN `user_pass` `user_pass` VARBINARY(255) NOT NULL,CHANGE COLUMN `user_mPass` `user_mPass` VARBINARY(255) DEFAULT NULL ;'; break; case 12001: $queries[] = 'ALTER TABLE `accounts` CHANGE COLUMN `account_userEditId` `account_userEditId` TINYINT(3) UNSIGNED NULL DEFAULT NULL, CHANGE COLUMN `account_dateEdit` `account_dateEdit` DATETIME NULL DEFAULT NULL;'; $queries[] = 'ALTER TABLE `accHistory` CHANGE COLUMN `acchistory_userEditId` `acchistory_userEditId` TINYINT(3) UNSIGNED NULL DEFAULT NULL, CHANGE COLUMN `acchistory_dateEdit` `acchistory_dateEdit` DATETIME NULL DEFAULT NULL;'; $queries[] = 'ALTER TABLE `accHistory` CHANGE COLUMN `accHistory_otherGroupEdit` `accHistory_otherGroupEdit` BIT NULL DEFAULT b\'0\';'; $queries[] = 'ALTER TABLE `usrProfiles` ADD COLUMN `userProfile_profile` BLOB NOT NULL;'; $queries[] = 'ALTER TABLE `usrData` ADD `user_preferences` BLOB NULL;'; $queries[] = 'CREATE TABLE usrToGroups (usertogroup_id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,usertogroup_userId INT UNSIGNED NOT NULL,usertogroup_groupId INT UNSIGNED NOT NULL) DEFAULT CHARSET=utf8;'; $queries[] = 'CREATE INDEX IDX_accountId ON usrToGroups (usertogroup_userId)'; $queries[] = 'ALTER TABLE `accFiles` ADD `accFile_thumb` BLOB NULL;'; $queries[] = 'CREATE TABLE `authTokens` (`authtoken_id` int(11) NOT NULL AUTO_INCREMENT,`authtoken_userId` int(11) NOT NULL,`authtoken_token` varbinary(100) NOT NULL,`authtoken_actionId` smallint(5) unsigned NOT NULL,`authtoken_createdBy` smallint(5) unsigned NOT NULL,`authtoken_startDate` int(10) unsigned NOT NULL,PRIMARY KEY (`authtoken_id`),UNIQUE KEY `unique_authtoken_id` (`authtoken_id`),KEY `IDX_checkToken` (`authtoken_userId`,`authtoken_actionId`,`authtoken_token`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;'; $queries[] = 'CREATE TABLE `customFieldsDef` (`customfielddef_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `customfielddef_module` smallint(5) unsigned NOT NULL, `customfielddef_field` blob NOT NULL, PRIMARY KEY (`customfielddef_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;'; $queries[] = 'CREATE TABLE `customFieldsData` (`customfielddata_id` int(10) unsigned NOT NULL AUTO_INCREMENT,`customfielddata_moduleId` smallint(5) unsigned NOT NULL,`customfielddata_itemId` int(10) unsigned NOT NULL,`customfielddata_defId` int(10) unsigned NOT NULL,`customfielddata_data` longblob,`customfielddata_iv` varbinary(128) DEFAULT NULL, PRIMARY KEY (`customfielddata_id`), KEY `IDX_DEFID` (`customfielddata_defId`), KEY `IDX_DELETE` (`customfielddata_itemId`,`customfielddata_moduleId`), KEY `IDX_UPDATE` (`customfielddata_moduleId`,`customfielddata_itemId`,`customfielddata_defId`), KEY `IDX_ITEM` (`customfielddata_itemId`), KEY `IDX_MODULE` (`customfielddata_moduleId`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;'; break; case 12002: $queries[] = 'ALTER TABLE config CHANGE config_value config_value VARCHAR(255);'; $queries[] = 'ALTER TABLE usrData CHANGE user_pass user_pass VARBINARY(255);'; $queries[] = 'ALTER TABLE usrData CHANGE user_hashSalt user_hashSalt VARBINARY(128);'; $queries[] = 'ALTER TABLE accHistory CHANGE acchistory_mPassHash acchistory_mPassHash VARBINARY(255);'; break; default: $log->addDescription(_('No es necesario actualizar la Base de Datos.')); return true; } foreach ($queries as $query) { try { DB::getQuery($query, __FUNCTION__); } catch (SPException $e) { $log->addDescription(_('Error al aplicar la actualización de la Base de Datos.') . ' (v' . $version . ')'); $log->addDescription('ERROR: ' . $e->getMessage() . ' (' . $e->getCode() . ')'); $log->writeLog(); Email::sendEmail($log); return false; } } $log->addDescription(_('Actualización de la Base de Datos realizada correctamente.') . ' (v' . $version . ')'); $log->writeLog(); Email::sendEmail($log); return true; }
/** * Obtener una nueva instancia de la clase inicializada * * @param $action string La acción realizada * @param null $description string La descripción de la acción realizada * @return Log */ public static function writeNewLogAndEmail($action, $description = null) { $log = new Log($action, $description); $log->writeLog(); Email::sendEmail($log); return $log; }
/** * Reporting Bug, Feature, or Enhancement. * * @access public * @param integer $userId * @param string $subject * @param string $label * @param string $message * @return bool * */ public function reportBug($userId, $subject, $label, $message) { $validation = new Validation(); if (!$validation->validate(["Subject" => [$subject, "required|minLen(4)|maxLen(80)"], "Label" => [$label, "required|inArray(" . Utility::commas(["bug", "feature", "enhancement"]) . ")"], "Message" => [$message, "required|minLen(4)|maxLen(1800)"]])) { $this->errors = $validation->errors(); return false; } $curUser = $this->getProfileInfo($userId); $data = ["subject" => $subject, "label" => $label, "message" => $message]; //email will be sent to the admin Email::sendEmail(EMAIL_REPORT_BUG, ADMIN_EMAIL, ["id" => $userId, "name" => $curUser["name"]], $data); return true; }
/** * Function used for get reviews on page load * @param string $refid referral id , string $userid user id * @author Gaurav Bhandari */ public function rating($refid = NULL, $userid = NULL) { if (empty($refid) || empty($userid)) { $this->redirect(array('controller' => 'pages', 'action' => 'home')); } $referralId = $this->Encryption->decode($refid); $userId = $this->Encryption->decode($userid); $userInfo = $this->User->userInfoById($userId); $checkValid = $this->ReceivedReferral->find('first', array('conditions' => array('ReceivedReferral.id' => $referralId, 'ReceivedReferral.to_user_id' => $userId))); if ($checkValid) { if (!empty($checkValid['ReceivedReferral']['rating_status'])) { if (date('Y-m-d H:i:s') > date('Y-m-d H:i:s', strtotime($checkValid['Review']['created'] . ' + 15 minutes'))) { $this->Session->setFlash(__('You have already submitted your review for this user'), 'Front/flash_bad'); } else { $data['Review']['services'] = $checkValid['Review']['services']; $data['Review']['knowledge'] = $checkValid['Review']['knowledge']; $data['Review']['communication'] = $checkValid['Review']['communication']; $data['Review']['comments'] = $checkValid['Review']['comments']; $timeleft = strtotime(date("Y-m-d H:i:s")) - strtotime($checkValid["Review"]["created"]); $this->set(compact('data')); $timeValid = 1; } } } else { $this->Session->setFlash(__('Invalid link'), 'Front/flash_bad'); $this->redirect(array('controller' => 'pages', 'action' => 'home')); } if ($this->request->is('post')) { $checkValid = $this->ReceivedReferral->find('first', array('conditions' => array('ReceivedReferral.id' => $referralId, 'ReceivedReferral.to_user_id' => $userId))); if ($checkValid) { if (empty($checkValid['ReceivedReferral']['rating_status']) || isset($timeValid)) { $this->request->data['Review']['services'] = !empty($this->request->data['Review']['services']) ? $this->request->data['Review']['services'] : 0; $this->request->data['Review']['knowledge'] = !empty($this->request->data['Review']['knowledge']) ? $this->request->data['Review']['knowledge'] : 0; $this->request->data['Review']['communication'] = !empty($this->request->data['Review']['communication']) ? $this->request->data['Review']['communication'] : 0; $this->request->data['Review']['referral_id'] = $this->Encryption->decode($this->request->data['Review']['referral_id']); $this->request->data['Review']['user_id'] = $this->Encryption->decode($this->request->data['Review']['user_id']); $this->request->data['Review']['group_id'] = $this->Encryption->decode($userInfo['Groups']['id']); $total = $this->request->data['Review']['services'] + $this->request->data['Review']['knowledge'] + $this->request->data['Review']['communication']; $this->request->data['Review']['rating'] = round($total / Configure::read('RATING_TYPE_NO')); if (empty($checkValid['ReceivedReferral']['rating_status'])) { $this->Review->create(); if ($this->Review->save($this->request->data)) { $this->request->data['LiveFeed']['to_user_id'] = $userId; $this->request->data['LiveFeed']['from_user_id'] = $referralId; $this->request->data['LiveFeed']['group_id'] = $this->Encryption->decode($userInfo['Groups']['id']); $this->request->data['LiveFeed']['feed_type'] = 'review'; $this->LiveFeed->save($this->request->data['LiveFeed']); $this->ReceivedReferral->id = $referralId; $this->ReceivedReferral->saveField('rating_status', 1); $userData = $this->Review->findByReferralId($referralId); $emailLib = new Email(); $subject = "FoxHopr: You have received a review"; $template = "referral_rating_success"; $format = "both"; $business_owner_name = $userData['BusinessOwner']['fname'] . " " . $userData['BusinessOwner']['lname']; $url = Configure::read('SITE_URL') . 'reviews/index'; $variable = array('businessowner' => $business_owner_name, 'url' => $url); $to = $userData['User']['user_email']; $success = $emailLib->sendEmail($to, $subject, $variable, $template, $format); $this->Session->setFlash(__('Thank You for submitting your review.'), 'Front/flash_good'); $this->redirect(array('controller' => 'reviews', 'action' => 'rating', $refid, $userid)); } else { $this->Session->setFlash(__('Review not saved this time. Please try again later.'), 'Front/flash_bad'); } } elseif (isset($timeValid)) { $this->Review->id = $this->Encryption->decode($checkValid['Review']['id']); $this->Review->save($this->request->data['Review']); $this->Session->setFlash(__('Thank You for submitting your review.'), 'Front/flash_good'); $this->redirect(array('controller' => 'reviews', 'action' => 'rating', $refid, $userid)); } } else { $this->Session->setFlash(__('You have already submitted your review for this user.'), 'Front/flash_bad'); $this->redirect(array('controller' => 'reviews', 'action' => 'rating', $refid, $userid)); } } } $this->set('action', 'rating'); if (isset($timeleft) && $timeleft >= 0) { $this->set('timeleft', $timeleft); } else { $this->set('timeleft', '0'); } $this->set(compact('refid', 'userid', 'checkValid', 'userInfo')); }