Пример #1
0
 public function startUserSession($row)
 {
     $login_key = $_SESSION['login_key'];
     # Unset all session variable
     $_SESSION = array();
     # Destroy session
     session_destroy();
     # New session name
     session_name(SESS_NAME);
     # New session id
     session_id($login_key);
     # Start Session
     session_start();
     $ts = new Date();
     # Initialize session
     $_SESSION['start_ts'] = $ts->getTs();
     $_SESSION['start_ts_str'] = $ts->getDate();
     $_SESSION['auth_state'] = 'user';
     $_SESSION['user_id'] = $row['id'];
     $_SESSION['login_key'] = $login_key;
     # Destroy old User object
     $this->user->__destruct();
     # Initialize new User object
     $this->user = User::getInstance($_SESSION['user_id']);
 }
Пример #2
0
function sendSqlDump()
{
    $result = BADGER_VERSION_TAG . "\n";
    $result .= getDbDump();
    $now = new Date();
    header('Content-Type: text/sql');
    header('Content-Disposition: attachment; filename="BADGER-' . getBadgerDbVersion() . '-DatabaseBackup-' . $now->getDate() . '.sql"');
    header('Content-Length: ' . strlen($result));
    echo $result;
}
Пример #3
0
 function getTime($format)
 {
     // reuse Date - pretty much does the same thing
     // I would have just deleted this class altogether
     // and just used the Date Model but the instructions said
     // each page should have it's own class - not knowing
     // completely what they meant, I just decided to
     // do it this way.  Hopefully it's not a ding in
     // judgement.  Adam
     return Date::getDate($format);
 }
 /**
  * Performs the action; returns true on success, false on error.
  *
  * @param $p_context - the current context object
  * @return bool
  */
 public function takeAction(CampContext &$p_context)
 {
     $p_context->default_url->reset_parameter('f_' . $this->m_name);
     $p_context->url->reset_parameter('f_' . $this->m_name);
     if (PEAR::isError($this->m_error)) {
         return false;
     }
     $auth = Zend_Auth::getInstance();
     $user = new User($p_context->user->identifier);
     if ($user->getUserId() != $auth->getIdentity() || $user->getUserId() == 0) {
         $this->m_error = new PEAR_Error('You must be logged in to create or edit your subscription.', ACTION_EDIT_SUBSCRIPTION_ERR_NO_USER);
         return false;
     }
     $subscriptions = Subscription::GetSubscriptions($p_context->publication->identifier, $user->getUserId());
     if (count($subscriptions) == 0) {
         $subscription = new Subscription();
         $created = $subscription->create(array('IdUser' => $user->getUserId(), 'IdPublication' => $p_context->publication->identifier, 'Active' => 'Y', 'Type' => $this->m_subscriptionType == 'trial' ? 'T' : 'P'));
         if (!$created) {
             $this->m_error = new PEAR_Error('Internal error (code 1)', ACTION_EDIT_SUBSCRIPTION_ERR_INTERNAL);
             exit(1);
         }
     } else {
         $subscription = $subscriptions[0];
     }
     $publication = new Publication($p_context->publication->identifier);
     $subscriptionDays = $this->computeSubscriptionDays($publication, $p_context->publication->subscription_time);
     $startDate = new Date();
     $columns = array('StartDate' => $startDate->getDate(), 'Days' => $subscriptionDays, 'PaidDays' => $this->m_subscriptionType == 'trial' ? $subscriptionDays : 0, 'NoticeSent' => 'N');
     if ($this->m_properties['subs_by_type'] == 'publication') {
         $sectionsList = Section::GetUniqueSections($p_context->publication->identifier);
         foreach ($sectionsList as $section) {
             $this->m_sections[] = $section['id'];
         }
     }
     foreach ($this->m_languages as $languageId) {
         foreach ($this->m_sections as $sectionNumber) {
             $subsSection = new SubscriptionSection($subscription->getSubscriptionId(), $sectionNumber, $languageId);
             $subsSection->create($columns);
         }
     }
     $fields = array('SubsType', 'tx_subs', 'nos', 'unitcost', 'unitcostalllang', 'f_substype', 'cb_subs', 'subs_all_languages', 'suma', 'tpl', 'subscription_language');
     foreach (CampRequest::GetInput() as $field => $value) {
         if (strncmp('tx_subs', $field, strlen('tx_subs')) == 0) {
             $fields[] = $field;
         }
     }
     foreach ($fields as $fieldName) {
         $p_context->default_url->reset_parameter($fieldName);
         $p_context->url->reset_parameter($fieldName);
     }
     $this->m_error = ACTION_OK;
     return true;
 }
 /**
  * A method that uses the getAllCampaigns() method to obtain all campaigns
  * that meet the requirements of this class. That is:
  *
  * - The campaign has an expiration date (that is not already passed); and
  * - As a result of the above, the campaign must have an activation date that has
  *   passed, or has the default fake activation date; and
  * - The campaign is active, and has a priority of at least 1; and
  * - The campaign has inventory requirements for the duration of its activation.
  *
  * @access private
  * @return array An array of {@link OX_Maintenance_Priority_Campaign} objects.
  */
 function _getValidCampaigns()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     // Get current date
     $oDate = new Date($this->_getDate());
     $oDate->toUTC();
     $dateYMD = $oDate->getDate(DATE_FORMAT_ISO);
     $oDbh = OA_DB::singleton();
     $table = $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['campaigns'], true);
     $aWheres = array(array("{$table}.priority >= 1", 'AND'), array("{$table}.status = " . OA_ENTITY_STATUS_RUNNING, 'AND'), array("{$table}.expire_time >= '{$dateYMD}'", 'AND'), array("({$table}.views > 0 OR {$table}.clicks > 0 OR {$table}.conversions > 0)", 'AND'));
     return $this->_getAllCampaigns($aWheres);
 }
Пример #6
0
 /**
  * A helper method to set applicationvariables
  *
  * @param Date $oScheduledDate
  * @param Date $oDate
  */
 function setVariables($oScheduledDate, $oDate)
 {
     if (isset($oScheduledDate)) {
         OA_Dal_ApplicationVariables::set('maintenance_cron_timestamp', $oScheduledDate->getDate(DATE_FORMAT_UNIXTIME));
     } else {
         OA_Dal_ApplicationVariables::delete('maintenance_cron_timestamp');
     }
     if (isset($oDate)) {
         OA_Dal_ApplicationVariables::set('maintenance_timestamp', $oDate->getDate(DATE_FORMAT_UNIXTIME));
     } else {
         OA_Dal_ApplicationVariables::delete('maintenance_timestamp');
     }
 }
Пример #7
0
 public function compare(Date $date)
 {
     $currentTime = strtotime($this->getDate());
     $argTime = strtotime($date->getDate());
     if ($currentTime > $argTime) {
         return 1;
         //argumento menor
     } elseif ($currentTime < $argTime) {
         return -1;
         //atual menor
     }
     return 0;
     //iguais
 }
Пример #8
0
/**
 * Returns the Account balance for $account at the end of each day between $startDate and $endDate.
 * 
 * Considers the planned transactions of $account.
 * 
 * @param object $account The Account object for which the balance should be calculated. 
 * It should be 'fresh', i. e. no transactions of any type should have been fetched from it.
 * @param object $startDate The first date the balance should be calculated for as Date object.
 * @param object $endDate The last date the balance should be calculated for as Date object.
 * @return array Array of Amount objects corresponding to the balance of $account at each day between
 * $startDate and $endDate. The array keys are the dates as ISO-String (yyyy-mm-dd). 
 */
function getDailyAmount($account, $startDate, $endDate)
{
    $account->setTargetFutureCalcDate($endDate);
    $account->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc')));
    $result = array();
    $startDate->setHour(0);
    $startDate->setMinute(0);
    $startDate->setSecond(0);
    $endDate->setHour(0);
    $endDate->setMinute(0);
    $endDate->setSecond(0);
    $currentDate = new Date($startDate);
    $currentAmount = new Amount();
    //foreach transaction
    while ($currentTransaction = $account->getNextTransaction()) {
        if ($currentDate->after($endDate)) {
            //we reached $endDAte
            break;
        }
        //fill all dates between last and this transaction with the old amount
        while (is_null($tmp = $currentTransaction->getValutaDate()) ? false : $currentDate->before($tmp)) {
            $result[$currentDate->getDate()] = new Amount($currentAmount);
            $currentDate->addSeconds(24 * 60 * 60);
            if ($currentDate->after($endDate)) {
                //we reached $endDAte
                break;
            }
        }
        $currentAmount->add($currentTransaction->getAmount());
    }
    //fill all dates after the last transaction with the newest amount
    while (Date::compare($currentDate, $endDate) <= 0) {
        $result[$currentDate->getDate()] = new Amount($currentAmount);
        $currentDate->addSeconds(24 * 60 * 60);
    }
    return $result;
}
Пример #9
0
function ListAttributes2011($attributes, $attributedata, $htmlchoice = 0, $userid = 0, $emaildoubleentry = 'no')
{
    global $strPreferHTMLEmail, $strPreferTextEmail, $strEmail, $tables, $table_prefix, $strPreferredFormat, $strText, $strHTML;
    if ($userid) {
        $data = array();
        $current = Sql_Fetch_array_Query("select * from {$GLOBALS["tables"]["user"]} where id = {$userid}");
        $datareq = Sql_Query("select * from {$GLOBALS["tables"]["user_attribute"]} where userid = {$userid}");
        while ($row = Sql_Fetch_Array($datareq)) {
            $data[$row["attributeid"]] = $row["value"];
        }
        $email = $current["email"];
        $htmlemail = $current["htmlemail"];
        # override with posted info
        foreach ($current as $key => $val) {
            if (isset($_POST[$key]) && $key != "password") {
                $current[$key] = $val;
            }
        }
    } else {
        if (isset($_REQUEST['email'])) {
            $email = stripslashes($_REQUEST["email"]);
        } else {
            $email = '';
        }
        if (isset($_POST['htmlemail'])) {
            $htmlemail = $_POST["htmlemail"];
        }
        $data = array();
        $current = array();
    }
    $textlinewidth = sprintf('%d', getConfig("textline_width"));
    if (!$textlinewidth) {
        $textlinewidth = 40;
    }
    list($textarearows, $textareacols) = explode(",", getConfig("textarea_dimensions"));
    if (!$textarearows) {
        $textarearows = 10;
    }
    if (!$textareacols) {
        $textareacols = 40;
    }
    $html = '';
    $html .= '<fieldset class="subscriberdetails">';
    $html .= sprintf('<div class="required"><label for="email">%s</label>
    <input type="text" name="email" value="%s" class="input email required" />', $GLOBALS["strEmail"], htmlspecialchars($email));
    if ($emaildoubleentry == 'yes') {
        if (!isset($_REQUEST['emailconfirm'])) {
            $_REQUEST['emailconfirm'] = '';
        }
        $html .= sprintf('<label for="emailconfirm">%s</label>
      <input type="text" name="emailconfirm" value="%s" class="input emailconfirm required" />', $GLOBALS["strConfirmEmail"], htmlspecialchars(stripslashes($_REQUEST["emailconfirm"])), $GLOBALS["strConfirmEmail"]);
    }
    if (ASKFORPASSWORD) {
        # we only require a password if there isnt one, so they can set it
        # otherwise they can keep the existing, if they do not enter anything
        if (!isset($current['password']) || !$current["password"]) {
            $pwdclass = "required";
            #  $html .= '<input type="hidden" name="passwordreq" value="1" />';
        } else {
            $pwdclass = 'attributename';
            #  $html .= '<input type="hidden" name="passwordreq" value="0" />';
        }
        $html .= sprintf('
      <label for="password">%s</label><input type="password" name="password" value="" class="input password required" />', $GLOBALS["strPassword"]);
        $html .= sprintf('
      <label for="password_check">%s</label><input type="password" name="password_check" value="" class="input password required" />', $GLOBALS["strPassword2"]);
    }
    $html .= '</div>';
    ## class=required
    $htmlchoice = 'checkforhtml';
    ## Write attribute fields
    switch ($htmlchoice) {
        case "textonly":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<input type="hidden" name="htmlemail" value="0" />');
            break;
        case "htmlonly":
            if (!isset($htmlemail)) {
                $htmlemail = 1;
            }
            $html .= sprintf('<input type="hidden" name="htmlemail" value="1" />');
            break;
        case "checkfortext":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<fieldset class="htmlchoice"><div><input type="checkbox" name="textemail" value="1" %s /><label for="textemail">%s</label></div></fieldset>', empty($htmlemail) ? 'checked="checked"' : '', $GLOBALS["strPreferTextEmail"]);
            break;
        case "radiotext":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
        case "radiohtml":
            if (!isset($htmlemail)) {
                $htmlemail = 1;
            }
            $html .= sprintf('<fieldset class="htmlchoice">
        <legend>%s</legend>
        <div><input type="radio" id="choicetext" name="htmlemail" value="0" %s /><label for="choicetext" class="htmlchoice">%s</label></div>
        <div><input type="radio" id="choicehtml" name="htmlemail" value="1" %s /><label for="choicehtml" class="htmlchoice">%s</label></div>
        </fieldset>', $GLOBALS["strPreferredFormat"], empty($htmlemail) ? 'checked="checked"' : '', $GLOBALS["strText"], !empty($htmlemail) ? 'checked="checked"' : '', $GLOBALS["strHTML"]);
            break;
        case "checkforhtml":
        default:
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<fieldset class="htmlchoice"><div><input type="checkbox" name="htmlemail" value="1" %s />
        <label for="htmlemail">%s</label></div></fieldset>', !empty($htmlemail) ? 'checked="checked"' : '', $GLOBALS["strPreferHTMLEmail"]);
            break;
    }
    $html .= "</fieldset>\n";
    $html .= '<fieldset class="attributes">' . "\n";
    $attids = join(',', array_keys($attributes));
    $output = array();
    if ($attids) {
        $res = Sql_Query("select * from {$GLOBALS["tables"]["attribute"]} where id in ({$attids})");
        while ($attr = Sql_Fetch_Array($res)) {
            $output[$attr["id"]] = '';
            if (!isset($data[$attr['id']])) {
                $data[$attr['id']] = '';
            }
            $attr["required"] = $attributedata[$attr["id"]]["required"];
            $attr["default_value"] = $attributedata[$attr["id"]]["default_value"];
            $fieldname = "attribute" . $attr["id"];
            #  print "<tr><td>".$attr["id"]."</td></tr>";
            if ($userid && !isset($_POST[$fieldname])) {
                # post values take precedence
                $val = Sql_Fetch_Row_Query(sprintf('select value from %s where
          attributeid = %d and userid = %d', $GLOBALS["tables"]["user_attribute"], $attr["id"], $userid));
                $_POST[$fieldname] = $val[0];
            } elseif (!isset($_POST[$fieldname])) {
                $_POST[$fieldname] = 0;
            }
            switch ($attr["type"]) {
                case "checkbox":
                    $output[$attr["id"]] = '';
                    # what they post takes precedence over the database information
                    if (isset($_POST[$fieldname])) {
                        $checked = !empty($_POST[$fieldname]) ? 'checked="checked"' : '';
                    } else {
                        $checked = !empty($data[$attr["id"]]) ? 'checked="checked"' : '';
                    }
                    $output[$attr["id"]] .= sprintf("\n" . '<input type="checkbox" name="%s" value="on" %s class="input%s" />', $fieldname, $checked, $attr["required"] ? ' required' : '');
                    $output[$attr["id"]] .= sprintf("\n" . '<label for="%s" class="%s">%s</label>', $fieldname, $attr["required"] ? 'required' : '', stripslashes($attr["name"]));
                    break;
                case "radio":
                    $output[$attr["id"]] .= sprintf("\n" . '<fieldset class="radiogroup %s"><legend>%s</legend>', $attr["required"] ? 'required' : '', stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    while ($value = Sql_Fetch_array($values_request)) {
                        if (!empty($_POST[$fieldname])) {
                            $checked = $_POST[$fieldname] == $value["id"] ? 'checked="checked"' : '';
                        } else {
                            if ($data[$attr["id"]]) {
                                $checked = $data[$attr["id"]] == $value["id"] ? 'checked="checked"' : '';
                            } else {
                                $checked = $attr["default_value"] == $value["name"] ? 'checked="checked"' : '';
                            }
                        }
                        $output[$attr["id"]] .= sprintf('<input type="radio" class="input%s" name="%s" value="%s" %s /><label for="%s">%s</label>', $attr["required"] ? ' required' : '', $fieldname, $value["id"], $checked, $fieldname, $value["name"]);
                    }
                    $output[$attr["id"]] . '</fieldset>';
                    break;
                case "select":
                    $output[$attr["id"]] .= sprintf("\n" . '<fieldset class="selectgroup %s"><label for="%s">%s</label>', $attr["required"] ? 'required' : '', $fieldname, stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    $output[$attr["id"]] .= sprintf('<select name="%s" class="input%s">', $fieldname, $attr["required"] ? 'required' : '');
                    while ($value = Sql_Fetch_array($values_request)) {
                        if (!empty($_POST[$fieldname])) {
                            $selected = $_POST[$fieldname] == $value["id"] ? 'selected="selected"' : '';
                        } elseif ($data[$attr["id"]]) {
                            $selected = $data[$attr["id"]] == $value["id"] ? 'selected="selected"' : '';
                        } else {
                            $selected = $attr["default_value"] == $value["name"] ? 'selected="selected"' : '';
                        }
                        if (preg_match('/^' . preg_quote(EMPTY_VALUE_PREFIX) . '/i', $value['name'])) {
                            $value['id'] = '';
                        }
                        $output[$attr["id"]] .= sprintf('<option value="%s" %s>%s</option>', $value["id"], $selected, stripslashes($value["name"]));
                    }
                    $output[$attr["id"]] .= "</select>";
                    $output[$attr["id"]] .= "</fieldset>";
                    break;
                case "checkboxgroup":
                    $output[$attr["id"]] .= sprintf("\n" . '<fieldset class="checkboxgroup %s"><label for="%s">%s</label>', $attr["required"] ? 'required' : '', $fieldname, stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    $cbCounter = 0;
                    while ($value = Sql_Fetch_array($values_request)) {
                        $cbCounter++;
                        $selected = '';
                        if (is_array($_POST[$fieldname])) {
                            $selected = in_array($value["id"], $_POST[$fieldname]) ? 'checked="checked"' : '';
                        } elseif ($data[$attr["id"]]) {
                            $selection = explode(",", $data[$attr["id"]]);
                            $selected = in_array($value["id"], $selection) ? 'checked="checked"' : '';
                        }
                        $output[$attr["id"]] .= sprintf('<input type="checkbox" name="%s[]" id="%s%d" class="input%s" value="%s" %s /><label for="%s%d">%s</label>', $fieldname, $fieldname, $cbCounter, $attr["required"] ? ' required' : '', $value["id"], $selected, $fieldname, $cbCounter, stripslashes($value["name"]));
                    }
                    $output[$attr["id"]] .= '</fieldset>';
                    break;
                case "textline":
                    $output[$attr["id"]] .= sprintf("\n" . '<label for="%s" class="input %s">%s</label>', $fieldname, $attr["required"] ? ' required' : '', $attr["name"]);
                    $output[$attr["id"]] .= sprintf('<input type="text" name="%s" class="input%s" value="%s" />', $fieldname, $attr["required"] ? ' required' : '', isset($_POST[$fieldname]) ? htmlspecialchars(stripslashes($_POST[$fieldname])) : (isset($data[$attr["id"]]) ? $data[$attr["id"]] : $attr["default_value"]));
                    break;
                case "textarea":
                    $output[$attr["id"]] .= sprintf("\n" . '<label for="%s" class="input %s">%s</label>', $fieldname, $attr["required"] ? ' required' : '', $attr["name"]);
                    $output[$attr["id"]] .= sprintf('<textarea name="%s" rows="%d" cols="%d" class="input%s" wrap="virtual">%s</textarea>', $fieldname, $textarearows, $textareacols, $attr["required"] ? ' required' : '', isset($_POST[$fieldname]) ? htmlspecialchars(stripslashes($_POST[$fieldname])) : (isset($data[$attr["id"]]) ? htmlspecialchars(stripslashes($data[$attr["id"]])) : $attr["default_value"]));
                    break;
                case "hidden":
                    $output[$attr["id"]] .= sprintf('<input type="hidden" name="%s" value="%s" />', $fieldname, $data[$attr["id"]] ? $data[$attr["id"]] : $attr["default_value"]);
                    break;
                case "date":
                    require_once dirname(__FILE__) . "/date.php";
                    $date = new Date();
                    $postval = $date->getDate($fieldname);
                    if ($data[$attr["id"]]) {
                        $val = $data[$attr["id"]];
                    } else {
                        $val = $postval;
                    }
                    $output[$attr["id"]] = sprintf("\n" . '<fieldset class="date%s"><label for="%s">%s</label>', $attr["required"] ? ' required' : '', $fieldname, $attr["name"]);
                    $output[$attr["id"]] .= sprintf('%s', $date->showInput($fieldname, "", $val));
                    $output[$attr["id"]] .= '</fieldset>';
                    break;
                default:
                    print "<!-- error: huh, invalid attribute type -->";
            }
            $output[$attr["id"]] .= "\n";
        }
    }
    # make sure the order is correct
    foreach ($attributes as $attribute => $listorder) {
        if (isset($output[$attribute])) {
            $html .= $output[$attribute];
        }
    }
    $html .= '</fieldset>' . "\n";
    ## class=attributes
    #  print htmlspecialchars( '<fieldset class="phplist">'.$html.'</fieldset>');exit;
    return $html;
}
Пример #10
0
 /**
  * This method modifies an existing campaign. Undefined fields do not change
  * and defined fields with a NULL value also remain unchanged.
  *
  * @access public
  *
  * @param OA_Dll_CampaignInfo &$oCampaign <br />
  *          <b>For adding</b><br />
  *          <b>Required properties:</b> advertiserId<br />
  *          <b>Optional properties:</b> campaignName, startDate, endDate, impressions, clicks, priority, weight<br />
  *
  *          <b>For modify</b><br />
  *          <b>Required properties:</b> campaignId<br />
  *          <b>Optional properties:</b> advertiserId, campaignName, startDate, endDate, impressions, clicks, priority, weight, viewWindow, clickWindow<br />
  *
  * @return boolean  True if the operation was successful
  *
  */
 function modify(&$oCampaign)
 {
     if (!isset($oCampaign->campaignId)) {
         // Add
         $oCampaign->setDefaultForAdd();
         if (!$this->checkPermissions(array(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER), 'clients', $oCampaign->advertiserId)) {
             return false;
         }
     } else {
         // Edit
         if (!$this->checkPermissions(array(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER), 'campaigns', $oCampaign->campaignId)) {
             return false;
         }
     }
     $oStartDate = $oCampaign->startDate;
     $oEndDate = $oCampaign->endDate;
     $campaignData = (array) $oCampaign;
     $campaignData['campaignid'] = $oCampaign->campaignId;
     $campaignData['campaignname'] = $oCampaign->campaignName;
     $campaignData['clientid'] = $oCampaign->advertiserId;
     $oNow = new Date();
     if (is_object($oStartDate)) {
         $oDate = new Date($oStartDate);
         $oDate->setTZ($oNow->tz);
         $oDate->setHour(0);
         $oDate->setMinute(0);
         $oDate->setSecond(0);
         $oDate->toUTC();
         $campaignData['activate_time'] = $oDate->getDate(DATE_FORMAT_ISO);
     }
     if (is_object($oEndDate)) {
         $oDate = new Date($oEndDate);
         $oDate->setTZ($oNow->tz);
         $oDate->setHour(23);
         $oDate->setMinute(59);
         $oDate->setSecond(59);
         $oDate->toUTC();
         $campaignData['expire_time'] = $oDate->getDate(DATE_FORMAT_ISO);
     }
     $campaignData['views'] = $oCampaign->impressions;
     $campaignData['target_impression'] = $oCampaign->targetImpressions;
     $campaignData['target_click'] = $oCampaign->targetClicks;
     $campaignData['target_conversion'] = $oCampaign->targetConversions;
     $campaignData['revenue_type'] = $oCampaign->revenueType;
     $campaignData['capping'] = $oCampaign->capping > 0 ? $oCampaign->capping : 0;
     $campaignData['session_capping'] = $oCampaign->sessionCapping > 0 ? $oCampaign->sessionCapping : 0;
     $campaignData['block'] = $oCampaign->block > 0 ? $oCampaign->block : 0;
     $campaignData['viewwindow'] = $oCampaign->viewWindow;
     $campaignData['clickwindow'] = $oCampaign->clickWindow;
     if ($this->_validate($oCampaign)) {
         $doCampaign = OA_Dal::factoryDO('campaigns');
         if (!isset($oCampaign->campaignId)) {
             $doCampaign->setFrom($campaignData);
             $oCampaign->campaignId = $doCampaign->insert();
         } else {
             $doCampaign->get($campaignData['campaignid']);
             $doCampaign->setFrom($campaignData);
             $doCampaign->update();
         }
         return true;
     } else {
         return false;
     }
 }
Пример #11
0
 /**
  * A method to convert a Date into an array containing the start
  * and end Dates of the operation interval that the date is in.
  *
  * @static
  * @param Date $oDate The date to convert.
  * @param integer $operation_interval Optional length of the operation interval
  *                                    in minutes. If not given, will use the
  *                                    currently defined operation interval.
  * @param boolean $cacheResult  If true the data should be cached
  * @return array An array of the start and end Dates of the operation interval.
  */
 function convertDateToOperationIntervalStartAndEndDates($oDate, $operationInterval = 0, $cacheResult = true)
 {
     // Convert to UTC
     $oDateCopy = new Date($oDate);
     $oDateCopy->toUTC();
     // Check cache
     static $aCache;
     if ($cacheResult && isset($aCache[$oDateCopy->getDate()][$operationInterval])) {
         $cachedDates = $aCache[$oDateCopy->getDate()][$operationInterval];
         $oStart = new Date($cachedDates['start']);
         $oStart->setTZbyID('UTC');
         $oEnd = new Date($cachedDates['end']);
         $oEnd->setTZbyID('UTC');
         return array('start' => $oStart, 'end' => $oEnd);
     }
     if ($operationInterval < 1) {
         $operationInterval = OX_OperationInterval::getOperationInterval();
     }
     // Get the date representing the start of the week
     $oStartOfWeek = new Date(Date_Calc::beginOfWeek($oDateCopy->getDay(), $oDateCopy->getMonth(), $oDateCopy->getYear(), '%Y-%m-%d 00:00:00'));
     $oStartOfWeek->setTZbyID('UTC');
     // Get the operation interval ID of the date
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDateCopy, $operationInterval);
     // The start of the operation interval is the start of the week plus the
     // operation interval ID multiplied by the operation interval
     $oStart = new Date();
     $oStart->copy($oStartOfWeek);
     $oStart->addSeconds($operationIntervalID * $operationInterval * 60);
     // The end of the operation interval is the start of the week plus the
     // operation interval ID + 1 multiplied by the operation interval
     $oEnd = new Date();
     $oEnd->copy($oStart);
     $oEnd->addSeconds($operationInterval * 60 - 1);
     // Cache result - cache as string to save memory
     if ($cacheResult) {
         $aCache[$oDate->getDate()][$operationInterval] = array('start' => $oStart->getDate(), 'end' => $oEnd->getDate());
     }
     // Return the result
     return array('start' => $oStart, 'end' => $oEnd);
 }
 function test_getAuditLogForAuditWidget()
 {
     $dllAuditPartialMock = new PartialMockOA_Dll_Audit($this);
     $oSpanDay = new Date_Span('1-0-0-0');
     $oDate = new Date(OA::getNow());
     $oDate->toUTC();
     $oDate->subtractSpan(new Date_Span('8-0-0-0'));
     // add 1 hour to make sure that the test passes even if it takes some time
     $oDate->addSpan(new Date_Span('0-1-0-0'));
     // record 1 - more than 7 days old so should not be returned
     $oAudit = OA_Dal::factoryDO('audit');
     $oAudit->account_id = 1;
     $oAudit->context = 'campaigns';
     $oAudit->contextid = 1;
     $oAudit->parentid = null;
     $oAudit->username = '******';
     $oAudit->actionid = OA_AUDIT_ACTION_UPDATE;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 1';
     $aDetails['status'] = OA_ENTITY_STATUS_EXPIRED;
     $oAudit->details = serialize($aDetails);
     $oAudit->insert();
     // record 2
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 3
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_PAUSED;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 4
     $oDate->addSpan($oSpanDay);
     $oAudit->contextid = 2;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 2';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 5
     $oDate->addSpan($oSpanDay);
     $oAudit->updated = $oDate->getDate();
     $oAudit->username = '******';
     $aDetails['status'] = OA_ENTITY_STATUS_EXPIRED;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 6
     $oDate->addSpan($oSpanDay);
     $oAudit->account_id = 2;
     $oAudit->contextid = 3;
     $oAudit->username = '******';
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 3';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $idAudit = $oAudit->insert();
     $aExpect[$idAudit] = $oAudit->toArray();
     $aExpect[$idAudit]['details'] = $aDetails;
     // record 7 - is a maintenance audit rec so should not be returned
     $oDate->addSpan($oSpanDay);
     $oAudit->username = '******';
     $oAudit->contextid = 1;
     $oAudit->updated = $oDate->getDate();
     $aDetails['campaignname'] = 'Campaign 1';
     $aDetails['status'] = OA_ENTITY_STATUS_RUNNING;
     $oAudit->details = serialize($aDetails);
     $oAudit->insert();
     $aParams = array();
     $aResults = $dllAuditPartialMock->getAuditLogForAuditWidget($aParams);
     $this->assertIsA($aResults, 'array');
     $this->assertEqual(count($aResults), 5);
     foreach ($aResults as $i => $aResRow) {
         $aExpRow = $aExpect[$aResRow['auditid']];
         $this->assertEqual($aResRow['auditid'], $aExpRow['auditid']);
         $this->assertEqual($aResRow['actionid'], $aExpRow['actionid']);
         $this->assertEqual($aResRow['context'], $dllAuditPartialMock->getContextDescription($aExpRow['context']));
         $this->assertEqual($aResRow['contextid'], $aExpRow['contextid']);
         $this->assertEqual($aResRow['parentid'], $aExpRow['parentid']);
         $this->assertEqual($aResRow['username'], $aExpRow['username']);
         $this->assertEqual($aResRow['details']['campaignname'], $aExpRow['details']['campaignname']);
         $this->assertEqual($aResRow['details']['status'], $aExpRow['details']['status']);
         $oDate = new Date($aResRow['updated']);
         $oDate->toUTC();
         $this->assertEqual($oDate->getDate(), $aExpRow['updated']);
     }
     // Check that the account_id filter is working
     $aParams = array('account_id' => 2);
     $aResults = $dllAuditPartialMock->getAuditLogForAuditWidget($aParams);
     $this->assertIsA($aResults, 'array');
     $this->assertEqual(count($aResults), 1);
 }
Пример #13
0
 /**
  * A method to test the getDaysLeftString() method.
  */
 function testGetDaysLeftString()
 {
     /*
         	Possible cases for testing:
         	Case 1 -> Campaign without expiration date and without a estimated
         	          expiration date yet
         	Case 2 -> Campaign without expiration date and with a estimated
         	          expiration date
         	Case 3 -> Campaign with expiration date and without a estimated
         	          expiration date
         	Case 4 -> Campaign with expiration date reached
         	Case 5 -> Campaign with expiration date and with estimated
         	          expiration date minor than the expiration date
         	Case 6 -> Campaign with expiration date and with estimated
         	          expiration date equals to the expiration date
         	Case 7 -> Campaign with expiration date and with estimated
         	          expiration date higher than the expiration date
     */
     $GLOBALS['strExpirationDate'] = "Expiration date";
     $GLOBALS['strNoExpiration'] = "No expiration date set";
     $GLOBALS['strEstimated'] = "Estimated expiration date";
     $GLOBALS['strNoExpirationEstimation'] = "No expiration estimated yet";
     $GLOBALS['strCampaignStop'] = "Campaign stop";
     $GLOBALS['strDaysAgo'] = "days ago";
     $GLOBALS['strDaysLeft'] = "Days left";
     $GLOBALS['date_format'] = '%d.%m.%Y';
     // Case 1
     // Test an unlimited campaign without expiration date and without a
     // estimated expiration date yet
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.1
     // Test a campaign (an impression limited campaign) without
     // expiration date and with a estimated expiration date
     $totalImpressions = 1000;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert impression delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days
     // to deliver remaining 950
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.2
     // Test a campaign (click limited campaign) without
     // expiration date and with a estimated expiration date
     $totalClicks = 500;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = 0;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert click delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     $daysLeft = 99;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.3
     // Test a campaign (conversion limited campaign)
     // without expiration date and with a estimated expiration date
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver remaining 9
     $daysLeft = 9;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 2.4
     // Test a triple limited campaign without expiration date
     // and with a estimated expiration date
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 3
     // Test a campaign with expiration date and without a estimated expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expires 10 days in the future
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 4
     // Campaign with expiration date reached
     // Prepare a campaign with expiration date reached
     $daysExpired = 5;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->subtractSeconds($daysExpired * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test an unlimited campaign which expired 5 days ago
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 0;
     $doCampaigns->clicks = 0;
     $doCampaigns->conversions = 0;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $GLOBALS['strCampaignStop'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $daysExpired . " " . $GLOBALS['strDaysAgo'] . ")");
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 5
     // Campaign with expiration date and with estimated
     // expiration date minor than the expiration date
     // Prepare a date 25 days in the future
     $daysLeft = 25;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver
     // remaining 9
     // The estimated expiration will be calucalated based onimpression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 6
     // Campaign with expiration date and with estimated
     // expiration date equals to the expiration date
     // Prepare a date 19 days in the future
     $daysLeft = 19;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver
     // remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order).
     $daysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
     // Case 7
     // Campaign with expiration date and with estimated
     // expiration date higher than the expiration date
     // Prepare a date 10 days in the future
     $daysLeft = 10;
     $oDate = new Date();
     $oDate->setHour(23);
     $oDate->setMinute(59);
     $oDate->setSecond(59);
     $oDate->addSeconds($daysLeft * SECONDS_PER_DAY);
     $oDate->toUTC();
     // Test a triple limited campaign with an expiration date 10 days
     // in the future
     $totalImpressions = 1000;
     $totalClicks = 500;
     $totalConversions = 10;
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = $totalImpressions;
     $doCampaigns->clicks = $totalClicks;
     $doCampaigns->conversions = $totalConversions;
     $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO);
     $aData = array('reportlastdate' => array('2007-04-03 18:39:45'));
     $dg = new DataGenerator();
     $dg->setData('clients', $aData);
     $aCampaignIds = $dg->generate($doCampaigns, 1, true);
     $campaignId = $aCampaignIds[0];
     $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")";
     // Link a banner to this campaign
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->acls_updated = '2007-04-03 18:39:45';
     $bannerId = DataGenerator::generateOne($doBanners);
     // Insert conversion delivery data occurring today
     $oDate = new Date();
     $impressions = 50;
     $clicks = 5;
     $conversions = 1;
     $doDSAH = OA_Dal::factoryDO('data_intermediate_ad');
     $doDSAH->day = $oDate->format('%Y-%m-%d');
     $doDSAH->hour = 10;
     $doDSAH->ad_id = $bannerId;
     $doDSAH->impressions = $impressions;
     $doDSAH->clicks = $clicks;
     $doDSAH->conversions = $conversions;
     $dsahId = DataGenerator::generateOne($doDSAH);
     // Expiration date is in 10 days
     // Delivered 50 impressions in 1 day. So, expect to take 19 days to
     // deliver remaining 950
     // Delivered 5 clicks in 1 day. So, expect to take 99 days to
     // deliver remaining 495
     // Delivered 1 conversion in 1 day. So, expect to take 9 days to
     // deliver remaining 9
     // The estimated expiration will be calucalated based on impression targets
     // or based on click targets or based on conversion targets (following this order)
     $estimatedDaysLeft = 19;
     $oExpirationDate = new Date();
     $oExpirationDate->copy($oDate);
     $oExpirationDate->addSeconds($estimatedDaysLeft * SECONDS_PER_DAY);
     // The extimated expiration is higher than the expiration set by the user
     // so the value of the extimated expiration will be null because is not a
     // relevant estimation because the campaign will expire before this estimation.
     $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $campaignExpiration);
     $actual = $this->oDalCampaigns->getDaysLeftString($campaignId);
     $this->assertEqual($actual, $expected);
 }
Пример #14
0
 function arrayToDate($date_input, $timestamp = false)
 {
     // possible year values
     if (isset($date_input['Y'])) {
         $year = $date_input['Y'];
     } else {
         if (isset($date_input['y'])) {
             $year = $date_input['y'];
         }
     }
     // possible month values
     if (isset($date_input['F'])) {
         $month = $date_input['F'];
     } else {
         if (isset($date_input['m'])) {
             $month = $date_input['m'];
         } else {
             if (isset($date_input['M'])) {
                 $month = $date_input['M'];
             } else {
                 if (isset($date_input['n'])) {
                     $month = $date_input['n'];
                 }
             }
         }
     }
     // possible day values
     if (isset($date_input['d'])) {
         $day = $date_input['d'];
     } else {
         if (isset($date_input['j'])) {
             $day = $date_input['j'];
         }
     }
     // possible hour values
     if (isset($date_input['g'])) {
         $hour = $date_input['g'];
     } else {
         if (isset($date_input['h'])) {
             $hour = $date_input['h'];
         } else {
             if (isset($date_input['G'])) {
                 $hour = $date_input['G'];
             } else {
                 if (isset($date_input['H'])) {
                     $hour = $date_input['H'];
                 }
             }
         }
     }
     // possible am/pm values
     if (isset($date_input['a'])) {
         $ampm = $date_input['a'];
     } else {
         if (isset($date_input['A'])) {
             $ampm = $date_input['A'];
         }
     }
     // instantiate date object
     $datestr = '';
     if (isset($year) || isset($month) || isset($day)) {
         if (isset($year) && !empty($year)) {
             if (strlen($year) < 2) {
                 $year = '0' . $year;
             }
             if (strlen($year) < 4) {
                 $year = substr($year, 0, 2) . $year;
             }
         } else {
             $year = '0000';
         }
         if ($year != '0000' && isset($month) && !empty($month)) {
             if (strlen($month) < 2) {
                 $month = '0' . $month;
             }
         } else {
             $month = '00';
         }
         if ($year != '0000' && $month != '00' && isset($day) && !empty($day)) {
             if (strlen($day) < 2) {
                 $day = '0' . $day;
             }
         } else {
             $day = '00';
         }
         $datestr .= "{$year}-{$month}-{$day}";
     }
     if (isset($hour) || isset($date_input['i']) || isset($date_input['s'])) {
         // set the hour
         if (isset($hour) && !empty($hour)) {
             if (strlen($hour) < 2) {
                 $hour = '0' . $hour;
             }
         } else {
             $hour = '00';
         }
         if (isset($ampm)) {
             if (strtolower($ampm) == 'pm' && strlen($hour) == 1) {
                 $hour += 12;
             }
         }
         // set the minutes
         if (isset($date_input['i']) && !empty($date_input['i'])) {
             if (strlen($date_input['i']) < 2) {
                 $date_input['i'] = '0' . $date_input['i'];
             }
         } else {
             $date_input['i'] = '00';
         }
         $datestr .= ($datestr != '' ? ' ' : '') . "{$hour}:{$date_input['i']}";
         // set the seconds
         if (isset($date_input['s']) && !empty($date_input['s'])) {
             $datestr .= ':' . (strlen($date_input['s']) < 2 ? '0' : '') . $date_input['s'];
         } else {
             $datestr .= ':00';
         }
     }
     // feed it into the date object
     $dateobj = new Date($datestr);
     // set the time zone
     $dateobj->setTZ(NDate::getClientTZ());
     // pull the string back out
     $datestr = $dateobj->getDate();
     unset($dateobj);
     return $datestr;
 }
Пример #15
0
function ListAttributes($attributes, $attributedata, $htmlchoice = 0, $userid = 0, $emaildoubleentry = 'no')
{
    global $strPreferHTMLEmail, $strPreferTextEmail, $strEmail, $tables, $table_prefix, $strPreferredFormat, $strText, $strHTML;
    /*  if (!sizeof($attributes)) {
        return "No attributes have been defined for this page";
       }
    */
    if ($userid) {
        $data = array();
        $current = Sql_Fetch_array_Query("select * from {$GLOBALS["tables"]["user"]} where id = {$userid}");
        $datareq = Sql_Query("select * from {$GLOBALS["tables"]["user_attribute"]} where userid = {$userid}");
        while ($row = Sql_Fetch_Array($datareq)) {
            $data[$row["attributeid"]] = $row["value"];
        }
        $email = $current["email"];
        $htmlemail = $current["htmlemail"];
        # override with posted info
        foreach ($current as $key => $val) {
            if ($_POST[$key] && $key != "password") {
                $current[$key] = $val;
            }
        }
    } else {
        if (isset($_REQUEST['email'])) {
            $email = stripslashes($_REQUEST["email"]);
        } else {
            $email = '';
        }
        if (isset($_POST['htmlemail'])) {
            $htmlemail = $_POST["htmlemail"];
        }
        $data = array();
        $current = array();
    }
    $textlinewidth = sprintf('%d', getConfig("textline_width"));
    if (!$textlinewidth) {
        $textlinewidth = 40;
    }
    list($textarearows, $textareacols) = explode(",", getConfig("textarea_dimensions"));
    if (!$textarearows) {
        $textarearows = 10;
    }
    if (!$textareacols) {
        $textareacols = 40;
    }
    $html = '';
    if (!isset($_GET['page']) || isset($_GET['page']) && $_GET["page"] != "import1") {
        $html = sprintf('
  <tr><td><div class="required">%s</div></td>
  <td class="attributeinput"><input type=text name=email value="%s" size="%d">
  <script language="Javascript" type="text/javascript">addFieldToCheck("email","%s");</script></td></tr>', $GLOBALS["strEmail"], htmlspecialchars($email), $textlinewidth, $GLOBALS["strEmail"]);
    }
    // BPM 12 May 2004 - Begin
    if ($emaildoubleentry == 'yes') {
        if (!isset($_REQUEST['emailconfirm'])) {
            $_REQUEST['emailconfirm'] = '';
        }
        $html .= sprintf('
  <tr><td><div class="required">%s</div></td>
  <td class="attributeinput"><input type=text name=emailconfirm value="%s" size="%d">
  <script language="Javascript" type="text/javascript">addFieldToCheck("emailconfirm","%s");</script></td></tr>', $GLOBALS["strConfirmEmail"], htmlspecialchars(stripslashes($_REQUEST["emailconfirm"])), $textlinewidth, $GLOBALS["strConfirmEmail"]);
    }
    // BPM 12 May 2004 - Finish
    if (isset($_GET['page']) && $_GET["page"] != "import1" || !isset($_GET['page'])) {
        if (ASKFORPASSWORD) {
            # we only require a password if there isnt one, so they can set it
            # otherwise they can keep the existing, if they do not enter anything
            if (!isset($current['password']) || !$current["password"]) {
                $pwdclass = "required";
                $js = sprintf('<script language="Javascript" type="text/javascript">addFieldToCheck("password","%s");</script>', $GLOBALS["strPassword"]);
                $js2 = sprintf('<script language="Javascript" type="text/javascript">addFieldToCheck("password_check","%s");</script>', $GLOBALS["strPassword2"]);
                $html .= '<input type=hidden name="passwordreq" value="1">';
            } else {
                $pwdclass = 'attributename';
                $html .= '<input type=hidden name="passwordreq" value="0">';
            }
            $html .= sprintf('
  <tr><td><div class="%s">%s</div></td>
  <td class="attributeinput"><input type=password name=password value="" size="%d">%s</td></tr>', $pwdclass, $GLOBALS["strPassword"], $textlinewidth, $js);
            $html .= sprintf('
  <tr><td><div class="%s">%s</div></td>
  <td class="attributeinput"><input type=password name="password_check" value="" size="%d">%s</td></tr>', $pwdclass, $GLOBALS["strPassword2"], $textlinewidth, $js2);
        }
    }
    ## Write attribute fields
    switch ($htmlchoice) {
        case "textonly":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<input type=hidden name="htmlemail" value="0">');
            break;
        case "htmlonly":
            if (!isset($htmlemail)) {
                $htmlemail = 1;
            }
            $html .= sprintf('<input type=hidden name="htmlemail" value="1">');
            break;
        case "checkfortext":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<tr><td colspan=2>
      <span class="attributeinput">
      <input type=checkbox name="textemail" value="1" %s></span>
      <span class="attributename">%s</span>
      </td></tr>', !$htmlemail, $strPreferTextEmail);
            break;
        case "radiotext":
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<tr><td colspan=2>
        <span class="attributename">%s<br/>
        <span class="attributeinput"><input type=radio name="htmlemail" value="0" %s /></span>
        <span class="attributename">%s</span>
        <span class="attributeinput"><input type=radio name="htmlemail" value="1" %s /></span>
        <span class="attributename">%s</span></td></tr>', $strPreferredFormat, !$htmlemail ? "checked" : "", $strText, $htmlemail ? "checked" : "", $strHTML);
            break;
        case "radiohtml":
            if (!isset($htmlemail)) {
                $htmlemail = 1;
            }
            $html .= sprintf('<tr><td colspan=2>
        <span class="attributename">%s</span><br/>
        <span class="attributeinput"><input type=radio name="htmlemail" value="0" %s /></span>
        <span class="attributename">%s</span>
        <span class="attributeinput"><input type=radio name="htmlemail" value="1" %s /></span>
        <span class="attributename">%s</span></td></tr>', $strPreferredFormat, !$htmlemail ? "checked" : "", $strText, $htmlemail ? "checked" : "", $strHTML);
            break;
        case "checkforhtml":
        default:
            if (!isset($htmlemail)) {
                $htmlemail = 0;
            }
            $html .= sprintf('<tr><td colspan=2>
        <span class="attributeinput"><input type=checkbox name="htmlemail" value="1" %s /></span>
        <span class="attributename">%s</span></td></tr>', $htmlemail ? "checked" : "", $strPreferHTMLEmail);
            break;
    }
    $html .= "\n";
    $attids = join(',', array_keys($attributes));
    $output = array();
    if ($attids) {
        $res = Sql_Query("select * from {$GLOBALS["tables"]["attribute"]} where id in ({$attids})");
        while ($attr = Sql_Fetch_Array($res)) {
            $output[$attr["id"]] = '';
            if (!isset($data[$attr['id']])) {
                $data[$attr['id']] = '';
            }
            $attr["required"] = $attributedata[$attr["id"]]["required"];
            $attr["default_value"] = $attributedata[$attr["id"]]["default_value"];
            $fieldname = "attribute" . $attr["id"];
            #  print "<tr><td>".$attr["id"]."</td></tr>";
            if ($userid && !isset($_POST[$fieldname])) {
                # post values take precedence
                $val = Sql_Fetch_Row_Query(sprintf('select value from %s where
          attributeid = %d and userid = %d', $GLOBALS["tables"]["user_attribute"], $attr["id"], $userid));
                $_POST[$postvalue] = $val[0];
            } elseif (!isset($_POST[$fieldname])) {
                $_POST[$fieldname] = 0;
            }
            switch ($attr["type"]) {
                case "checkbox":
                    $output[$attr["id"]] = '<tr><td colspan=2>';
                    # what they post takes precedence over the database information
                    if ($_POST[$fieldname]) {
                        $checked = $_POST[$fieldname] ? "checked" : "";
                    } else {
                        $checked = $data[$attr["id"]] ? "checked" : "";
                    }
                    $output[$attr["id"]] .= sprintf("\n" . '<input type="checkbox" name="%s" value="on" %s class="attributeinput">', $fieldname, $checked);
                    $output[$attr["id"]] .= sprintf("\n" . '<span class="%s">%s</span>', $attr["required"] ? 'required' : 'attributename', stripslashes($attr["name"]));
                    if ($attr["required"]) {
                        $output[$attr["id"]] .= sprintf('<script language="Javascript" type="text/javascript">addFieldToCheck("%s","%s");</script>', $fieldname, $attr["name"]);
                    }
                    break;
                case "radio":
                    $output[$attr["id"]] .= sprintf("\n" . '<tr><td colspan=2><div class="%s">%s</div>', $attr["required"] ? 'required' : 'attributename', stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    while ($value = Sql_Fetch_array($values_request)) {
                        if (!empty($_POST[$fieldname])) {
                            $checked = $_POST[$fieldname] == $value["id"] ? "checked" : "";
                        } else {
                            if ($data[$attr["id"]]) {
                                $checked = $data[$attr["id"]] == $value["id"] ? "checked" : "";
                            } else {
                                $checked = $attr["default_value"] == $value["name"] ? "checked" : "";
                            }
                        }
                        $output[$attr["id"]] .= sprintf('&nbsp;%s&nbsp;<input type=radio  class="attributeinput" name="%s" value="%s" %s>', $value["name"], $fieldname, $value["id"], $checked);
                    }
                    if ($attr["required"]) {
                        $output[$attr["id"]] .= sprintf('<script language="Javascript" type="text/javascript">addGroupToCheck("%s","%s");</script>', $fieldname, $attr["name"]);
                    }
                    break;
                case "select":
                    $output[$attr["id"]] .= sprintf("\n" . '<tr><td><div class="%s">%s</div>', $attr["required"] ? 'required' : 'attributename', stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    $output[$attr["id"]] .= sprintf('</td><td class="attributeinput"><!--%d--><select name="%s" class="attributeinput">', $data[$attr["id"]], $fieldname);
                    while ($value = Sql_Fetch_array($values_request)) {
                        if (!empty($_POST[$fieldname])) {
                            $selected = $_POST[$fieldname] == $value["id"] ? "selected" : "";
                        } else {
                            if ($data[$attr["id"]]) {
                                $selected = $data[$attr["id"]] == $value["id"] ? "selected" : "";
                            } else {
                                $selected = $attr["default_value"] == $value["name"] ? "selected" : "";
                            }
                        }
                        if (preg_match('/^' . preg_quote(EMPTY_VALUE_PREFIX) . '/i', $value['name'])) {
                            $value['id'] = '';
                        }
                        $output[$attr["id"]] .= sprintf('<option value="%s" %s>%s', $value["id"], $selected, stripslashes($value["name"]));
                    }
                    $output[$attr["id"]] .= "</select>";
                    break;
                case "checkboxgroup":
                    $output[$attr["id"]] .= sprintf("\n" . '<tr><td colspan=2><div class="%s">%s</div>', $attr["required"] ? 'required' : 'attributename', stripslashes($attr["name"]));
                    $values_request = Sql_Query("select * from {$table_prefix}" . "listattr_" . $attr["tablename"] . " order by listorder,name");
                    $output[$attr["id"]] .= sprintf('</td></tr>');
                    while ($value = Sql_Fetch_array($values_request)) {
                        if (is_array($_POST[$fieldname])) {
                            $selected = in_array($value["id"], $_POST[$fieldname]) ? "checked" : "";
                        } else {
                            if ($data[$attr["id"]]) {
                                $selection = explode(",", $data[$attr["id"]]);
                                $selected = in_array($value["id"], $selection) ? "checked" : "";
                            } else {
                                $selection = array();
                                $selected = "";
                            }
                        }
                        $output[$attr["id"]] .= sprintf('<tr><td colspan=2 class="attributeinput"><input type=checkbox name="%s[]"  class="attributeinput" value="%s" %s> %s</td></tr>', $fieldname, $value["id"], $selected, stripslashes($value["name"]));
                    }
                    break;
                case "textline":
                    $output[$attr["id"]] .= sprintf("\n" . '<tr><td><div class="%s">%s</div>', $attr["required"] ? 'required' : 'attributename', $attr["name"]);
                    $output[$attr["id"]] .= sprintf('</td><td class="attributeinput">
            <input type=text name="%s"  class="attributeinput" size="%d" value="%s">', $fieldname, $textlinewidth, $_POST[$fieldname] ? htmlspecialchars(stripslashes($_POST[$fieldname])) : ($data[$attr["id"]] ? $data[$attr["id"]] : $attr["default_value"]));
                    if ($attr["required"]) {
                        $output[$attr["id"]] .= sprintf('<script language="Javascript" type="text/javascript">addFieldToCheck("%s","%s");</script>', $fieldname, $attr["name"]);
                    }
                    break;
                case "textarea":
                    $output[$attr["id"]] .= sprintf("\n" . '<tr><td colspan=2>
            <div class="%s">%s</div></td></tr>', $attr["required"] ? 'required' : 'attributename', $attr["name"]);
                    $output[$attr["id"]] .= sprintf('<tr><td class="attributeinput" colspan=2>
            <textarea name="%s" rows="%d"  class="attributeinput" cols="%d" wrap="virtual">%s</textarea>', $fieldname, $textarearows, $textareacols, $_POST[$fieldname] ? htmlspecialchars(stripslashes($_POST[$fieldname])) : ($data[$attr["id"]] ? htmlspecialchars(stripslashes($data[$attr["id"]])) : $attr["default_value"]));
                    if ($attr["required"]) {
                        $output[$attr["id"]] .= sprintf('<script language="Javascript" type="text/javascript">addFieldToCheck("%s","%s");</script>', $fieldname, $attr["name"]);
                    }
                    break;
                case "hidden":
                    $output[$attr["id"]] .= sprintf('<input type=hidden name="%s" size=40 value="%s">', $fieldname, $data[$attr["id"]] ? $data[$attr["id"]] : $attr["default_value"]);
                    break;
                case "date":
                    require_once dirname(__FILE__) . "/date.php";
                    $date = new Date();
                    $postval = $date->getDate($fieldname);
                    if ($data[$attr["id"]]) {
                        $val = $data[$attr["id"]];
                    } else {
                        $val = $postval;
                    }
                    $output[$attr["id"]] = sprintf("\n" . '<tr><td><div class="%s">%s</div>', $attr["required"] ? 'required' : 'attributename', $attr["name"]);
                    $output[$attr["id"]] .= sprintf('</td><td class="attributeinput">
            %s</td></tr>', $date->showInput($fieldname, "", $val));
                    break;
                default:
                    print "<!-- error: huh, invalid attribute type -->";
            }
            $output[$attr["id"]] .= "</td></tr>\n";
        }
    }
    # make sure the order is correct
    foreach ($attributes as $attribute => $listorder) {
        if (isset($output[$attribute])) {
            $html .= $output[$attribute];
        }
    }
    return $html;
}
/**
 * Processes submit values of campaign form
 *
 * @param OA_Admin_UI_Component_Form $form form to process
 * @return An array of Pear::Error objects if any
 */
function processCampaignForm($form, &$oComponent = null)
{
    $aFields = $form->exportValues();
    if (!empty($aFields['start'])) {
        $oDate = new Date(date('Y-m-d 00:00:00', strtotime($aFields['start'])));
        $oDate->toUTC();
        $activate = $oDate->getDate();
    } else {
        $oDate = new Date(date('Y-m-d 00:00:00'));
        $oDate->toUTC();
        $activate = $oDate->getDate();
    }
    if (!empty($aFields['end'])) {
        $oDate = new Date(date('Y-m-d 23:59:59', strtotime($aFields['end'])));
        $oDate->toUTC();
        $expire = $oDate->getDate();
    } else {
        $expire = null;
    }
    if (empty($aFields['campaignid'])) {
        // The form is submitting a new campaign, so, the ID is not set;
        // set the ID to the string "null" so that the table auto_increment
        // or sequence will be used when the campaign is created
        $aFields['campaignid'] = "null";
    } else {
        // The form is submitting a campaign modification; need to test
        // if any of the banners in the campaign are linked to an email zone,
        // and if so, if the link(s) would still be valid if the change(s)
        // to the campaign were made...
        $dalCampaigns = OA_Dal::factoryDAL('campaigns');
        $aCurrentLinkedEmalZoneIds = $dalCampaigns->getLinkedEmailZoneIds($aFields['campaignid']);
        if (PEAR::isError($aCurrentLinkedEmalZoneIds)) {
            OX::disableErrorHandling();
            $errors[] = PEAR::raiseError($GLOBALS['strErrorDBPlain']);
            OX::enableErrorHandling();
        }
        $errors = array();
        foreach ($aCurrentLinkedEmalZoneIds as $zoneId) {
            $thisLink = Admin_DA::_checkEmailZoneAdAssoc($zoneId, $aFields['campaignid'], $activate, $expire);
            if (PEAR::isError($thisLink)) {
                $errors[] = $thisLink;
                break;
            }
        }
    }
    //correct and check revenue and ecpm
    correctAdnCheckNumericFormField($aFields, $errors, 'revenue', $GLOBALS['strErrorEditingCampaignRevenue']);
    correctAdnCheckNumericFormField($aFields, $errors, 'ecpm', $GLOBALS['strErrorEditingCampaignECPM']);
    if (empty($errors)) {
        //check booked limits values
        // If this is a remnant, ecpm or exclusive campaign with an expiry date, set the target's to unlimited
        if (!empty($expire) && ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_REMNANT || $aFields['campaign_type'] == OX_CAMPAIGN_TYPE_ECPM || $aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_EXCLUSIVE)) {
            $aFields['impressions'] = $aFields['clicks'] = $aFields['conversions'] = -1;
        } else {
            if (!empty($aFields['impr_unlimited']) && $aFields['impr_unlimited'] == 't') {
                $aFields['impressions'] = -1;
            } else {
                if (empty($aFields['impressions']) || $aFields['impressions'] == '-') {
                    $aFields['impressions'] = 0;
                }
            }
            if (!empty($aFields['click_unlimited']) && $aFields['click_unlimited'] == 't') {
                $aFields['clicks'] = -1;
            } else {
                if (empty($aFields['clicks']) || $aFields['clicks'] == '-') {
                    $aFields['clicks'] = 0;
                }
            }
            if (!empty($aFields['conv_unlimited']) && $aFields['conv_unlimited'] == 't') {
                $aFields['conversions'] = -1;
            } else {
                if (empty($aFields['conversions']) || $aFields['conversions'] == '-') {
                    $aFields['conversions'] = 0;
                }
            }
        }
        //pricing model - reset fields not applicable to model to 0,
        //note that in new flow MAX_FINANCE_CPA allows all limits to be set
        if ($aFields['revenue_type'] == MAX_FINANCE_CPM) {
            $aFields['clicks'] = -1;
            $aFields['conversions'] = -1;
        } else {
            if ($aFields['revenue_type'] == MAX_FINANCE_CPC) {
                $aFields['conversions'] = -1;
            } else {
                if ($aFields['revenue_type'] == MAX_FINANCE_MT) {
                    $aFields['impressions'] = -1;
                    $aFields['clicks'] = -1;
                    $aFields['conversions'] = -1;
                }
            }
        }
        //check type and set priority
        if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_REMNANT) {
            $aFields['priority'] = 0;
            //low
        } else {
            if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_NORMAL) {
                $aFields['priority'] = isset($aFields['high_priority_value']) ? $aFields['high_priority_value'] : 5;
                //high
            } else {
                if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_CONTRACT_EXCLUSIVE) {
                    $aFields['priority'] = -1;
                    //exclusive
                } else {
                    if ($aFields['campaign_type'] == OX_CAMPAIGN_TYPE_ECPM) {
                        $aFields['priority'] = -2;
                        //ecpm
                    }
                }
            }
        }
        // Set target
        $target_impression = 0;
        $target_click = 0;
        $target_conversion = 0;
        if ($aFields['priority'] > 0) {
            // Daily targets need to be set only if the campaign doesn't have both expiration and lifetime targets
            $hasExpiration = !empty($expire);
            $hasLifetimeTargets = $aFields['impressions'] != -1 || $aFields['clicks'] != -1 || $aFields['conversions'] != -1;
            if (!($hasExpiration && $hasLifetimeTargets) && isset($aFields['target_value']) && $aFields['target_value'] != '-') {
                switch ($aFields['target_type']) {
                    case 'target_impression':
                        $target_impression = $aFields['target_value'];
                        break;
                    case 'target_click':
                        $target_click = $aFields['target_value'];
                        break;
                    case 'target_conversion':
                        $target_conversion = $aFields['target_value'];
                        break;
                }
            }
            $aFields['weight'] = 0;
        } else {
            // Set weight
            if (!isset($aFields['weight']) || $aFields['weight'] == '-' || $aFields['weight'] == '') {
                $aFields['weight'] = 0;
            }
        }
        if ($aFields['anonymous'] != 't') {
            $aFields['anonymous'] = 'f';
        }
        if ($aFields['companion'] != 1) {
            $aFields['companion'] = 0;
        }
        if ($aFields['show_capped_no_cookie'] != 1) {
            $aFields['show_capped_no_cookie'] = 0;
        }
        $new_campaign = $aFields['campaignid'] == 'null';
        if (empty($aFields['revenue']) || $aFields['revenue'] <= 0) {
            // No revenue information, set to null
            $aFields['revenue'] = OX_DATAOBJECT_NULL;
        }
        if (empty($aFields['ecpm']) || $aFields['ecpm'] <= 0) {
            // No ecpm information, set to null
            $aFields['ecpm'] = OX_DATAOBJECT_NULL;
        }
        // Get the capping variables
        $block = _initCappingVariables($aFields['time'], $aFields['capping'], $aFields['session_capping']);
        $doCampaigns = OA_Dal::factoryDO('campaigns');
        $doCampaigns->campaignname = $aFields['campaignname'];
        $doCampaigns->clientid = $aFields['clientid'];
        $doCampaigns->views = $aFields['impressions'];
        $doCampaigns->clicks = $aFields['clicks'];
        $doCampaigns->conversions = $aFields['conversions'];
        $doCampaigns->priority = $aFields['priority'];
        $doCampaigns->weight = $aFields['weight'];
        $doCampaigns->target_impression = $target_impression;
        $doCampaigns->target_click = $target_click;
        $doCampaigns->target_conversion = $target_conversion;
        $doCampaigns->min_impressions = $aFields['min_impressions'];
        $doCampaigns->ecpm = $aFields['ecpm'];
        $doCampaigns->anonymous = $aFields['anonymous'];
        $doCampaigns->companion = $aFields['companion'];
        $doCampaigns->show_capped_no_cookie = $aFields['show_capped_no_cookie'];
        $doCampaigns->comments = $aFields['comments'];
        $doCampaigns->revenue = $aFields['revenue'];
        $doCampaigns->revenue_type = $aFields['revenue_type'];
        $doCampaigns->block = $block;
        $doCampaigns->capping = $aFields['capping'];
        $doCampaigns->session_capping = $aFields['session_capping'];
        // Activation and expiration
        $doCampaigns->activate_time = isset($activate) ? $activate : OX_DATAOBJECT_NULL;
        $doCampaigns->expire_time = isset($expire) ? $expire : OX_DATAOBJECT_NULL;
        if (!empty($aFields['campaignid']) && $aFields['campaignid'] != "null") {
            $doCampaigns->campaignid = $aFields['campaignid'];
            $doCampaigns->setEcpmEnabled();
            $doCampaigns->update();
        } else {
            $doCampaigns->setEcpmEnabled();
            $aFields['campaignid'] = $doCampaigns->insert();
        }
        if ($oComponent) {
            $oComponent->processCampaignForm($aFields);
        }
        // Recalculate priority only when editing a campaign
        // or moving banners into a newly created, and when:
        //
        // - campaign changes status (activated or deactivated) or
        // - the campaign is active and target/weight are changed
        //
        if (!$new_campaign) {
            $doCampaigns = OA_Dal::staticGetDO('campaigns', $aFields['campaignid']);
            $status = $doCampaigns->status;
            switch (true) {
                case (bool) $status != (bool) $aFields['status_old']:
                    // Run the Maintenance Priority Engine process
                    OA_Maintenance_Priority::scheduleRun();
                    break;
                case $status == OA_ENTITY_STATUS_RUNNING:
                    if (!empty($aFields['target_type']) && ${$aFields['target_type']} != $aFields['target_old'] || !empty($aFields['target_type']) && $aFields['target_type_old'] != $aFields['target_type'] || $aFields['weight'] != $aFields['weight_old'] || $aFields['clicks'] != $aFields['previousclicks'] || $aFields['conversions'] != $aFields['previousconversions'] || $aFields['impressions'] != $aFields['previousimpressions']) {
                        // Run the Maintenance Priority Engine process
                        OA_Maintenance_Priority::scheduleRun();
                    }
                    break;
            }
        }
        // Rebuild cache
        // include_once MAX_PATH . '/lib/max/deliverycache/cache-'.$conf['delivery']['cache'].'.inc.php';
        // phpAds_cacheDelete();
        // Delete channel forecasting cache
        include_once 'Cache/Lite.php';
        $options = array('cacheDir' => MAX_CACHE);
        $cache = new Cache_Lite($options);
        $group = 'campaign_' . $aFields['campaignid'];
        $cache->clean($group);
        $translation = new OX_Translation();
        if ($new_campaign) {
            // Queue confirmation message
            $translated_message = $translation->translate($GLOBALS['strCampaignHasBeenAdded'], array(MAX::constructURL(MAX_URL_ADMIN, 'campaign-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid']), htmlspecialchars($aFields['campaignname']), MAX::constructURL(MAX_URL_ADMIN, 'banner-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid'])));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
            OX_Admin_Redirect::redirect("advertiser-campaigns.php?clientid=" . $aFields['clientid']);
        } else {
            $translated_message = $translation->translate($GLOBALS['strCampaignHasBeenUpdated'], array(MAX::constructURL(MAX_URL_ADMIN, 'campaign-edit.php?clientid=' . $aFields['clientid'] . '&campaignid=' . $aFields['campaignid']), htmlspecialchars($aFields['campaignname'])));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
            OX_Admin_Redirect::redirect("campaign-edit.php?clientid=" . $aFields['clientid'] . "&campaignid=" . $aFields['campaignid']);
        }
    }
    //return processing errors
    return $errors;
}
Пример #17
0
 /**
  * A method to return the end day of the span in UTC (ISO
  *
  * @param string $format An optional PEAR::Date compatible format string.
  * @return string The end day of the span.
  */
 function getEndDateStringUTC($format = '%Y-%m-%d')
 {
     $oDate = new Date($this->oEndDate);
     $oDate->toUTC();
     return $oDate->getDate(DATE_FORMAT_ISO);
 }
Пример #18
0
	public function getExpirationDate() {
	    $startDate = new Date(isset($this->m_data['StartDate']) ? $this->m_data['StartDate'] : 0);
	    $timeSpan = new Date_Span();
	    $timeSpan->setFromDays($this->m_data['Days']);
	    $startDate->addSpan($timeSpan);
	    return $startDate->getDate();
	}
Пример #19
0
 function showAction()
 {
     $this->date = Date::getDate('m/d/Y');
     $this->layout = 'default';
     $this->render('date/show');
 }
Пример #20
0
 function runMacro($func, $arg)
 {
     global $dbh;
     $ret = '';
     switch ($func) {
         case 'list':
             $arg = str_replace('?', '_', $arg);
             $arg = str_replace('*', '%', $arg);
             $sql = "SELECT name FROM nodes WHERE name LIKE '{$arg}'";
             // catch errors
             $dbh->pushErrorHandling(PEAR_ERROR_RETURN);
             $nodes = $dbh->getCol($sql, 0);
             $dbh->popErrorHandling();
             if (is_array($nodes)) {
                 $ret = implode("\n", $nodes);
             }
             break;
         case 'phpdoc':
             $url = "http://php.net/{$arg}";
             $ret = "<a href=\"{$url}\">{$arg} (php.net)</a>";
             break;
         case 'pear-listall':
             include_once "PEAR/Config.php";
             include_once "PEAR/Remote.php";
             $config =& PEAR_Config::singleton();
             @($remote =& new PEAR_Remote($config));
             @($packages = $remote->call('package.listAll'));
             $ret = implode("\n", array_keys($packages));
             break;
         case 'recent':
             include_once "Date.php";
             $arg = (int) $arg;
             $res = $dbh->limitQuery("SELECT name, mtime FROM nodes ORDER BY mtime DESC", 0, $arg);
             $ret = '';
             while ($res->fetchInto($tmp)) {
                 $date = new Date($tmp['mtime']);
                 $ret .= "{$tmp['name']} " . $date->getDate() . "\n";
             }
             $res->free();
             break;
     }
     return $ret;
 }
Пример #21
0
 /**
  * Returns the data used by the weekly report.
  *
  * @access  public
  * @param   string $usr_id The ID of the user this report is for.
  * @param   string The start date of this report.
  * @param   string The end date of this report.
  * @param   boolean If closed issues should be separated from other issues.
  * @return  array An array of data containing all the elements of the weekly report.
  */
 function getWeeklyReport($usr_id, $start, $end, $separate_closed = false)
 {
     $usr_id = Misc::escapeInteger($usr_id);
     // figure out timezone
     $user_prefs = Prefs::get($usr_id);
     $tz = @$user_prefs["timezone"];
     $start_dt = new Date();
     $end_dt = new Date();
     // set timezone to that of user.
     $start_dt->setTZById($tz);
     $end_dt->setTZById($tz);
     // set the dates in the users time zone
     $start_dt->setDate($start . " 00:00:00");
     $end_dt->setDate($end . " 23:59:59");
     // convert time to GMT
     $start_dt->toUTC();
     $end_dt->toUTC();
     $start_ts = $start_dt->getDate();
     $end_ts = $end_dt->getDate();
     $time_tracking = Time_Tracking::getSummaryByUser($usr_id, $start_ts, $end_ts);
     // replace spaces in index with _ and calculate total time
     $total_time = 0;
     foreach ($time_tracking as $category => $data) {
         unset($time_tracking[$category]);
         $time_tracking[str_replace(" ", "_", $category)] = $data;
         $total_time += $data["total_time"];
     }
     // get count of issues assigned in week of report.
     $stmt = "SELECT\n                    COUNT(*)\n                 FROM\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "issue,\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "issue_user,\n                    " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "status\n                 WHERE\n                    iss_id = isu_iss_id AND\n                    iss_sta_id = sta_id AND\n                    isu_usr_id = {$usr_id} AND\n                    isu_assigned_date BETWEEN '{$start_ts}' AND '{$end_ts}'";
     $newly_assigned = $GLOBALS["db_api"]->dbh->getOne($stmt);
     if (PEAR::isError($newly_assigned)) {
         Error_Handler::logError(array($newly_assigned->getMessage(), $newly_assigned->getDebugInfo()), __FILE__, __LINE__);
     }
     $email_count = array("associated" => Support::getSentEmailCountByUser($usr_id, $start_ts, $end_ts, true), "other" => Support::getSentEmailCountByUser($usr_id, $start_ts, $end_ts, false));
     $data = array("start" => str_replace('-', '.', $start), "end" => str_replace('-', '.', $end), "user" => User::getDetails($usr_id), "group_name" => Group::getName(User::getGroupID($usr_id)), "issues" => History::getTouchedIssuesByUser($usr_id, $start_ts, $end_ts, $separate_closed), "status_counts" => History::getTouchedIssueCountByStatus($usr_id, $start_ts, $end_ts), "new_assigned_count" => $newly_assigned, "time_tracking" => $time_tracking, "email_count" => $email_count, "phone_count" => Phone_Support::getCountByUser($usr_id, $start_ts, $end_ts), "note_count" => Note::getCountByUser($usr_id, $start_ts, $end_ts), "total_time" => Misc::getFormattedTime($total_time, false));
     return $data;
 }
Пример #22
0
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date.
     $prefix = $this->getTablePrefix();
     $oNowDate = new Date($oDate);
     $oNowDate->toUTC();
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate_time AS start,\n                ca.expire_time AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ((\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . " AND\n                    (\n                        ca.expire_time IS NOT NULL\n                        OR\n                        (\n                            ca.views > 0\n                            OR\n                            ca.clicks > 0\n                            OR\n                            ca.conversions > 0\n                        )\n                    )\n                ) OR (\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_AWAITING, 'integer') . " AND\n                    (\n                        ca.activate_time <= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                        AND\n                        (\n                            ca.weight > 0\n                            OR\n                            ca.priority > 0\n                        )\n                        AND\n                        (\n                            ca.expire_time >= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                            OR\n                            ca.expire_time IS NULL\n                        )\n                    )\n                ))\n            ORDER BY\n                advertiser_id";
     OA::debug('- Requesting campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug('  - Selecting impressions, clicks and conversions for this running campaign ID = ' . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (isset($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (!isset($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (!isset($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (!isset($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '  - Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if (!empty($aCampaign['end'])) {
                 // The campaign has a valid end date, stored in in UTC
                 $oEndDate = new Date($aCampaign['end']);
                 $oEndDate->setTZByID('UTC');
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "  - Passed campaign end time of '" . $oEndDate->getDate() . " UTC" . "': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("  - Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending campaign deactivated email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                     // Also send campaignDeliveryEmail for the campaign we just deactivated.
                     $doClients = OA_Dal::staticGetDO('clients', $aCampaign['advertiser_id']);
                     $aAdvertiser = $doClients->toArray();
                     OA::debug("  - Sending campaign delivery email ", PEAR_LOG_DEBUG);
                     $oStart = new Date($aAdvertiser['reportlastdate']);
                     $oEnd = new Date($oDate);
                     // Set end date to tomorrow so we get stats for today.
                     $oEnd->addSpan(new Date_Span('1-0-0-0'));
                     $oEmail->sendCampaignDeliveryEmail($aAdvertiser, $oStart, $oEnd, $aCampaign['campaign_id']);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     OA::debug("  - Sending campaign 'soon deactivated' email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } elseif (!empty($aCampaign['start'])) {
             // The campaign is awaiting activation and has a valid start date, stored in UTC
             $oStartDate = new Date($aCampaign['start']);
             $oStartDate->setTZByID('UTC');
             // Find out if there are any impression, click or conversion targets for
             // the campaign (i.e. if the target values are > 0)
             $remainingImpressions = 0;
             $remainingClicks = 0;
             $remainingConversions = 0;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug("  - The campaign ID " . $aCampaign['campaign_id'] . " has an impression, click and/or conversion target, requesting impressions so far", PEAR_LOG_DEBUG);
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 // Set the remaining impressions, clicks and conversions for the campaign
                 $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                 $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                 $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
             }
             // In order for the campaign to be activated, need to test:
             // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
             //    then there must be remaining impressions to deliver (> 0); and
             // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
             //    then there must be remaining clicks to deliver (> 0); and
             // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
             //    then there must be remaining conversions to deliver (> 0)
             if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0)) {
                 $message = "- Passed campaign start time of '" . $oStartDate->getDate() . " UTC" . "': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                 OA::debug($message, PEAR_LOG_INFO);
                 $report .= $message . "\n";
                 $doCampaigns = OA_Dal::factoryDO('campaigns');
                 $doCampaigns->campaignid = $aCampaign['campaign_id'];
                 $doCampaigns->find();
                 $doCampaigns->fetch();
                 $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                 $result = $doCampaigns->update();
                 if ($result == false) {
                     return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 phpAds_userlogSetUser(phpAds_userMaintenance);
                 phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending activation email for campaign ID " . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                 }
             }
         }
     }
 }
Пример #23
0
 function testAbstraction()
 {
     $d = new Date();
     $my = new myDate($d);
     $this->assertEquals($d->getDate(), $my->getDate());
 }
Пример #24
0
 /**
  * Prune all entries where the ad_id is for a banner in a High Priority Campaign where:
  * The campaign has a booked number of lifetime target impressions and/or clicks and/or conversions AND the campaign is not active AND at least one of the booked lifetime target values has been reached.
  *
  */
 function testpruneDataSummaryAdZoneAssocTargetReached()
 {
     $oToday = new Date();
     $oExpire = new Date();
     $oExpire->subtractSeconds(999999);
     $today = $oToday->getDate();
     $expire = $oExpire->getDate();
     $oDal = new OA_Maintenance_Pruning();
     $doDSAZA = OA_Dal::factoryDO('data_summary_ad_zone_assoc');
     $doDIA = OA_Dal::factoryDO('data_intermediate_ad');
     $aDIAs = DataGenerator::generate($doDIA, 4);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 1000;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 100;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 10;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[3]);
     $doDIA->ad_id = $this->idBanner1;
     $doDIA->impressions = 1;
     $doDIA->clicks = 0;
     $doDIA->conversions = 0;
     $doDIA->update();
     // generate 2 summary ad_zone records for an active campaign ad_id
     $doDSAZA->ad_id = $this->idBanner1;
     $aIds = DataGenerator::generate($doDSAZA, 2);
     // generate 7 summary ad_zone records for an inactive campaign ad_id
     $doDSAZA->ad_id = $this->idBanner2;
     $aIds = DataGenerator::generate($doDSAZA, 7);
     // make sure 9 rows in table
     $this->assertEqual($this->_countRowsInDSAZA(), 9);
     // ad_id 1 => campaignid 1 => active, high priority, not expired, target impressions not reached
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 100000;
     $doCampaigns->clicks = 1000;
     $doCampaigns->conversions = 100;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(1);
     // 0 records were deleted
     $this->assertEqual($result, 0);
     // 0 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 9);
     // ad_id 1 => campaignid 1 => not active, high priority, not expired, target impressions reached
     $doCampaigns = OA_Dal::staticGetDO('campaigns', $this->idCampaign1);
     $doCampaigns->priority = 5;
     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $doCampaigns->views = 1111;
     $doCampaigns->clicks = 111;
     $doCampaigns->conversions = 11;
     $doCampaigns->update();
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(1);
     // 1 record deleted
     $this->assertEqual($result, 1);
     // 8 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 8);
     $result = $oDal->_pruneDataSummaryAdZoneAssocInactiveTargetReached(5);
     // 1 record was deleted
     $this->assertEqual($result, 1);
     // 7 records remain
     $this->assertEqual($this->_countRowsInDSAZA(), 7);
 }
 /**
  * A method to test the activation and deactivation of campaigns within
  * the manageCampaigns() method.
  */
 function testManageCampaigns()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('now', new Date('2004-06-05 09:00:00'));
     $oFactory = new OX_Dal_Maintenance_Statistics_Factory();
     $oDalMaintenanceStatistics = $oFactory->factory();
     // Create the required accounts & set the various ID values
     $aValues = $this->_createAccounts();
     $adminAccountId = $aValues['adminAccount'];
     $managerAccountId = $aValues['managerAccount'];
     $advertiserClientId = $aValues['advertiserClient'];
     $oTimezone = new Date_TimeZone('Australia/Sydney');
     /******************************************************************************/
     /* Prepare Campaign and Banner Data for Tests 1 - 4                           */
     /******************************************************************************/
     // Campaign 1, Orphaned
     $aData = array('campaignname' => 'Test Campaign 1');
     $idCampaign1 = $this->_insertPlacement($aData);
     // Campaign 2:
     // - Owned by Advertiser 1
     // - Lifetime Target Impressions of 10
     $aData = array('campaignname' => 'Test Campaign 2', 'clientid' => $advertiserClientId, 'views' => 10);
     $idCampaign2 = $this->_insertPlacement($aData);
     // Campaign 3:
     // - Owned by Advertiser 1
     // - Lifetime Target Clicks of 10
     $aData = array('campaignname' => 'Test Campaign 3', 'clientid' => $advertiserClientId, 'clicks' => 10);
     $idCampaign3 = $this->_insertPlacement($aData);
     // Campaign 4:
     // - Owned by Advertiser 1
     // - Lifetime Target Conversions of 10
     $aData = array('campaignname' => 'Test Campaign 4', 'clientid' => $advertiserClientId, 'conversions' => 10);
     $idCampaign4 = $this->_insertPlacement($aData);
     // Campaign 5:
     // - Owned by Advertiser 1
     // - Lifetime Target Impressions of 10
     // - Lifetime Target Clicks of 10
     // - Lifetime Target Conversions of 10
     $aData = array('campaignname' => 'Test Campaign 5', 'clientid' => $advertiserClientId, 'views' => 10, 'clicks' => 10, 'conversions' => 10);
     $idCampaign5 = $this->_insertPlacement($aData);
     // Campaign 6:
     // - Owned by Advertiser 1
     // - No Lifetime Target Impressions
     // - Campaign Expiration of 2004-06-06
     $oDate = new Date('2004-06-06 23:59:59');
     $oDate->setTZ($oTimezone);
     $oDate->toUTC();
     $aData = array('campaignname' => 'Test Campaign 6', 'clientid' => $advertiserClientId, 'views' => -1, 'expire_time' => $oDate->getDate(DATE_FORMAT_ISO));
     $idCampaign6 = $this->_insertPlacement($aData);
     // Campaign 7:
     // - Owned by Advertiser 1
     // - No Lifetime Target Impressions
     // - Campaign Activation of 2004-06-06
     // - Currently not active
     $oDate = new Date('2004-06-06 00:00:00');
     $oDate->setTZ($oTimezone);
     $oDate->toUTC();
     $aData = array('campaignname' => 'Test Campaign 7', 'clientid' => $advertiserClientId, 'activate_time' => $oDate->getDate(DATE_FORMAT_ISO), 'status' => OA_ENTITY_STATUS_AWAITING);
     $idCampaign7 = $this->_insertPlacement($aData);
     // Banner 1
     // - In Campaign 1
     $aData = array('campaignid' => $idCampaign1);
     $idBanner1 = $this->_insertAd($aData);
     // Banner 2
     // - In Campaign 2
     $aData = array('campaignid' => $idCampaign2);
     $idBanner2 = $this->_insertAd($aData);
     // Banner 3
     // - In Campaign 2
     $aData = array('campaignid' => $idCampaign2);
     $idBanner3 = $this->_insertAd($aData);
     // Banner 4
     // - In Campaign 2
     $aData = array('campaignid' => $idCampaign2);
     $idBanner4 = $this->_insertAd($aData);
     // Banner 5
     // - In Campaign 3
     $aData = array('campaignid' => $idCampaign3);
     $idBanner5 = $this->_insertAd($aData);
     // Banner 6
     // - In Campaign 4
     $aData = array('campaignid' => $idCampaign4);
     $idBanner6 = $this->_insertAd($aData);
     // Banner 7
     // - In Campaign 5
     $aData = array('campaignid' => $idCampaign5);
     $idBanner7 = $this->_insertAd($aData);
     // Banner 8
     // - In Campaign 6
     $aData = array('campaignid' => $idCampaign6);
     $idBanner8 = $this->_insertAd($aData);
     // Banner 9
     // - In Campaign 7
     $aData = array('campaignid' => $idCampaign7);
     $idBanner9 = $this->_insertAd($aData);
     // Reset now
     $oServiceLocator->remove('now');
     /******************************************************************************/
     // Test 1: Prepare a date for the manageCampaigns() method to run at in UTC;
     //         2004-06-05 13:01:00 UTC is 2004-06-05 23:01:00 Australia/Sydney
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->setDate('2004-06-05 13:01:00');
     $oServiceLocator->register('now', $oDate);
     // Test 1: Run the method with no summarised data, and a UTC date/time
     //         that is before the start/end dates that are set in
     //         Campaign 6 and Campaign 7
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     // Test 1: Campaign 1 is orphaned, test that default values are unchanged
     $this->_testCampaignByCampaignId($idCampaign1, -1, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 2 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign2, 10, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 3 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign3, -1, 10, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 4 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign4, -1, -1, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 5 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign5, 10, 10, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 6 is owned, and has a campaign end date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should still be running
     $this->_testCampaignByCampaignId($idCampaign6, -1, -1, -1, null, '2004-06-06 13:59:59', OA_ENTITY_STATUS_RUNNING);
     // Test 1: Campaign 7 is owned, and has a campaign start date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should still not be running
     $this->_testCampaignByCampaignId($idCampaign7, -1, -1, -1, '2004-06-05 14:00:00', null, OA_ENTITY_STATUS_AWAITING);
     /******************************************************************************/
     // Test 2: Prepare a date for the manageCampaigns() method to run at in UTC;
     //         2004-06-05 14:01:00 UTC is 2004-06-06 00:01:00 Australia/Sydney
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->setDate('2004-06-05 14:01:00');
     $oServiceLocator->register('now', $oDate);
     // Test 2: Run the method with no summarised data, and a UTC date/time
     //         that is before the end date of Campaign 6 (as campaigns end at
     //         the end of the day), but after the start date of Campaign 7
     //         (as campaigns start at the start of the day)
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     // Test 2: Campaign 1 is orphaned, test that default values are unchanged
     $this->_testCampaignByCampaignId($idCampaign1, -1, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 2 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign2, 10, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 3 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign3, -1, 10, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 4 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign4, -1, -1, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 5 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign5, 10, 10, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 6 is owned, and has a campaign end date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should still be running
     $this->_testCampaignByCampaignId($idCampaign6, -1, -1, -1, null, '2004-06-06 13:59:59', OA_ENTITY_STATUS_RUNNING);
     // Test 2: Campaign 7 is owned, and has a campaign start date, and given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should now be running
     $this->_testCampaignByCampaignId($idCampaign7, -1, -1, -1, '2004-06-05 14:00:00', null, OA_ENTITY_STATUS_RUNNING);
     /******************************************************************************/
     // Test 3: Prepare a date for the manageCampaigns() method to run at in UTC;
     //         2004-06-06 13:01:00 UTC is 2004-06-06 23:01:00 Australia/Sydney
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->setDate('2004-06-06 13:01:00');
     $oServiceLocator->register('now', $oDate);
     // Test 3: Run the method with no summarised data, and a UTC date/time
     //         that is (still) before the end date of Campaign 6 (as campaigns
     //         end at the end of the day), but (still) after the start date of
     //         Campaign 7 (as campaigns start at the start of the day)
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     // Test 3: Campaign 1 is orphaned, test that default values are unchanged
     $this->_testCampaignByCampaignId($idCampaign1, -1, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 2 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign2, 10, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 3 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign3, -1, 10, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 4 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign4, -1, -1, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 5 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign5, 10, 10, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 6 is owned, and has a campaign end date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should still be running
     $this->_testCampaignByCampaignId($idCampaign6, -1, -1, -1, null, '2004-06-06 13:59:59', OA_ENTITY_STATUS_RUNNING);
     // Test 3: Campaign 7 is owned, and has a campaign start date, and given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should now be running
     $this->_testCampaignByCampaignId($idCampaign7, -1, -1, -1, '2004-06-05 14:00:00', null, OA_ENTITY_STATUS_RUNNING);
     /******************************************************************************/
     // Test 4: Prepare a date for the manageCampaigns() method to run at in UTC;
     //         2004-06-06 14:01:00 UTC is 2004-06-07 00:01:00 Australia/Sydney
     $oDate = new Date();
     $oDate->toUTC();
     $oDate->setDate('2004-06-06 14:01:00');
     $oServiceLocator->register('now', $oDate);
     // Test 4: Run the method with no summarised data, and a UTC date/time
     //         that is now after the end date of Campaign 6 (as campaigns
     //         end at the end of the day), and (still) after the start date of
     //         Campaign 7 (as campaigns start at the start of the day)
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     // Test 4: Campaign 1 is orphaned, test that default values are unchanged
     $this->_testCampaignByCampaignId($idCampaign1, -1, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 4: Campaign 2 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign2, 10, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 4: Campaign 3 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign3, -1, 10, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 4: Campaign 4 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign4, -1, -1, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 4: Campaign 5 is owned, but with no start/end date, and no data rows
     //         yet, should be unchanged from initial values
     $this->_testCampaignByCampaignId($idCampaign5, 10, 10, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 4: Campaign 6 is owned, and has a campaign end date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should no longer still be running
     $this->_testCampaignByCampaignId($idCampaign6, -1, -1, -1, null, '2004-06-06 13:59:59', OA_ENTITY_STATUS_EXPIRED);
     // Test 4: Campaign 7 is owned, and has a campaign start date, and given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should now be running
     $this->_testCampaignByCampaignId($idCampaign7, -1, -1, -1, '2004-06-05 14:00:00', null, OA_ENTITY_STATUS_RUNNING);
     /******************************************************************************/
     /* Prepare Campaign Banner Delivery Data for Test 5                           */
     /******************************************************************************/
     // Banner 1 is in Campaign 1
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner1, 'impressions' => 1, 'clicks' => 1, 'conversions' => 1);
     $idDIA1 = $this->_insertDataIntermediateAd($aData);
     // Banner 2 is in Campaign 2
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner2, 'impressions' => 1, 'clicks' => 1, 'conversions' => 1);
     $idDIA2 = $this->_insertDataIntermediateAd($aData);
     // Banner 3 is in Campaign 2
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner3, 'impressions' => 1, 'clicks' => 0, 'conversions' => 0);
     $idDIA3 = $this->_insertDataIntermediateAd($aData);
     // Banner 4 is in Campaign 2
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner4, 'impressions' => 8, 'clicks' => 0, 'conversions' => 0);
     $idDIA4 = $this->_insertDataIntermediateAd($aData);
     // Banner 5 is in Campaign 3
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner5, 'impressions' => 1000, 'clicks' => 5, 'conversions' => 1000);
     $idDIA5 = $this->_insertDataIntermediateAd($aData);
     // Banner 6 is in Campaign 4
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner6, 'impressions' => 1000, 'clicks' => 1000, 'conversions' => 1000);
     $idDIA6 = $this->_insertDataIntermediateAd($aData);
     // Banner 7 is in Campaign 5
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner7, 'impressions' => 0, 'clicks' => 4, 'conversions' => 6);
     $idDIA7 = $this->_insertDataIntermediateAd($aData);
     // Banner 8 is in Campaign 6
     $aData = array('interval_start' => '2004-06-06 17:00:00', 'interval_end' => '2004-06-06 17:59:59', 'ad_id' => $idBanner8, 'impressions' => 0, 'clicks' => 4, 'conversions' => 6);
     $idDIA8 = $this->_insertDataIntermediateAd($aData);
     /******************************************************************************/
     // Test 5: Now that impressions, clicks and conversions have been
     //         delivered, re-run with the same date as Test 4 and make
     //         sure that campaigns are deactivated as required
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     // Test 5: Campaign 1 is orphaned, test that default values are unchanged
     $this->_testCampaignByCampaignId($idCampaign1, -1, -1, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 5: Campaign 2 is owned, with no start/end date, but now with
     //         10 impressions across three banners, so the campaign should
     //         no longer be running
     $this->_testCampaignByCampaignId($idCampaign2, 10, -1, -1, null, null, OA_ENTITY_STATUS_EXPIRED);
     // Test 5: Campaign 3 is owned, with no start/end date, but now with
     //         only 5 clicks, the campaign should still be running (even
     //         though there are lots of impressions and conversions)
     $this->_testCampaignByCampaignId($idCampaign3, -1, 10, -1, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 5: Campaign 4 is owned, with no start/end date, but now with
     //         1000 conversions, the campaign should no longer be running
     $this->_testCampaignByCampaignId($idCampaign4, -1, -1, 10, null, null, OA_ENTITY_STATUS_EXPIRED);
     // Test 5: Campaign 5 is owned, with no start/end date, but now with
     //         no impressions, only 4 clicks and only 6 conversions, the
     //         campaign should still be running
     $this->_testCampaignByCampaignId($idCampaign5, 10, 10, 10, null, null, OA_ENTITY_STATUS_RUNNING);
     // Test 5: Campaign 6 is owned, and has a campaign end date, but given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should no longer still be running
     $this->_testCampaignByCampaignId($idCampaign6, -1, -1, -1, null, '2004-06-06 13:59:59', OA_ENTITY_STATUS_EXPIRED);
     // Test 5: Campaign 7 is owned, and has a campaign start date, and given the
     //         advertiser's manager timezone and the time that the manageCampaigns()
     //         method was run, the campaign should now be running
     $this->_testCampaignByCampaignId($idCampaign7, -1, -1, -1, '2004-06-05 14:00:00', null, OA_ENTITY_STATUS_RUNNING);
     /******************************************************************************/
     DataGenerator::cleanUp();
 }
Пример #26
0
// | to obtain it through the world-wide-web, please send a note to       |
// | pear-dev@lists.php.net so we can mail you a copy immediately.        |
// +----------------------------------------------------------------------+
// | Author: Leandro Lucarella <*****@*****.**>                           |
// +----------------------------------------------------------------------+
//
// $Id$
//
require_once 'Date.php';
require_once 'Date/Span.php';
$date = new Date();
$tmp = new Date($date);
printf("Actual date: %s\n", $date->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->subtractSpan(new Date_Span('0:00:00:05'));
printf("Subtracting 5 seconds: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->subtractSpan(new Date_Span('0:00:20:00'));
printf("Subtracting 20 minutes: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->subtractSpan(new Date_Span('0:10:00:00'));
printf("Subtracting 10 hours: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->subtractSpan(new Date_Span('3:00:00:00'));
printf("Subtracting 3 days: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->subtractSpan(new Date_Span('3:10:20:05'));
printf("Subtracting 3 days, 10 hours, 20 minutes and 5 seconds: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
$tmp->copy($date);
$tmp->addSpan(new Date_Span('0:00:00:05'));
printf("Adding 5 seconds: %s\n", $tmp->getDate(DATE_FORMAT_ISO));
 /**
  * Prepares and executes the SQL query.
  * 
  * @throws BadgerException If an SQL error occured.
  */
 private function fetchFromDB()
 {
     if ($this->dataFetched) {
         return;
     }
     //Add condition to limit balance to transactions in the past and today
     $today = new Date();
     $sql = "SELECT a.account_id, a.currency_id, a.title, a.description, a.lower_limit, a.upper_limit,\n\t\t\t\ta.currency_id, (\n\t\t\t\t\tSELECT SUM( ft.amount ) \n\t\t\t\t\tFROM finished_transaction ft\n\t\t\t\t\tWHERE a.account_id = ft.account_id\n\t\t\t\t\t\tAND (ft.valuta_date <= '" . $today->getDate() . "' OR ft.valuta_date IS NULL)\n\t\t\t\t) balance, a.last_calc_date, a.csv_parser, a.delete_old_planned_transactions\n\t\t\tFROM account a\n\t\t\t\tINNER JOIN currency c ON a.currency_id = c.currency_id\n\t\t";
     $where = $this->getFilterSQL();
     if ($where) {
         $sql .= " WHERE {$where}\n ";
     }
     $order = $this->getOrderSQL();
     if ($order) {
         $sql .= "ORDER BY {$order}\n ";
     }
     //echo "<pre>$sql</pre>";
     $this->dbResult =& $this->badgerDb->query($sql);
     if (PEAR::isError($this->dbResult)) {
         throw new BadgerException('AccountManager', 'SQLError', "SQL: {$sql}\n" . $this->dbResult->getMessage());
     }
     $this->dataFetched = true;
 }
 /**
  * Tests that an e-mail reporting on impending campaign expiration
  * is able to be generated correctly.
  */
 function testSendAndPrepareCampaignImpendingExpiryEmail()
 {
     $adminContact = 'Andrew Hill';
     $adminName = 'OpenX Limited';
     $adminMail = '*****@*****.**';
     $adminCompany = 'Admin company name';
     $adminAccountId = 100;
     $agencyName = 'Agency Ltd.';
     $agencyContact = 'Mr. Foo Bar Agency';
     $agencyMail = '*****@*****.**';
     $advertiserName = 'Foo Client';
     $advertiserMail = '*****@*****.**';
     $advertiserUsername = '******';
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['webpath']['admin'] = 'example.com';
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['logOutgoing'] = true;
     $mockName = uniqid('PartialMockOA_Email_');
     Mock::generatePartial('OA_Email', $mockName, array('sendMail'));
     $oEmail = new $mockName();
     $oEmail->setReturnValue('sendMail', true);
     // Prepare valid test data
     $dateReason = 'date';
     $dateValue = '2007-05-15';
     $impReason = 'impressions';
     $impValue = 100;
     // The tests below assume that the number of days before a campaign expires when the
     $oCampaignDate = new Date($dateValue);
     $oCampaignDate->setHour(23);
     $oCampaignDate->setMinute(59);
     $oCampaignDate->setSecond(59);
     $oCampaignDate->toUTC();
     $oTwoDaysPriorDate = new Date($dateValue);
     $oTwoDaysPriorDate->subtractSeconds(2 * 24 * 60 * 60 - 10);
     $oNowDate = new Date($dateValue);
     // Prepare an admin user
     // Create the admin account
     $doAccounts = OA_Dal::factoryDO('accounts');
     $doAccounts->account_name = 'System Administrator';
     $doAccounts->account_type = OA_ACCOUNT_ADMIN;
     $adminAccountId = DataGenerator::generateOne($doAccounts);
     // Setup the admin account id
     $doAppVar = OA_Dal::factoryDO('application_variable');
     $doAppVar->name = 'admin_account_id';
     $doAppVar->value = $adminAccountId;
     // Create an user
     $doAdminUser = OA_Dal::factoryDO('users');
     $doAdminUser->contact_name = $adminContact;
     $doAdminUser->email_address = $adminMail;
     $doAdminUser->username = $adminName;
     $doAdminUser->password = md5('password');
     $doAdminUser->language = 'en';
     $doAdminUser->default_account_id = $adminAccountId;
     $adminUserId = DataGenerator::generateOne($doAdminUser);
     $doAdminUser = OA_Dal::staticGetDO('users', $adminUserId);
     $aAdminUser = $doAdminUser->toArray();
     // Create admin account-user association
     $doAUA = OA_Dal::factoryDO('account_user_assoc');
     $doAUA->account_id = $adminAccountId;
     $doAUA->user_id = $adminUserId;
     $doAUA->insert();
     // Prepare an agency
     $doAgency = OA_Dal::factoryDO('agency');
     $doAgency->name = $agencyName;
     $doAgency->contact = $agencyContact;
     $doAgency->email = $agencyMail;
     $agencyId = DataGenerator::generateOne($doAgency);
     $doAgency = OA_Dal::staticGetDO('agency', $agencyId);
     //get('agencyid', $agencyId);
     $agencyAccountId = $doAgency->account_id;
     // Prepare an agency user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $agencyContact;
     $doUser->email_address = $agencyMail;
     $doUser->username = $agencyName;
     $doUser->language = 'en';
     $agencyUserId = DataGenerator::generateOne($doUser);
     $doAgencyUser = OA_Dal::staticGetDO('users', $agencyUserId);
     $aAgencyUser = $doAgencyUser->toArray();
     $oUserAccess = new OA_Admin_UI_UserAccess();
     // Agency user
     $oUserAccess->linkUserToAccount($agencyUserId, $doAgency->account_id, array(), array());
     // Generate an advertiser owned by the agency with no email adddress,
     // but no placements, and ensure false is returned
     $doClients = OA_Dal::factoryDO('clients');
     $doClients->agencyid = $agencyId;
     $doClients->clientname = $advertiserName;
     $doClients->email = '';
     $advertiserId1 = DataGenerator::generateOne($doClients);
     $doClients = OA_Dal::staticGetDO('clients', 'clientid', $advertiserId1);
     // ->get('clientid', $advertiserId1);
     $advertiserAccountId = $doClients->account_id;
     // Create an advertiser user
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = $advertiserName;
     $doUser->email_address = $advertiserMail;
     $doUser->username = $advertiserUsername;
     $doUser->language = 'en';
     $userId = DataGenerator::generateOne($doUser);
     $doAdvertiserUser = OA_Dal::staticGetDO('users', $userId);
     $aAdvertiserUser = $doAdvertiserUser->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($userId, $doClients->account_id, array(), array());
     // Create a campaign
     $doPlacements = OA_Dal::factoryDO('campaigns');
     $doPlacements->clientid = $advertiserId1;
     $doPlacements->campaignname = 'Default Campaign';
     $doPlacements->views = 50;
     $doPlacements->expire_time = $oCampaignDate->getDate(DATE_FORMAT_ISO);
     $placementId = DataGenerator::generateOne($doPlacements);
     $doPlacements = OA_Dal::staticGetDO('campaigns', $placementId);
     $aCampaign = $doPlacements->toArray();
     $result = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     // No emails should be sent yet because the preferences weren't set
     $this->assertEqual($result, 0);
     // No entries in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->find();
     $this->assertFalse($doUserLog->fetch());
     // Create the preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin threshold preference
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create the admin day warning
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_admin_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADMIN;
     $warnEmailAdminDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     // Set the admin preference
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $adminAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdminDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the agency preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_manager_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_MANAGER;
     $warnEmailManagerDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Set the advertiser preferences
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_impression_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserImpLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserImpLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 100;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     $doPreferences = OA_Dal::factoryDO('preferences');
     $doPreferences->preference_name = 'warn_email_advertiser_day_limit';
     $doPreferences->account_type = OA_ACCOUNT_ADVERTISER;
     $warnEmailAdvertiserDayLimitPreferenceId = DataGenerator::generateOne($doPreferences);
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserDayLimitPreferenceId;
     $doAccount_Preference_Assoc->value = 2;
     DataGenerator::generateOne($doAccount_Preference_Assoc);
     // Create another user linked to the advertiser account and ensure that an additional email is sent
     $doUser = OA_Dal::factoryDO('users');
     $doUser->contact_name = '2_' . $advertiserName;
     $doUser->email_address = '2_' . $advertiserMail;
     $doUser->username = '******' . $clientName;
     $doUser->language = 'de';
     $advertiserUserId2 = DataGenerator::generateOne($doUser);
     $doAdvertiserUser2 = OA_Dal::staticGetDO('users', $advertiserUserId2);
     $aAdvertiserUser2 = $doAdvertiserUser2->toArray();
     // Link the advertiser user
     $oUserAccess->linkUserToAccount($advertiserUserId2, $doClients->account_id, array(), array());
     // If the advertiser preference is off, then the advertiser should not be sent emails
     // even if the admin/manager preference is on
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // And turning off the manager preference should leave just agency emails (2)
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 0;
     $doAccount_Preference_Assoc->update();
     // -- The above sets up the environment for the tests below -- //
     // Check the body when passing in the admin user:
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     // Clear cache
     $oEmail->clearCache();
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // One entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     $this->assertEqual($aUserLog[0]['action'], phpAds_actionWarningMailed);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 1);
     // Still one entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 1);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 2);
     // Use email from details instead of the owning account's details
     $aConf['email']['useManagerDetails'] = false;
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Use email from empty details and test that not Regards are added
     $aConf['email']['fromAddress'] = '';
     $aConf['email']['fromName'] = '';
     $aConf['email']['fromCompany'] = '';
     // Manager user
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'manager');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $aConf['email']['useManagerDetails'] = true;
     $aConf['email']['fromAddress'] = $adminMail;
     $aConf['email']['fromName'] = $adminName;
     $aConf['email']['fromCompany'] = $adminCompany;
     // Should create another entry in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // The following should never be sent because a campaign without banners should never deliver (and therefore never reach the "remaining" threshold)
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAgencyUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " There are currently no banners defined for this campaign.\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   " . $aConf['email']['fromName'] . ", " . $aConf['email']['fromCompany'];
     Language_Loader::load('default', $aAgencyUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oNowDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAgencyUser, $advertiserId1, $placementId, $impReason, $impValue, 'manager');
     $this->assertEqual($numSent, 0);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Emails not sent, nothing new in userlog
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 4);
     // Add some banners and retest
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = '';
     $bannerId1 = DataGenerator::generateOne($doBanners);
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $placementId;
     $doBanners->description = 'Test Banner';
     $doBanners->url = 'http://www.fornax.net/';
     $bannerId2 = DataGenerator::generateOne($doBanners);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdminUser['contact_name']},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     Language_Loader::load('default', $aAdminUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId1, $dateReason, $dateValue, 'admin');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 5);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below is due to end on {$dateValue}.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     Language_Loader::load('default', $aAdvertiserUser['language']);
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $dateReason, $dateValue, 'advertiser');
     $this->assertEqual($numSent, 1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear userlog table
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->whereAdd('1=1');
     $doUserLog->delete(DB_DATAOBJECT_WHEREADD_ONLY);
     // Enable the warn_email_advertiser preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $advertiserAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailAdvertiserPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     // Clear cache
     $oEmail->clearCache();
     // So should now send 1 admin and 2 advertiser emails
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 3);
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$adminContact},\n\n";
     $expectedContents .= "The campaign belonging to {$advertiserName} shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$adminName}, {$adminCompany}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdminUser, $advertiserId1, $placementId, $impReason, $impValue, 'admin');
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 3);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 6);
     // Clear cache
     $oEmail->clearCache();
     // Enable the warn_email_manager preference and retest
     $doAccount_Preference_Assoc = OA_Dal::factoryDO('account_preference_assoc');
     $doAccount_Preference_Assoc->account_id = $agencyAccountId;
     $doAccount_Preference_Assoc->preference_id = $warnEmailManagerPreferenceId;
     $doAccount_Preference_Assoc->value = 1;
     $doAccount_Preference_Assoc->update();
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Turn off email logging and send mail again
     $aConf['email']['logOutgoing'] = false;
     $numSent = $oEmail->sendCampaignImpendingExpiryEmail($oTwoDaysPriorDate, $placementId);
     $this->assertEqual($numSent, 4);
     // No new entries in user log
     $doUserLog = OA_Dal::factoryDO('userlog');
     $doUserLog->action = phpAds_actionWarningMailed;
     $aUserLog = $doUserLog->getAll();
     $this->assertEqual(count($aUserLog), 10);
     // Set email logging back to true
     $aConf['email']['logOutgoing'] = true;
     $expectedSubject = "Impending campaign expiration: {$advertiserName}";
     $expectedContents = "Dear {$aAdvertiserUser['contact_name']},\n\n";
     $expectedContents .= "Your campaign shown below has less than {$impValue} impressions remaining.\n\n";
     $expectedContents .= "As a result, the campaign will soon be automatically disabled, and the\n";
     $expectedContents .= "following banners in the campaign will also be disabled:\n";
     $expectedContents .= "\nCampaign [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  linked to: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Regards,\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     // Check that advertiser2's email is send in their desired language (german)
     $expectedSubject = "Bevorstehende Deaktivierung der Kampagne: {$advertiserName}";
     $expectedContents = "Sehr geehrte(r) {$aAdvertiserUser2['contact_name']},\n\n";
     $expectedContents .= "Unten angegebene Ihre Kampagne hat weniger als {$impValue} Impressions übrig.\n\n";
     $expectedContents .= "Auf Grund dessen wird die Kampagne bald deaktiviert und weiter unten angegebene Banner aus dieser Kampagne werden deaktiviert:\n";
     $expectedContents .= "\nKampagne [id{$placementId}] Default Campaign\n";
     $expectedContents .= "http://{$aConf['webpath']['admin']}/stats.php?clientid={$advertiserId1}&campaignid={$placementId}&statsBreakdown=day&entity=campaign&breakdown=history&period_preset=all_stats&period_start=&period_end=\n";
     $expectedContents .= "-------------------------------------------------------\n\n";
     $expectedContents .= " Banner [id{$bannerId1}] Test Banner\n\n";
     $expectedContents .= " Banner [id{$bannerId2}] Test Banner\n";
     $expectedContents .= "  verknüpft mit: http://www.fornax.net/\n\n";
     $expectedContents .= "-------------------------------------------------------\n\n\n";
     $expectedContents .= "Mit freundlichem Gruß\n   {$agencyContact}, {$agencyName}";
     $aResult = $oEmail->prepareCampaignImpendingExpiryEmail($aAdvertiserUser2, $advertiserId1, $placementId, $impReason, $impValue, 'advertiser');
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), 2);
     $this->assertEqual($aResult['subject'], $expectedSubject);
     $this->assertEqual(str_replace("\r", "", $aResult['contents']), str_replace("\r", "", $expectedContents));
     DataGenerator::cleanUp(array('accounts', 'account_user_assoc'));
 }
Пример #29
0
     } elseif ((!$require_login || $require_login && isSuperUser()) && $key == "confirmed") {
         Sql_Query("update {$tables["user"]} set {$key} = \"" . sql_escape($_POST[$key]) . "\" where id = {$id}");
     }
 }
 if (is_array($_POST['attribute'])) {
     while (list($key, $val) = each($_POST['attribute'])) {
         Sql_Query(sprintf('replace into %s (userid,attributeid,value)
   values(%d,%d,"%s")', $tables["user_attribute"], $id, $key, $val));
     }
 }
 if (is_array($_POST["dateattribute"])) {
     foreach ($_POST["dateattribute"] as $attid => $attname) {
         if (isset($_POST[normalize($attname) . '_novalue'])) {
             $value = "";
         } else {
             $value = $date->getDate($attname);
         }
         Sql_Query(sprintf('replace into %s (userid,attributeid,value)
   values(%d,%d,"%s")', $tables["user_attribute"], $id, $attid, $value));
     }
 }
 if (is_array($_POST['cbattribute'])) {
     while (list($key, $val) = each($_POST['cbattribute'])) {
         if ($_POST['attribute'][$key] == "on") {
             Sql_Query(sprintf('replace into %s (userid,attributeid,value)
       values(%d,%d,"on")', $tables["user_attribute"], $id, $key));
         } else {
             Sql_Query(sprintf('replace into %s (userid,attributeid,value)
       values(%d,%d,"")', $tables["user_attribute"], $id, $key));
         }
     }
 function _convertDate($date, $tz, $end)
 {
     if (empty($date) || $date == '0000-00-00') {
         return null;
     }
     $oDate = new Date($date);
     $oDate->setTZByID($tz);
     if ($end) {
         $oDate->setHour(23);
         $oDate->setMinute(59);
         $oDate->setSecond(59);
     }
     $oDate->toUTC();
     return $oDate->getDate(DATE_FORMAT_ISO);
 }