/** * Process * Works out what's going on. * The API does the loading, saving, updating - this page just displays the right form(s), checks password validation and so on. * After that, it'll print a success/failure message depending on what happened. * It also checks to make sure that you're an admin before letting you add or delete. * It also checks you're not going to delete your own account. * If you're not an admin user, it won't let you edit anyone elses account and it won't let you delete your own account either. * * @see PrintHeader * @see ParseTemplate * @see IEM::getDatabase() * @see GetUser * @see GetLang * @see User_API::Set * @see PrintEditForm * @see CheckUserSystem * @see PrintManageUsers * @see User_API::Find * @see User_API::Admin * @see PrintFooter * * @return Void Doesn't return anything, passes control over to the relevant function and prints that functions return message. */ function Process() { $action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : ''; if (!in_array($action, $this->PopupWindows)) { $this->PrintHeader(); } $thisuser = IEM::getCurrentUser(); $checkaction = $action; if ($action == 'generatetoken') { $checkaction = 'manage'; } if (!$thisuser->HasAccess('users', $checkaction)) { $this->DenyAccess(); } if ($action == 'processpaging') { $this->SetPerPage($_GET['PerPageDisplay']); $action = ''; } switch ($action) { case 'generatetoken': $check_fields = array('username', 'fullname', 'emailaddress'); foreach ($check_fields as $field) { if (!isset($_POST[$field])) { exit; } $$field = $_POST[$field]; } $user = GetUser(); echo htmlspecialchars(sha1($username . $fullname . $emailaddress . GetRealIp(true) . time() . microtime()), ENT_QUOTES, SENDSTUDIO_CHARSET); exit; break; case 'save': $userid = (isset($_GET['UserID'])) ? $_GET['UserID'] : 0; if (empty($_POST)) { $GLOBALS['Error'] = GetLang('UserNotUpdated'); $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false); $this->PrintEditForm($userid); break; } $user = GetUser($userid); $username = false; if (isset($_POST['username'])) { $username = $_POST['username']; } $userfound = $user->Find($username); $error = false; $template = false; $duplicate_username = false; if ($userfound && $userfound != $userid) { $duplicate_username = true; $error = GetLang('UserAlreadyExists'); } $warnings = array(); $GLOBALS['Message'] = ''; if (!$duplicate_username) { $to_check = array(); foreach (array('status' => 'isLastActiveUser', 'admintype' => 'isLastSystemAdmin') as $area => $desc) { if (!isset($_POST[$area])) { $to_check[] = $desc; } if (isset($_POST[$area]) && $_POST[$area] == '0') { $to_check[] = $desc; } } if ($user->isAdmin()) { $to_check[] = 'isLastSystemAdmin'; } $error = $this->CheckUserSystem($userid, $to_check); if (!$error) { $smtptype = (isset($_POST['smtptype'])) ? $_POST['smtptype'] : 0; // Make sure smtptype is eiter 0 or 1 if ($smtptype != 1) { $smtptype = 0; } /** * This was added, because User's API uses different names than of the HTML form names. * HTML form names should stay the same to keep it consistant throught the application * * This will actually map HTML forms => User's API fields */ $areaMapping = array( 'trialuser' => 'trialuser', 'groupid' => 'groupid', 'username' => 'username', 'fullname' => 'fullname', 'emailaddress' => 'emailaddress', 'status' => 'status', 'admintype' => 'admintype', 'listadmintype' => 'listadmintype', 'segmentadmintype' => 'segmentadmintype', 'templateadmintype' => 'templateadmintype', 'editownsettings' => 'editownsettings', 'usertimezone' => 'usertimezone', 'textfooter' => 'textfooter', 'htmlfooter' => 'htmlfooter', 'infotips' => 'infotips', 'smtp_server' => 'smtpserver', 'smtp_u' => 'smtpusername', 'smtp_p' => 'smtppassword', 'smtp_port' => 'smtpport', 'usewysiwyg' => 'usewysiwyg', 'usexhtml' => 'usexhtml', 'enableactivitylog' => 'enableactivitylog', 'xmlapi' => 'xmlapi', 'xmltoken' => 'xmltoken', 'googlecalendarusername' => 'googlecalendarusername', 'googlecalendarpassword' => 'googlecalendarpassword', 'user_language' => 'user_language', 'adminnotify_email' => 'adminnotify_email', 'adminnotify_send_flag' => 'adminnotify_send_flag', 'adminnotify_send_threshold' => 'adminnotify_send_threshold', 'adminnotify_send_emailtext' => 'adminnotify_send_emailtext', 'adminnotify_import_flag' => 'adminnotify_import_flag', 'adminnotify_import_threshold' => 'adminnotify_import_threshold', 'adminnotify_import_emailtext' => 'adminnotify_import_emailtext' ); $group = API_USERGROUPS::getRecordById($_POST['groupid']); $totalEmails = (int) $group['limit_totalemailslimit']; $unlimitedEmails = $totalEmails == 0; // set fields foreach ($areaMapping as $p => $area) { $val = (isset($_POST[$p])) ? $_POST[$p] : ''; if (in_array($area, array('status', 'editownsettings'))) { if ($userid == $thisuser->userid) { $val = $thisuser->$area; } } $user->Set($area, $val); } // activity type $activity = IEM::requestGetPOST('eventactivitytype', '', 'trim'); if (!empty($activity)) { $activity_array = explode("\n", $activity); for ($i = 0, $j = count($activity_array); $i < $j; ++$i) { $activity_array[$i] = trim($activity_array[$i]); } } else { $activity_array = array(); } $user->Set('eventactivitytype', $activity_array); // the 'limit' things being on actually means unlimited. so check if the value is NOT set. foreach (array('permonth', 'perhour', 'maxlists') as $p => $area) { $limit_check = 'limit' . $area; $val = 0; if (!isset($_POST[$limit_check])) { $val = (isset($_POST[$area])) ? $_POST[$area] : 0; } $user->Set($area, $val); } if (SENDSTUDIO_MAXHOURLYRATE > 0) { if ($user->Get('perhour') == 0 || ($user->Get('perhour') > SENDSTUDIO_MAXHOURLYRATE)) { $user_hourly = $this->FormatNumber($user->Get('perhour')); if ($user->Get('perhour') == 0) { $user_hourly = GetLang('UserPerHour_Unlimited'); } $warnings[] = sprintf(GetLang('UserPerHourOverMaxHourlyRate'), $this->FormatNumber(SENDSTUDIO_MAXHOURLYRATE), $user_hourly); } } if ($smtptype == 0) { $user->Set('smtpserver', ''); $user->Set('smtpusername', ''); $user->Set('smtppassword', ''); $user->Set('smtpport', 25); } if ($_POST['ss_p'] != '') { if ($_POST['ss_p_confirm'] != '' && $_POST['ss_p_confirm'] == $_POST['ss_p']) { $user->Set('password', $_POST['ss_p']); } else { $error = GetLang('PasswordsDontMatch'); } } } if (!$error) { $user->RevokeAccess(); $temp = array(); if (!empty($_POST['permissions'])) { foreach ($_POST['permissions'] as $area => $p) { foreach ($p as $subarea => $k) { $temp[$subarea] = $user->GrantAccess($area, $subarea); } } } } } if (!$error) { $result = $user->Save(); if ($result) { FlashMessage(GetLang('UserUpdated'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Users')); } else { $GLOBALS['Message'] = GetFlashMessages(); $GLOBALS['Error'] = GetLang('UserNotUpdated'); $GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false); } } else { $GLOBALS['Error'] = $error; $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false); } if (!empty($warnings)) { $GLOBALS['Warning'] = implode('<br/>', $warnings); $GLOBALS['Message'] .= $this->ParseTemplate('WarningMsg', true, false); } $this->PrintEditForm($userid); break; case 'add': $temp = get_available_user_count(); if ($temp['normal'] == 0 && $temp['trial'] == 0) { $this->PrintManageUsers(); break; } $this->PrintEditForm(0); break; case 'delete': $users = IEM::requestGetPOST('users', array(), 'intval'); $deleteData = (IEM::requestGetPOST('deleteData', 0, 'intval') == 1); $this->DeleteUsers($users, $deleteData); break; case 'create': $user = New User_API(); $warnings = array(); $fields = array( 'trialuser', 'username', 'fullname', 'emailaddress', 'status', 'admintype', 'editownsettings', 'listadmintype', 'segmentadmintype', 'usertimezone', 'textfooter', 'htmlfooter', 'templateadmintype', 'infotips', 'smtpserver', 'smtpusername', 'smtpport', 'usewysiwyg', 'enableactivitylog', 'xmlapi', 'xmltoken', 'googlecalendarusername','googlecalendarpassword', 'adminnotify_email','adminnotify_send_flag','adminnotify_send_threshold', 'adminnotify_send_emailtext','adminnotify_import_flag','adminnotify_import_threshold', 'adminnotify_import_emailtext' ); if (!$user->Find($_POST['username'])) { foreach ($fields as $p => $area) { $val = (isset($_POST[$area])) ? $_POST[$area] : ''; $user->Set($area, $val); } // activity type $activity = IEM::requestGetPOST('eventactivitytype', '', 'trim'); if (!empty($activity)) { $activity_array = explode("\n", $activity); for ($i = 0, $j = count($activity_array); $i < $j; ++$i) { $activity_array[$i] = trim($activity_array[$i]); } } else { $activity_array = array(); } $user->Set('eventactivitytype', $activity_array); // the 'limit' things being on actually means unlimited. so check if the value is NOT set. foreach (array('permonth', 'perhour', 'maxlists') as $p => $area) { $limit_check = 'limit' . $area; $val = 0; if (!isset($_POST[$limit_check])) { $val = (isset($_POST[$area])) ? $_POST[$area] : 0; } $user->Set($area, $val); } if (SENDSTUDIO_MAXHOURLYRATE > 0) { if ($user->Get('perhour') == 0 || ($user->Get('perhour') > SENDSTUDIO_MAXHOURLYRATE)) { $user_hourly = $this->FormatNumber($user->Get('perhour')); if ($user->Get('perhour') == 0) { $user_hourly = GetLang('UserPerHour_Unlimited'); } $warnings[] = sprintf(GetLang('UserPerHourOverMaxHourlyRate'), $this->FormatNumber(SENDSTUDIO_MAXHOURLYRATE), $user_hourly); } } // this has a different post value otherwise firefox tries to pre-fill it. $smtp_password = ''; if (isset($_POST['smtp_p'])) { $smtp_password = $_POST['smtp_p']; } $user->Set('smtppassword', $smtp_password); $error = false; if ($_POST['ss_p'] != '') { if ($_POST['ss_p_confirm'] != '' && $_POST['ss_p_confirm'] == $_POST['ss_p']) { $user->Set('password', $_POST['ss_p']); } else { $error = GetLang('PasswordsDontMatch'); } } if (!$error) { if (!empty($_POST['permissions'])) { foreach ($_POST['permissions'] as $area => $p) { foreach ($p as $subarea => $k) { $user->GrantAccess($area, $subarea); } } } if (!empty($_POST['lists'])) { $user->GrantListAccess($_POST['lists']); } if (!empty($_POST['templates'])) { $user->GrantTemplateAccess($_POST['templates']); } if (!empty($_POST['segments'])) { $user->GrantSegmentAccess($_POST['segments']); } $GLOBALS['Message'] = ''; if (!empty($warnings)) { $GLOBALS['Warning'] = implode('<br/>', $warnings); $GLOBALS['Message'] .= $this->ParseTemplate('WarningMsg', true, false); } $user->Set('gettingstarted', 0); $user->Set('groupid', (int) IEM_Request::getParam('groupid')); $result = $user->Create(); if ($result == '-1') { FlashMessage(GetLang('UserNotCreated_License'), SS_FLASH_MSG_ERROR, IEM::urlFor('Users')); break; } else { if ($result) { FlashMessage(GetLang('UserCreated'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Users')); break; } else { FlashMessage(GetLang('UserNotCreated'), SS_FLASH_MSG_ERROR, IEM::urlFor('Users')); } } } else { $GLOBALS['Error'] = $error; } } else { $GLOBALS['Error'] = GetLang('UserAlreadyExists'); } $GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false); $details = array(); foreach (array('FullName', 'EmailAddress', 'Status', 'AdminType', 'ListAdminType', 'SegmentAdminType', 'TemplateAdminType', 'InfoTips', 'forcedoubleoptin', 'forcespamcheck', 'smtpserver', 'smtpusername', 'smtpport') as $p => $area) { $lower = strtolower($area); $val = (isset($_POST[$lower])) ? $_POST[$lower] : ''; $details[$area] = $val; } $this->PrintEditForm(0, $details); break; case 'edit': $userid = IEM::requestGetGET('UserID', 0, 'intval'); if ($userid == 0) { $this->DenyAccess(); } $this->PrintEditForm($userid); break; case 'sendpreviewdisplay': $this->PrintHeader(true); $this->SendTestPreviewDisplay('index.php?Page=Users&Action=SendPreview', 'self.parent.getSMTPPreviewParameters()'); $this->PrintFooter(true); break; case 'testgooglecalendar': $status = array( 'status' => false, 'message' => '' ); try { $details = array( 'username' => $_REQUEST['gcusername'], 'password' => $_REQUEST['gcpassword'] ); $this->GoogleCalendarAdd($details, true); $status['status'] = true; $status['message'] = GetLang('GooglecalendarTestSuccess'); } catch (Exception $e) { $status['message'] = GetLang('GooglecalendarTestFailure'); } print GetJSON($status); break; case 'sendpreview': $this->SendTestPreview(); break; default: $this->PrintManageUsers(); break; } if (!in_array($action, $this->PopupWindows)) { $this->PrintFooter(); } }
/** * MakeViewPopupMenu * Return "view" popup menus * * @param Array $search_info Search info * @param User_API $user (REF) Current user record * @return String Returns "View" popup menu HTML string * * @uses GetLang() * @uses SendStudio_Functions::ParseTemplate() */ function MakeViewPopupMenu($search_info, &$user) { $tempCommonRows = array(); $tempListRows = array(); $tempSegmentRows = array(); $tempSelectedListID = 0; $tempSelectedSegmentID = '-'; $tempSelectedAllList = false; if (array_key_exists('List', $search_info)) { $tempSelectedListID = intval($search_info['List']); } if (array_key_exists('Segment', $search_info) && is_array($search_info['Segment'])) { $tempSelectedSegmentID = $search_info['Segment']; } $tempSelectedAllList = ($tempSelectedListID == 0 && $tempSelectedSegmentID == 0); /** * List views */ if ($user->HasAccess('Lists') && !empty($search_info['List'])) { $tempListList = $user->GetLists(); foreach ($tempListList as $tempListID => $tempListRecord) { $GLOBALS['RowAction'] = 'index.php?Page=Subscribers&Action=Manage&Lists[]=' . $tempListID; $GLOBALS['RowTitle'] = htmlspecialchars($tempListRecord['name'], ENT_QUOTES, SENDSTUDIO_CHARSET); $GLOBALS['RowCaption'] = ' <img border="0" src="images/nodejoinsmall.gif" /> ' . htmlspecialchars($this->TruncateName($tempListRecord['name'], 55), ENT_QUOTES, SENDSTUDIO_CHARSET); if ($tempSelectedListID == $tempListID) { $GLOBALS['RowCaption'] = '<b>' . $GLOBALS['RowCaption'] . '</b>'; } array_push($tempListRows, $this->ParseTemplate('Subscribers_Manage_ViewPicker_Row', true)); } unset($tempListList); } else { $GLOBALS['DisplayStyleList'] = 'none'; } /** * ----- */ /** * Segment views */ if ($user->HasAccess('Segments') && !empty($search_info['Segment'])) { $tempSegmentList = $user->GetSegmentList(); if (count($tempSegmentList) == 0) { $GLOBALS['SegmentDisplay'] = 'none'; } else { $GLOBALS['SegmentDisplay'] = ''; foreach ($tempSegmentList as $tempSegmentID => $tempSegmentRecord) { $GLOBALS['RowAction'] = 'index.php?Page=Subscribers&Action=Manage&Segment=' . $tempSegmentID; $GLOBALS['RowTitle'] = htmlspecialchars($tempSegmentRecord['segmentname'], ENT_QUOTES, SENDSTUDIO_CHARSET); $GLOBALS['RowCaption'] = ' <img border="0" src="images/nodejoinsmall.gif" /> ' . htmlspecialchars($this->TruncateName($tempSegmentRecord['segmentname'], 55), ENT_QUOTES, SENDSTUDIO_CHARSET); if ($tempSelectedSegmentID == $tempSegmentID) { $GLOBALS['RowCaption'] = '<b>' . $GLOBALS['RowCaption'] . '</b>'; } array_push($tempSegmentRows, $this->ParseTemplate('Subscribers_Manage_ViewPicker_Row', true)); } unset($tempSegmentList); } } else { $GLOBALS['DisplayStyleSegment'] = 'none'; } /** * ----- */ unset($GLOBALS['RowCaption']); unset($GLOBALS['RowTitle']); unset($GLOBALS['RowAction']); $GLOBALS['CommonViews'] = implode('', $tempCommonRows); $GLOBALS['ListViews'] = implode('', $tempListRows); $GLOBALS['SegmentViews'] = implode('', $tempSegmentRows); $output = $this->ParseTemplate('Subscribers_Manage_ViewPicker', true); unset($GLOBALS['SegmentViews']); unset($GLOBALS['ListViews']); unset($GLOBALS['CommonViews']); return $output; }
// if we are installing or upgrading then we need to bypass this if (!IEM::isInstalled() && IEM::isInstalling() || IEM::hasUpgrade() && IEM::isUpgrading() || IEM::isCompletingUpgrade()) { $tempValid = true; break; } // Get cookie $tempCookie = IEM::requestGetCookie('IEM_CookieLogin', array()); if (empty($tempCookie)) { break; } // Check if cookie contains user information if (!is_array($tempCookie) || !isset($tempCookie['user'])) { break; } // Get user $tempUser = new User_API(); $tempUser->Load(intval($tempCookie['user'])); // Check if the user is a valid user if (!isset($tempUser->settings['LoginCheck']) || !$tempUser->userid || !$tempUser->Status()) { break; } // Check whether or not the random number matches if (!$tempUser->settings['LoginCheck'] == $tempCookie['rand']) { break; } // The cookie is valid! Update session accordingly IEM::userLogin($tempUser->userid); $tempValid = true; // Check if we have login preferences $tempLoginPref = IEM::requestGetCookie('IEM_LoginPreference', array()); if (is_array($tempLoginPref) && isset($tempLoginPref['takemeto'])) {
/** * _checkUserResourcePermission * Check if user have access to all of the resources that trigger email record has defined * * We need to do this here, because currently API shuldn't be checking any user permission. * Once user permission are being used in API, we can deprecate this function * * @param Array $record Associated array of the record * @param User_API $user User API * * @return Boolean Returns TRUE if user have all permission, FALSE otherwise * * @todo deprecate this when API take account user permission */ private function _checkUserResourcePermission($record, $user) { // If admin, don't worry about evaluating permission if ($user->Admin()) { return true; } $error = false; $userLists = $user->GetLists(); $userNewsletters = $user->GetNewsletters(); // Check if user have access to particular list if ($record['triggertype'] == 'f' && isset($record['data']['listid']) && !array_key_exists($record['data']['listid'], $userLists)) { trigger_error('Does not have access to contact list', E_USER_NOTICE); $error = true; } // Check if user have access to particular newsletter specified for link if ($record['triggertype'] == 'l' && isset($record['data']['linkid_newsletterid']) && !array_key_exists($record['data']['linkid_newsletterid'], $userNewsletters)) { trigger_error('Does not have access to specified newsletter', E_USER_NOTICE); $error = true; } // Check newsletter ID defined for "Newsletter Opened" event if ($record['triggertype'] == 'n' && isset($record['data']['newsletterid']) && !array_key_exists($record['data']['newsletterid'], $userNewsletters)) { trigger_error('Does not have access to specified newsletter', E_USER_NOTICE); $error = true; } // Check if list IDs defined for static date exists if ($record['triggertype'] == 's' && isset($record['data']['staticdate_listids'])) { foreach ($record['data']['staticdate_listids'] as $each) { if (!array_key_exists($each, $userLists)) { trigger_error('Does not have access to specified list', E_USER_NOTICE); $error = true; break; } } } // ----- The following are required for "send" action if (isset($record['triggeractions']['send']) && isset($record['triggeractions']['send']['enabled']) && $record['triggeractions']['send']['enabled']) { if (isset($record['triggeractions']['send']['newsletterid']) && !array_key_exists($record['triggeractions']['send']['newsletterid'], $userNewsletters)) { trigger_error('Newsletter does not exits', E_USER_NOTICE); return false; } } // ----- // ----- The following are required for "addlist" action if (isset($record['triggeractions']['addlist']) && isset($record['triggeractions']['addlist']['enabled']) && $record['triggeractions']['addlist']['enabled']) { if (isset($record['triggeractions']['addlist']['listid'])) { foreach ($record['triggeractions']['addlist']['listid'] as $each) { if (!array_key_exists($each, $userLists)) { trigger_error('Does not have access to specified newsletter', E_USER_NOTICE); $error = true; break; } } } } // ----- return !$error; }
/** * Checks whether this user is allowed to send these emails or not. * * @param object $user_object User Object to check. * @param int $queuesize The size of the queue to check. * @param int $queuetime The time when you are trying to send / schedule the queue. * * @return array Returns an array of status and a language variable describing why it can't be sent. This allows us to differentiate between whether it's a "maxemails" issue or a "per month" issue. */ public function CheckUserStats(User_API $user, $queueSize = 0, $queuetime=0) { // if they have no limits, then no need to do any other checks if ($user->hasUnlimitedCredit()) {return array(true, false);} $queueSize = (int) $queueSize; if (!$user->hasUnlimitedMonthlyCredit()){ $monthly = (int) API_USERS::creditAvailableThisMonth($user->userid, false, $queuetime); } if (!$user->hasUnlimitedTotalCredit()){ $total = (int) API_USERS::creditAvailableFixed($user->userid); } // do monthly credit check if (isset($monthly) && $queueSize > $monthly){return array(false, 'OverLimit_PerMonth');} // do total credit check if (isset($total) && $queueSize > $total) {return array(false, 'OverLimit_MaxEmails');} return array(true, false); }
// Also need the "permissions" parameter if (!isset($function_params['permissions'])) { array_push($tempRequired, 'permissions'); } } if (count($tempRequired) != 0) { SendResponse(false, 'Invalid parameters specified to use this function.'); exit(); } // ----- $user = New User_API(); $warnings = array(); // Load existing data if editing if ($editMode) { $param_userid = IEM::ifsetor($function_params['userid'], false); if (!$param_userid) { SendResponse(false, 'userid cannot be empty.'); exit(); } $status = $user->Load($param_userid, true); if (!$status) { SendResponse(false, 'Cannot load user record.'); exit(); }
/** * Record credit usage * This function will record credit usage for a particular user. * * @param record_Users|integer $user User record object or user ID * @param string $usagetype Usage type (see class constansts CREDIT_USAGETYPE_* for valid types) * @param integer $creditused The number of credits that are being used up * @param integer $jobid Associate job ID (OPTIONAL, default = 0) * @param integer $statid Associate statistic ID (OPTIONAL, default = 0) * @param integer $time Time of which the credit is being used (OPTIONAL, default = now) * * @return boolean Returns TRUE if successful, FALSE otherwise */ public static function creditUse($user, $usagetype, $creditused, $jobid = 0, $statid = 0, $time = 0, $evaluateWarnings = true) { $userid = 0; $usagetype = strtolower($usagetype); $creditused = intval($creditused); $jobid = intval($jobid); $statid = intval($statid); $time = intval($time); $db = IEM::getDatabase(); static $validTypes = null; if (is_null($validTypes)) { $validTypes = array(self::CREDIT_USAGETYPE_SENDAUTORESPONDER, self::CREDIT_USAGETYPE_SENDCAMPAIGN, self::CREDIT_USAGETYPE_SENDTRIGGER); } if (!$user instanceof record_Users) { $userid = intval($user); $user = API_USERS::getRecordByID($userid); } if (!$user) { trigger_error("API_USERS::creditUse -- Invalid user specified.", E_USER_NOTICE); return false; } if (!in_array($usagetype, $validTypes)) { trigger_error("API_USERS::creditUse -- Invalid credit type '{$usagetype}'.", E_USER_NOTICE); return false; } if ($creditused < 1) { trigger_error("API_USERS::creditUse -- Credit cannot be less than 1.", E_USER_NOTICE); return false; } if ($jobid < 0) { trigger_error("API_USERS::creditUse -- Invalid jobid specified.", E_USER_NOTICE); return false; } if ($statid < 0) { trigger_error("API_USERS::creditUse -- Invalid statid specified.", E_USER_NOTICE); return false; } if ($time < 0) { trigger_error("API_USERS::creditUse -- Time cannot be negative.", E_USER_NOTICE); return false; } // If user has unlimited emails credit, we don't need to record this $usersApi = new User_API($user->userid); if ($usersApi->hasUnlimitedCredit()) { return true; } // Check for cases (based on usage type) where credit does not need to be deducted switch ($usagetype) { case self::CREDIT_USAGETYPE_SENDTRIGGER: if (!SENDSTUDIO_CREDIT_INCLUDE_TRIGGERS) { return true; } break; case self::CREDIT_USAGETYPE_SENDAUTORESPONDER: if (!SENDSTUDIO_CREDIT_INCLUDE_AUTORESPONDERS) { return true; } break; } $time = $time == 0 ? time() : $time; $db->StartTransaction(); $tempStatus = $db->Query("\n\t\t\t\tINSERT INTO [|PREFIX|]user_credit (userid, transactiontype, transactiontime, credit, jobid, statid)\n\t\t\t\tVALUES ({$userid}, '{$usagetype}', {$time}, -{$creditused}, {$jobid}, {$statid})\n\t\t\t"); if (!$tempStatus) { $db->RollbackTransaction(); trigger_error("API_USERS::creditUse -- Unable to insert credit usage into database: " . $db->Error(), E_USER_NOTICE); return false; } /**@TODO REMOVE ALL REFERENCES TO OLD CREDIT SYSTEM /* // Record this in the credit summary table $tempTimeperiod = mktime(0, 0, 0, date('n'), 1, date('Y')); $tempQuery; // Since MySQL have a direct query which will insert/update in one go, we can utilzie this. if (SENDSTUDIO_DATABASE_TYPE == 'mysql') { $tempQuery = " INSERT INTO [|PREFIX|]user_credit_summary (userid, startperiod, credit_used) VALUES ({$userid}, {$tempTimeperiod}, {$creditused}) ON DUPLICATE KEY UPDATE credit_used = credit_used + {$creditused} "; // Do we need to do an INSERT or an UPDATE query ?? } else { $tempRS = $db->Query("SELECT usagesummaryid FROM [|PREFIX|]user_credit_summary WHERE userid = {$userid} AND startperiod = {$tempTimeperiod}"); if (!$tempRS) { $db->RollbackTransaction(); trigger_error("API_USERS::creditUse -- Cannot query user_credit_summary table: " . $db->Error(), E_USER_NOTICE); return false; } if ($db->CountResult($tempRS) == 0) { $tempQuery = " INSERT INTO [|PREFIX|]user_credit_summary (userid, startperiod, credit_used) VALUES ({$userid}, {$tempTimeperiod}, {$creditused}) "; } else { $tempSummaryID = $db->FetchOne($tempRS, 'usagesummaryid'); $tempQuery = " UPDATE [|PREFIX|]user_credit_summary SET credit_used = credit_used + {$creditused} WHERE usagesummaryid = {$tempSummaryID} "; } $db->FreeResult($tempRS); } $tempStatus = $db->Query($tempQuery); if (!$tempStatus) { $db->RollbackTransaction(); trigger_error("API_USERS::creditUse -- Unable to update/insert user_credit_summary table: " . $db->Error(), E_USER_NOTICE); return false; }*/ $db->CommitTransaction(); if ($evaluateWarnings) { return self::creditEvaluateWarnings($userid); } else { return true; } }
/** * _checkPermissionCanEdit * Check whether or not a user can edit a segment * * Checking user privilege in this instance will also means checking * whether or not a user have access to all mailing list used in a segment. * Once lists used in a segment become "restricted" to a user, user should not be able to edit * the segment at all. * * Here's the logic: * (1) If Admin go to (7), otherwise go to (2) * (2) If segment is owned by user, go to (3), otherwise go (4) * (3) If user have "edit" permission, go to (7), otherwise (6) * (4) If user is allowed to have "edit" access to the segment, then check (5), otherwise go (7) * (5) If user DO NOT have access to all the lists in the segment, go (6), otherwise go (7) * (6) CANNOT EDIT * (7) CAN EDIT * * @param Segment_API $segmentapi Current segment API * @param User_API $userapi Current user API * * @return Boolean Returns TRUE if user have edit privilege on segment, FALSE otherwise * * @uses User_API::HasAccess() * @uses User_API::GetLists() * * @access private */ function _checkPermissionCanEdit($segmentapi, $userapi) { if ($userapi->Admin()) { return true; } $haveAccess = false; $userList = array_keys($userapi->GetLists()); if ($segmentapi->ownerid == $userapi->userid) { if ($userapi->HasAccess('Segments', 'Edit')) { $haveAccess = true; } } else { if ($userapi->HasAccess('Segments', 'Edit', $segmentapi->segmentid)) { if (count(array_intersect($userList, $segmentapi->searchinfo['Lists'])) == count($segmentapi->searchinfo['Lists'])) { $haveAccess = true; } } } return $haveAccess; }