/**
  * Конструктор класса
  *
  */
 public function __construct()
 {
     // Название класса
     $className = get_class($this);
     // Подключаем объект CI
     $CI =& get_instance();
     // Подключаем хелпер периодов дат
     $CI->load->helper('periods');
     // Подготавливаем массив для чтения из поста даты
     $fields = array('from' => type_cast($CI->input->post('from'), 'date'), 'to' => type_cast($CI->input->post('to'), 'date'), 'period' => $CI->input->post('period'), 'mode' => $CI->input->post('mode'));
     if (false !== $fields['mode']) {
         // Устанавливаем период
         $period = data_range($fields);
         $this->setUnixRange($period['from'], $period['to']);
         // Сохраняем период
         period_save($className, $fields);
     } else {
         // Загружаем период
         $fields = period_load($className, 'select', 'today');
         // Устанавливаем период
         $period = data_range($fields);
         $this->setUnixRange($period['from'], $period['to']);
     }
     $this->specifiedRange = false;
 }
 /**
  * возвращает список рекламодателей
  *
  * @param integer $page номер запрошенной страницы
  * @param integer $per_page количество записей на странице
  * @param string $sort_field имя поля, по которому осуществляется сортировка
  * @param string $sort_direction направление сортировки
  * @param string $filt фильтр по статусу
  * @param array $range массив с двумя датами - начала и конце периода ('from', 'to')
  * @param string $quickSearch 
  * @return array массив с данными рекламодателей (id => (name, email, join_date, status, ballance, impressions, clicks, ctr, spent)) 
  */
 public function get($page, $per_page, $sort_field, $sort_direction, $filt, $range, $quickSearch = '')
 {
     $sql = "\n   \t  \tSELECT \n   \t  \t\ta.id_entity_advertiser AS id,\n   \t  \t\te.name,\n   \t  \t\te_mail,\n   \t  \t\tUNIX_TIMESTAMP(creation_date) as join_date,\n   \t  \t\ter.status,\n   \t  \t\tballance,\n   \t  \t\te.bonus,\n   \t  \t\t(SUM(clicks)*100/SUM(impressions)) AS ctr,\n   \t  \t\tSUM(sa.impressions) AS impressions,\n   \t  \t\tSUM(sa.clicks) AS clicks,\n   \t  \t\tSUM(sa.spent) AS spent\n   \t  \tFROM advertisers a\n      \t\tJOIN entities e ON a.id_entity_advertiser = e.id_entity\n      \t\tJOIN entity_roles er ON (er.id_entity = e.id_entity AND er.id_role = " . self::ID_ROLE . ")\n      \t\tLEFT JOIN stat_advertisers sa ON (a.id_entity_advertiser = sa.id_entity_advertiser\n      \t\t\tAND sa.stat_date BETWEEN '" . type_to_str($range['from'], 'databasedate') . "' AND '" . type_to_str($range['to'], 'databasedate') . "')\n      \tWHERE 1 = 1 \n   \t  ";
     if ($filt != 'all') {
         $sql .= ' AND er.status = ' . $this->db->escape($filt);
     }
     if (!empty($quickSearch)) {
         $escapedQuickSearch = $this->db->escape_str($quickSearch);
         $mysql_date = type_to_str(type_cast($quickSearch, 'date'), 'databasedate');
         $sql .= " AND ((e.id_entity = '{$escapedQuickSearch}')\n      \t \t\t\t\tOR (e.name LIKE '%" . $escapedQuickSearch . "%')\n      \t \t\t\t\tOR (e.e_mail LIKE '%" . $escapedQuickSearch . "%')\n      \t \t\t\t\tOR (e.creation_date LIKE '%" . $mysql_date . "%'))\n      \t \t\t ";
     }
     $sql .= "\n      \tGROUP BY id\n      \tORDER BY " . $sort_field . " " . $sort_direction . "\n      \tLIMIT " . ($page - 1) * $per_page . ", " . $per_page . "\n      ";
     $res = $this->db->query($sql);
     $list = array();
     $id_list = array();
     foreach ($res->result() as $row) {
         $id_list[] = $row->id;
         $list[$row->id]['id'] = $row->id;
         $list[$row->id]['name'] = $row->name;
         $list[$row->id]['email'] = $row->e_mail;
         $list[$row->id]['join_date'] = $row->join_date;
         $list[$row->id]['status'] = $row->status;
         $list[$row->id]['ballance'] = $row->ballance;
         $list[$row->id]['bonus'] = $row->bonus;
         $list[$row->id]['impressions'] = $row->impressions;
         $list[$row->id]['clicks'] = $row->clicks;
         $list[$row->id]['spent'] = $row->spent;
         $list[$row->id]['ctr'] = $row->ctr;
     }
     return $list;
 }
 /**
  * конструктор класса,
  * вносит изменения в структуру базового класса
  *
  * @return ничего не возвращает
  */
 public function Edit_advertiser()
 {
     parent::Parent_entity();
     $this->content["CANCEL"] = $this->site_url . $this->index_page . 'admin/manage_advertisers';
     $code = $this->input->post('edit_code');
     $this->content["IDENTITY"] = $code;
     $this->content['SROLE'] = 'admin';
     $id_entity = type_cast($code, 'textcode');
     $this->form_data["id"] = $id_entity;
     $this->form_data["kill"] = array("terms_and_conditions", "confirm_password", "password");
     $this->form_data['vars']['CODE'] = $code;
     $this->form_data["redirect"] = "admin/edit_advertiser/success";
     unset($this->form_data["fields"]["confirm"]);
     unset($this->form_data["fields"]["password"]);
     $this->button_name = __("Update Account");
     $this->cancel_redirect = $this->site_url . $this->index_page . 'admin/manage_advertisers';
     $this->content["INFO"] = $this->load->view("advertiser/account_settings/info.html", "", TRUE);
     $this->_set_title(implode(self::TITLE_SEP, array(__('Administrator'), __('Edit Advertiser'))));
     $this->_set_help_index("edit_advertiser");
     $this->load->model('entity', '', TRUE);
     $entity = $this->entity->get_name_and_mail($id_entity);
     if (is_null($entity)) {
         return;
     }
     $this->formname = '<a href="' . $this->site_url . $this->index_page . 'admin/manage_advertisers' . '">' . __("Manage Advertisers") . '</a> &rarr; ' . __("Edit Advertiser") . ':&nbsp;&nbsp;<span class="green i">&bdquo;' . $entity->name . "({$entity->e_mail})&ldquo;</span> ";
 }
 public function index($code)
 {
     $this->load->model("entity");
     $this->load->library("form");
     $this->form_data['id'] = type_cast($code, 'textcode');
     $this->_set_content($this->form->get_form_content("modify", $this->form_data, $this->input, $this));
     $this->_set_help_index("change_password");
     $this->_display();
 }
 /**
  * тоже что и index, но делает текущей выбранную кампанию
  *
  * @param string $code шифрованный код выбранной кампании
  * @return ничего не возвращает
  */
 public function campaign($code)
 {
     $this->id_campaign = $code;
     $id_campaign = type_cast($code, 'textcode');
     $this->load->model('campaigns', '', TRUE);
     if ($this->campaigns->get_entity($id_campaign) != $this->user_id) {
         redirect($this->role . '/dashboard');
     }
     $this->index();
 }
 public function index($code)
 {
     if ($this->user_id != type_cast($code, 'textcode')) {
         //Если админ меняет пароль другого юзера, то старый пароль не спрашиваем
         unset($this->form_data['fields']['old']);
         $this->form_data['kill'] = array('old_password');
         $this->form_data['redirect'] = $this->role . '/change_pass/admin_success';
     }
     parent::index($code);
 }
 public function index($group_code = FALSE, $program_type = null)
 {
     $this->set_campaign_type('edit_channels');
     $this->setCurrentStep('/advertiser/edit_channels');
     $this->load->model('groups', '', TRUE);
     $code = $this->input->post('group');
     if (FALSE === $code) {
         $code = $group_code;
     } else {
         //Если код группы есть в POST, то на страницу пришли из раздела Manage Ads (производим очистку XML)
         $this->new_campaign->free_storage($this->id_xml);
         $this->id_xml = uniqid();
         $this->session->set_userdata('id_xml', $this->id_xml);
     }
     if (2 == $this->new_campaign->init_storage($this->id_xml)) {
         //на первом шаге создаем xml-файл и наполняем его данными выбранной группы
         $id_group = type_cast($code, 'textcode');
         //$this->new_campaign->free_storage($this->id_xml);
         //$this->new_campaign->init_storage($this->id_xml);
         $this->new_campaign->set_group_name($code);
         /*$channels = $this->groups->get_channels($id_group);
           foreach ($channels as $channel) {
           	$this->new_campaign->add_channel($channel);
           }*/
         $this->new_campaign->set_program_type($program_type);
         $site_channels = $this->groups->get_site_channels($id_group, false);
         foreach ($site_channels as $site_channel) {
             $this->new_campaign->add_site_channel($site_channel);
         }
         $this->new_campaign->apply_sites_channels();
         $frequency_coup = $this->groups->get_frequency_coup($id_group);
         $this->new_campaign->set_daily_impressions($frequency_coup > 0 ? $frequency_coup : '');
         $this->new_campaign->save_data();
     } else {
         //на остальных шагах работаем с xml-файлом
         //$this->new_campaign->init_storage($this->id_xml);
         $code = $this->new_campaign->get_group_name();
         $id_group = type_cast($code, 'textcode');
     }
     $this->cancel_creation_controller = 'advertiser/manage_ads/group/' . $code . '/channels';
     $this->load->model('campaigns', '', TRUE);
     $campaign_name = type_to_str($this->groups->parent_campaign($id_group), 'encode');
     $id_campaign = type_to_str($this->groups->id_parent_campaign($id_group), 'textcode');
     $group_name = type_to_str($this->groups->name($id_group), 'encode');
     $group_code = type_to_str($id_group, 'textcode');
     $this->form_title = '<h1><a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads">{@Manage Ads@}</a> &rarr; ' . '<a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads/campaign/' . $id_campaign . '">{@Campaign@}:</a> <span class="green i">&bdquo;' . $campaign_name . '&ldquo;</span> &rarr; ' . '<a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads/group/' . $group_code . '/channels">{@Group@}:</a> <span class="green i">&bdquo;' . $group_name . '&ldquo;</span></h1>';
     parent::index('edit_channels');
 }
 public function index()
 {
     $this->load->model('groups', '', TRUE);
     $this->new_campaign->init_storage($this->id_xml);
     $code = $this->new_campaign->get_group_name();
     $this->id_group = type_cast($code, 'textcode');
     $this->cancel_creation_controller = 'advertiser/manage_ads/group/' . $code . '/channels';
     $this->load->model('campaigns', '', TRUE);
     $campaign_name = type_to_str($this->groups->parent_campaign($this->id_group), 'encode');
     $id_campaign = type_to_str($this->groups->id_parent_campaign($this->id_group), 'textcode');
     $group_name = type_to_str($this->groups->name($this->id_group), 'encode');
     $group_code = type_to_str($this->id_group, 'textcode');
     $this->form_title = '<h1><a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads">{@Manage Ads@}</a> &rarr; ' . '<a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads/campaign/' . $id_campaign . '">{@Campaign@}:</a> <span class="green i">&bdquo;' . $campaign_name . '&ldquo;</span> &rarr; ' . '<a href="<%SITEURL%><%INDEXPAGE%>advertiser/manage_ads/group/' . $group_code . '/channels">{@Group@}:</a> <span class="green i">&bdquo;' . $group_name . '&ldquo;</span></h1>';
     $this->next_step = 'advertiser/edit_set_pricing/success/' . $code;
     parent::index('edit_channels');
 }
 /**
  * AJAX-функция, помечает элементы списка как удаленные
  *
  * @param POST values список значений списка
  * @param POST targeting_group_code шифрованный код группы таргетинга
  * @param POST group наименование группы значений
  * @return ничего не возвращает
  */
 public function set_values()
 {
     $values = $this->input->post('values');
     $group = $this->input->post('group');
     $denied = $this->input->post('denied');
     if ($denied == 0) {
         $values = '';
     }
     $targeting_group_code = $this->input->post('targeting_group_code');
     $id_targeting_group = type_cast($targeting_group_code, 'textcode');
     $this->load->model('targeting_groups', '', TRUE);
     //while(!is_null($this->global_variables->get("set_values_".$id_targeting_group."_".$group, $this->user_id)));
     //$this->global_variables->set("set_values_".$id_targeting_group."_".$group, "true", $this->user_id, TRUE);
     $this->targeting_groups->set_group_value($id_targeting_group, $group, $values);
     //$this->global_variables->kill($this->user_id, "set_values_".$id_targeting_group."_".$group);
 }
 /**
  * выполнение различных действий над выбранными рекламодателями
  *
  * @param string $action действие, которое необходимо выполнить
  * @return ничего не возвращает
  */
 protected function _actions($action)
 {
     $id_entities = $this->input->post('id_entity');
     if (is_array($id_entities)) {
         foreach ($id_entities as $code) {
             $id_entity = type_cast($code, 'textcode');
             switch ($action) {
                 case 'pause':
                     if ($this->advertisers->pause($id_entity)) {
                         $this->_set_notification('Selected advertiser accounts was paused.');
                     } else {
                         $this->_set_notification('Selected advertiser accounts wasn\'t paused.');
                     }
                     break;
                 case 'resume':
                     if ($this->advertisers->resume($id_entity)) {
                         $this->_set_notification('Selected advertiser accounts was resumed.');
                     } else {
                         $this->_set_notification('Selected advertiser accounts wasn\'t resumed.');
                     }
                     break;
                 case 'approve':
                     if ($this->advertisers->approve($id_entity)) {
                         $this->_set_notification('Selected advertiser accounts was approved.');
                     } else {
                         $this->_set_notification('Selected advertiser accounts wasn\'t approved.');
                     }
                     break;
                 case 'delete':
                     if ($this->advertisers->delete($id_entity)) {
                         $this->_set_notification('Selected advertiser accounts was successfully deleted.');
                     } else {
                         $this->_set_notification('Selected advertiser accounts wasn\'t deleted.');
                     }
                     break;
                 case 'restore':
                     if ($this->advertisers->restore($id_entity)) {
                         $this->_set_notification('Selected advertiser accounts was successfully restored.');
                     } else {
                         $this->_set_notification('Selected advertiser accounts wasn\'t restored.');
                     }
                     break;
             }
         }
     }
 }
 /**
  * получение глобальной переменной для заданного пользователя
  *
  * @param string $name имя переменной
  * @param int $id_entity код пользователя владельца переменной,по умолчанию - 0 (системная переменная)
  * @param string $default значение переменной по умолчанию
  * @return string значение переменной или NULL если переменная не найдена
  */
 public function get($name, $id_entity = 0, $default = NULL)
 {
     if (isset($this->_variablesCache[$id_entity][$name])) {
         return $this->_variablesCache[$id_entity][$name];
     }
     $this->db->select('value, type');
     $this->db->from('settings');
     $this->db->join('setting_fields', 'settings.name=setting_fields.name', 'left');
     $this->db->where(array('settings.name' => $name, 'id_entity' => $id_entity));
     $res = $this->db->get();
     if ($res->num_rows()) {
         $row = $res->row();
         $this->_variablesCache[$id_entity][$name] = type_cast($row->value, $row->type);
     } else {
         $this->_variablesCache[$id_entity][$name] = $default;
     }
     return $this->_variablesCache[$id_entity][$name];
 }
 public function _save($id, $fields)
 {
     $id_entity = type_cast($id, 'textcode');
     $balance = $this->entity->ballance($id_entity);
     if ($fields['balance_mode'] == 'add') {
         $balance += $fields['amount'];
         $value = $fields['amount'];
     } else {
         if ($balance < $fields['amount']) {
             return __("You can't set user balance negative!");
         }
         $balance -= $fields['amount'];
         $value = -$fields['amount'];
     }
     $this->entity->set_ballance($id_entity, $balance);
     $this->load->model('payment_gateways', '', TRUE);
     $this->payment_gateways->money_flow($this->user_id, $id_entity, $value, $balance, 0, $value > 0 ? 'deposit' : 'deduction', 0, TRUE, 0);
     $this->load->model('sites_channels', '', TRUE);
     $this->sites_channels->autopay($id_entity);
     return '';
 }
 /**
  * совершает выбранное действие над выделенными кампаниями
  *
  * @param $action действие производимое над кампаниями (delete)
  * @return ничего не возвращает
  */
 public function _actions($action)
 {
     $this->content['JSACTION'] = '';
     $id_campaigns = $this->input->post('id_campaigns');
     if (is_array($id_campaigns) && !empty($action)) {
         foreach ($id_campaigns as $code) {
             $id_campaign = type_cast($code, 'textcode');
             $this->campaigns->action($action, $this->user_id, $id_campaign);
         }
         switch ($action) {
             case 'pause':
                 $this->_set_notification('Selected campaigns was paused.');
                 break;
             case 'resume':
                 $this->_set_notification('Selected campaigns was resumed.');
                 break;
             case 'delete':
                 $this->_set_notification('Selected campaigns was deleted.');
                 $this->content['JSACTION'] = "\$(['" . implode("','", $id_campaigns) . "']).each(function(a){top.deleteCampaign(this);});";
                 break;
         }
     }
 }
 /**
  * функция по умолчанию, выводит данные выбранного отчета на экран
  *
  * @param POST view_code зашифрованный код выбранного отчета
  * @return ничего не возвращает
  */
 public function index()
 {
     $on_start = $this->input->post('on_start');
     if ($on_start) {
         $this->global_variables->kill_vars($this->user_id, array('viewreport_page', 'viewreport_sort_direction', 'viewreport_sort_field', 'viewreport_per_page'));
     }
     $code = $this->code;
     if (is_null($code)) {
         $code = $this->input->post('view_code');
     }
     if (!$code) {
         $this->_report_not_found();
         return;
     }
     $id_report = type_cast($code, 'textcode');
     $this->load->model('report_types');
     $this->load->model('report_generator', '', TRUE);
     $report = $this->report_types->report($this->user_id, $id_report);
     $info = $this->report_generator->get_report_info($id_report);
     if (!$report) {
         $this->_report_not_found();
         return;
     }
     if ($report['id_entity'] != $this->user_id || $info['role'] != $this->role) {
         $this->_report_not_found();
         return;
     }
     $this->load->library('Table_Builder');
     $this->table_builder->clear();
     $this->table_builder->insert_empty_cells = true;
     // Page Total
     $page_total = array();
     $total = array();
     $all_columns = $this->report_types->columns_info($report['type'], -1);
     foreach ($all_columns['columns'] as $name => $data) {
         if ($data['is_total']) {
             $page_total[$name] = 0;
             $total[$name] = 0;
         }
     }
     $columns = $this->report_types->columns_info($report['type'], $report['vis']);
     $this->table_builder->init_sort_vars('viewreport', $columns['sort']['name'], $columns['sort']['direction']);
     $this->load->model('pagination_post');
     $this->pagination_post->set_form_name('viewreport');
     $this->load->model('sqlite');
     $sqlite_file = $this->report_generator->get_sqlite_file($id_report);
     if (!file_exists($sqlite_file) || filesize($sqlite_file) == 0) {
         //redirect($this->from_controller.'/not_found');
         //exit();
         $this->_report_not_found();
         return;
         $this->_set_notification('Sorry! Report file not found.');
         $this->_set_content($this->load->view('common/view_report/file_not_found.html', '', TRUE));
         $this->_display();
         return;
     }
     $sqlite = $this->sqlite->get_database($sqlite_file);
     if (!$sqlite) {
         //$this->_set_content($this->load->view('common/view_report/file_not_found.html', '', TRUE));
         //$this->_display();
         $this->_report_not_found();
         return;
     }
     $this->pagination_post->set_total_records($this->report_generator->total($sqlite));
     $this->pagination_post->read_variables('viewreport', 1, $this->global_variables->get('ReportRowsPerPage'));
     $reports = $this->report_generator->report($sqlite, $this->table_builder->sort_field, $this->table_builder->sort_direction, $this->temporary['viewreport_page'], $this->temporary['viewreport_per_page']);
     $count = 0;
     foreach ($columns['columns'] as $name => $data) {
         $this->table_builder->sorted_column($count, $name, $data['title'], $data['direction']);
         $count++;
     }
     // Total
     $total = $this->report_generator->total_info($sqlite, array_keys($total));
     $this->table_builder->add_row_attribute(0, 'class', 'th');
     $this->table_builder->add_attribute('class', 'xTable');
     $clone_icon = "<img class='icon' src='{$this->site_url}images/pixel.gif'/>" . __('Clone');
     $row = 1;
     $invariable_columns = array();
     foreach ($reports as $report_data) {
         $column = 0;
         foreach ($report_data as $name => $value) {
             if (isset($page_total[$name])) {
                 $page_total[$name] += $value;
             }
             if (isset($columns['columns'][$name])) {
                 $c = $columns['columns'][$name];
                 if ($c['is_unchanged']) {
                     array_push($invariable_columns, $column);
                 }
                 $this->table_builder->set_cell_content($row, $column, type_to_str(type_to_str($value, $c['type']), 'encode'));
                 $column++;
             }
         }
         $row++;
     }
     // Устанавливаем возможность выбора колонок
     $this->table_builder->use_select_columns();
     $this->table_builder->set_invariable_columns($invariable_columns);
     if (0 == count($reports)) {
         $this->table_builder->insert_empty_cells = false;
         $this->table_builder->set_cell_content(1, 0, __('Records not found'));
         $this->table_builder->cell(1, 0)->add_attribute('class', '"nodata"');
         $this->table_builder->cell(1, 0)->add_attribute('colspan', count($columns['columns']));
     } else {
         // Display page total
         foreach (array('Page total' => 'page_total', 'Total' => 'total') as $title => $var) {
             $arr = ${$var};
             $this->table_builder->set_cell_content($row, 0, __($title));
             $i = 0;
             foreach ($all_columns['columns'] as $name => $data) {
                 if ($data['is_total'] && 'ctr' == $name) {
                     if (isset($arr['clicks']) && isset($arr['impressions'])) {
                         $arr[$name] = $arr['impressions'] ? $arr['clicks'] / $arr['impressions'] * 100 : 0;
                     } else {
                         $arr[$name] = 0;
                     }
                 } elseif ($data['is_total'] && 'cpc' == $name) {
                     // TODO: В будущем при добавлении новых типов отчетов нужно покопаться здесь
                     $col = $data['role'] == 'advertiser' ? 'spent' : 'earned';
                     if (isset($arr['clicks']) && isset($arr[$col])) {
                         $arr[$name] = $arr['clicks'] ? $arr[$col] / $arr['clicks'] : 0;
                     } else {
                         $arr[$name] = 0;
                     }
                 }
                 if (isset($columns['columns'][$name])) {
                     if ($data['is_total']) {
                         $this->table_builder->set_cell_content($row, $i, type_to_str(type_to_str($arr[$name], $data['type']), 'encode'));
                     }
                     $i++;
                 }
             }
             $this->table_builder->clear_row_attributes($row);
             $this->table_builder->add_row_attribute($row, 'class', 'pagetotal');
             $row++;
         }
     }
     $vars = array('FROM' => __($this->menu_item), 'REPORTNAME' => $report['title'], 'TABLE' => $this->table_builder->get_sort_html(), 'PAGINATION' => $this->pagination_post->create_form(), 'RETURN' => $this->site_url . $this->index_page . $this->from_controller, 'FROMCONTROLLER' => $this->from_controller, 'SORT' => $this->table_builder->sort_field, 'DIRECTION' => $this->table_builder->sort_direction, 'ROLE' => $this->role, 'CODE' => $code, 'COLUMNS' => $this->table_builder->get_columns_html());
     $this->_set_content($this->parser->parse('common/view_report/template.html', $vars, TRUE));
     $this->_set_help_index("view_report");
     $this->_display();
 }
    /**
     * Search sites according to specified criteria
     *
     * @return void
     */
    public function search_sites()
    {
        //load nessesary components
        $this->load->model('pagination_post');
        $filter_mode = $this->input->post('filter_mode');
        $this->load->helper('periods_helper');
        $siteModel = new Sppc_SiteModel();
        //initialize table builder
        $this->table_builder->clear();
        $this->table_builder->init_sort_vars('search_sites_cpc', 'url', 'asc');
        $col_index = 0;
        $col_alias = array('url' => $col_index++, 'impressions' => $col_index++, 'clicks' => $col_index++, 'min_bid' => $col_index++, 'min_bid_image' => $col_index++, 'action' => $col_index++);
        $this->table_builder->sorted_column($col_alias['url'], 'url', "Site", 'asc');
        $this->table_builder->sorted_column($col_alias['impressions'], 'impressions', "Monthly Traffic Volume", 'asc');
        $this->table_builder->sorted_column($col_alias['clicks'], 'clicks', "Clicks", 'asc');
        $this->table_builder->sorted_column($col_alias['min_bid'], 'min_cpc', "Min Bid Text", 'asc');
        $this->table_builder->sorted_column($col_alias['min_bid_image'], 'min_cpc_image', "Min Bid Image", 'asc');
        $this->table_builder->set_cell_content(0, $col_alias['action'], __('Action'));
        $this->table_builder->cell(0, $col_alias['action'])->add_attribute('class', 'simpleTitle');
        // set table attributes
        $this->table_builder->add_attribute('class', 'xTable');
        //or set style here
        $this->table_builder->add_row_attribute(0, 'class', 'th f9px');
        $this->table_builder->add_col_attribute($col_alias['action'], 'class', 'center');
        $this->table_builder->insert_empty_cells = false;
        // initialize page browser
        $this->pagination_post->clear();
        $this->pagination_post->set_form_name('search_sites_cpc');
        //initialize from config
        $form_data = array("name" => "search_sites_cpc_form", "view" => "advertiser/manage_ads/campaigns/creation/select_sites/jframe_search_sites.html", "action" => $this->site_url . $this->index_page . "advertiser/create_campaign_step_select_sites/search_sites", 'fields' => array('filter_mode' => array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $filter_mode)));
        //initialize search filter object
        $dateRange = data_range(array('mode' => 'select', 'period' => 'lastmonth'));
        $statStartDate = new Zend_Date($dateRange['from'], Zend_Date::TIMESTAMP);
        $statEndDate = new Zend_Date($dateRange['to'], Zend_Date::TIMESTAMP);
        $searchFilter = new Sppc_Site_SearchFilter();
        $searchFilter->setConnectToStats(true, $statStartDate, $statEndDate)->setHasCpc(true);
        // according to filter mode configure search filter object
        switch ($filter_mode) {
            case 'all':
                //show all active sites
                break;
            case 'by_category':
                // search sites by category
                $categories = array();
                $id_category = $this->input->post('id_category');
                $include_subcats = $this->input->post('include_subcats');
                if ($id_category) {
                    $categoryModel = new Sppc_CategoryModel();
                    $category = $categoryModel->findObjectById($id_category);
                    if (!is_null($category)) {
                        $categories[] = $category;
                        if ($include_subcats == 'true') {
                            $categories = array_merge($categories, $category->getChildCategories(true));
                        }
                    }
                    $this->table_builder->insert_empty_cells = false;
                    $form_data['fields']['id_category'] = array('id_field_type' => 'int', 'form_field_type' => 'hidden', 'default' => $id_category);
                    $form_data['fields']['include_subcats'] = array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $include_subcats);
                }
                $searchFilter->setCategories($categories);
                break;
            case 'by_name':
                // search sites by id
                $siteIds = array();
                $id_site = $this->input->post('id_site');
                if ($id_site) {
                    $form_data['fields']['id_site'] = array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $id_site);
                    $id_site = explode(',', $id_site);
                    foreach ($id_site as $site) {
                        $siteIds[] = type_cast($site, 'textcode');
                    }
                }
                $searchFilter->setSiteId($siteIds);
                break;
            case 'by_price':
                // search sites by bid
                $bid = $this->input->post('price');
                $cpcBidType = $this->input->post('cpc_bid_type');
                $cpcBidType = in_array($cpcBidType, array('text', 'image')) ? $cpcBidType : false;
                if ($bid && $cpcBidType) {
                    $form_data['fields']['price'] = array('id_field_type' => 'positive_float', 'form_field_type' => 'hidden', 'default' => type_to_str($bid, 'float'));
                    $form_data['field']['cpc_bid_type'] = array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $cpcBidType);
                    switch ($cpcBidType) {
                        case 'text':
                            $searchFilter->setMaximumTextBid($bid);
                            break;
                        case 'image':
                            $searchFilter->setMaximumImageBid($bid);
                            break;
                    }
                }
                break;
        }
        $sitesCount = $siteModel->getCount($searchFilter);
        $this->pagination_post->set_total_records($sitesCount);
        $this->pagination_post->read_variables('search_sites_cpc', 1, 10);
        $sites = $siteModel->search($searchFilter, $this->table_builder->sort_field . ' ' . $this->table_builder->sort_direction, $this->pagination_post->get_per_page(), $this->pagination_post->get_page());
        $rowsCount = count($sites);
        if ($rowsCount > 0) {
            $rowCounter = 1;
            foreach ($sites as $site) {
                // url
                $this->table_builder->set_cell_content($rowCounter, $col_alias['url'], array('name' => $site->getUrl(), 'href' => 'http://' . $site->getUrl(), 'extra' => 'target="_blank"'), 'link');
                $this->table_builder->add_cell_content($rowCounter, $col_alias['url'], '<br>' . limit_str_and_hint($site->getName(), 30));
                // last month traffic
                $this->table_builder->set_cell_content($rowCounter, $col_alias['impressions'], type_to_str($site->getImpressions(), 'impressions'));
                // Clicks
                $this->table_builder->set_cell_content($rowCounter, $col_alias['clicks'], type_to_str($site->getClicks(), 'clicks'));
                // Min bid for text ads
                $cellContent = '
					<span class="min_bid_text">' . type_to_str($site->getMinCpc(), 'money') . '
						<span class="hide min_bid_value">' . type_to_str($site->getMinCpc(), 'float') . '</span>
					</span>';
                $this->table_builder->set_cell_content($rowCounter, $col_alias['min_bid'], $cellContent);
                // Min bid for image ads
                $cellContent = '
					<span class="min_image_bid_text">' . type_to_str($site->getMinCpcImage(), 'money') . '
						<span class="hide min_image_bid_value">' . type_to_str($site->getMinCpcImage(), 'float') . '
						</span>
					</span>';
                $this->table_builder->set_cell_content($rowCounter, $col_alias['min_bid_image'], $cellContent);
                // Actions
                $this->table_builder->set_cell_content($rowCounter, $col_alias['action'], array('name' => __('Add'), 'href' => '#', 'extra' => 'value="{@Add@}" title="{@Add@}" class="guibutton floatl ico ico-plusgreen" jframe="no" onclick="return addSiteToGroup(\'' . type_to_str($site->getId(), 'textcode') . '\');"'), 'link');
                // add attribute for row
                $this->table_builder->add_row_attribute($rowCounter, 'id_site', type_to_str($site->getId(), 'textcode'));
                $rowCounter++;
            }
        } else {
            $this->table_builder->set_cell_content(1, 0, __('Records not found'));
            $this->table_builder->cell(1, 0)->add_attribute('colspan', count($col_alias));
            $this->table_builder->cell(1, 0)->add_attribute('class', 'nodata');
        }
        // Устанавливаем возможность выбора колонок
        $this->table_builder->use_select_columns();
        $invariable_columns = array($col_alias['url'], $col_alias['action']);
        $this->table_builder->set_invariable_columns($invariable_columns);
        $sites_table = $this->table_builder->get_sort_html();
        $this->template = "common/parent/jq_iframe.html";
        $form_content = $this->form->get_form_content('create', $form_data, $this->input, $this);
        $form_content = str_replace('<%SITES_TABLE%>', $sites_table, $form_content);
        $form_content = str_replace('<%COLUMNS%>', $this->table_builder->get_columns_html(), $form_content);
        $form_content = str_replace('<%PAGINATION%>', $this->pagination_post->create_form(), $form_content);
        $this->_set_content($form_content);
        $this->_display();
    }
 function save_ad($code, $bulk = false, $bulk_field = 'all')
 {
     $jdata = array('status' => 'succ');
     $this->load->model('ads');
     // Получаем идентификатор рекламного объявления
     $id_ad = type_cast($code, 'textcode');
     // Проверяем на принадледность объявления рекламодателю
     if (!$this->ads->check_advert_ad($id_ad, $this->user_id)) {
         show_404();
     }
     // Получаем тип объявления
     $ad = $this->ads->get($id_ad);
     $type = $ad['ad_type'];
     // Валидируем
     $this->load->library('validation');
     $this->validation->set_error_delimiters('', '');
     $rules = array('title' => 'trim|required|max_length[25]', 'display_url' => 'trim|required|callback_check_url|max_length[35]', 'destination_url' => 'trim|required|callback_check_url|max_length[1024]', 'destination_protocol' => 'trim|required');
     if ('text' == $type) {
         $rules['description1'] = 'trim|required|max_length[35]';
         $rules['description2'] = 'trim|required|max_length[35]';
     }
     $this->validation->set_rules($rules);
     $titles = array('title' => __("Title"), 'display_url' => __("Display URL"), 'destination_url' => __("Destination URL"), 'destination_protocol' => __("Destination URL protocol"), 'description1' => __("Description 1"), 'description2' => __("Description 2"));
     if ($this->validation->run()) {
         // Получаем fileds
         $fields = array('title' => trim($this->input->post('title')), 'description1' => trim($this->input->post('description1')), 'description2' => trim($this->input->post('description2')), 'display_url' => trim($this->input->post('display_url')), 'destination_url' => trim($this->input->post('destination_url')), 'destination_protocol' => trim($this->input->post('destination_protocol')));
         // Сохраняем
         if (!$bulk) {
             $this->ads->save($id_ad, $fields, $type);
         } else {
             // Получаем группу
             $id_group = $this->ads->group($id_ad);
             // Получаем все объявления этой группы
             $ads = $this->ads->get_ads_ids_by_group($id_group);
             // Обновляем все объявления
             foreach ($ads as $id) {
                 // Собираем массив для обновления
                 $ad = $this->ads->get($id);
                 $ad_type = $ad['ad_type'];
                 if ('all' != $bulk_field && isset($fields[$bulk_field])) {
                     // Обновляем только одно поле
                     $ad[$bulk_field] = $fields[$bulk_field];
                     if ('destination_url' == $bulk_field) {
                         $ad['destination_protocol'] = $fields['destination_protocol'];
                     }
                 } else {
                     if ('image' == $type && 'image' != $ad['ad_type']) {
                         // Сохраняем descriptions для тектовых адов, если редактировался картиночный ад
                         $desc1 = $ad['description1'];
                         $desc2 = $ad['description2'];
                         $ad = $fields;
                         $ad['description1'] = $desc1;
                         $ad['description2'] = $desc2;
                     } else {
                         // Обновляем все поля
                         $ad = $fields;
                     }
                 }
                 $this->ads->save($id, $ad, $ad_type);
             }
         }
     } else {
         // Возвращяем ошибки
         $jdata['status'] = 'error';
         $errors = array();
         foreach (array_keys($rules) as $key) {
             $error = $key . '_error';
             if (isset($this->validation->{$error}) && !empty($this->validation->{$error})) {
                 $errors[$key] = str_replace('{@' . $key . '@}', "'" . $titles[$key] . "'", $this->validation->{$error});
             }
         }
         $jdata['errors'] = $errors;
     }
     echo json_encode($jdata);
 }
                // adding default media as well as album
                uihelper_add_default_media($_SESSION['user']['id']);
                uihelper_add_default_media($_SESSION['user']['id'], '_audio');
                uihelper_add_default_media($_SESSION['user']['id'], '_video');
                uihelper_add_default_blog($_SESSION['user']['id']);
            }
        } catch (PAException $e) {
            $msg = "{$e->message}";
        }
        $network = new Network();
        $network->set_params(array('network_id' => $nid));
        $netinfo = $network->get();
        $netinfo = $netinfo[0];
        $requester = new User();
        $requester->load((int) $_SESSION['user']['id']);
        $recipient = type_cast($netinfo, 'Network');
        // defined in helper_functions.php
        PANotify::send("network_join", $recipient, $requester, array());
        $redirect_url = "http://" . $netinfo->address . "." . PA::$domain_suffix . BASE_URL_REL . PA_ROUTE_HOME_PAGE . "/msg=7001";
        header("Location:{$redirect_url}");
        exit;
        // $msg = "You have successfully joined the '".stripslashes($netinfo->name)."' network. Click <a href='http://".$netinfo->address.".".PA::$domain_suffix.BASE_URL_REL."/homepage.php'>here</a> to go to network.";
    } else {
        //$msg = "Please login first to join the network.";
        header("Location: " . PA::$url . "/login.php?error=1&return=" . urlencode($_SERVER['REQUEST_URI']));
    }
} else {
    if ($_GET['action'] == 'leave') {
        try {
            if ($_SESSION['user']['id']) {
                $suc = Network::leave((int) PA::$network_info->network_id, (int) $_SESSION['user']['id']);
 /**
  * функция вызываемая по умолчанию, выводит таблицу кампаний
  *
  * @param integer $id_campaign уникальный код кампании, содержащей группы объявлений
  * @return ничего не возвращает
  */
 public function index($code_campaign)
 {
     $this->id_campaign = type_cast($code_campaign, 'textcode');
     $this->load->library('form');
     $this->load->helper('periods');
     $form = array('id' => 'groups', 'name' => 'manadsgroups_form', 'view' => 'advertiser/manage_ads/groups/table.html', 'redirect' => 'advertiser/manage_ads', 'no_errors' => 'true', 'vars' => array('DATEFILTER' => period_html('manadsgroups')), 'fields' => array('filt' => array('id_field_type' => 'string', 'form_field_type' => 'select', 'options' => array('all' => __('all'), 'active' => __('pl_active'), 'paused' => __('pl_paused')))));
     data_range_fields($form, 'select', 'alltime');
     $html = $this->form->get_form_content('modify', $form, $this->input, $this);
     $this->load->model('groups');
     $this->_actions($this->input->post('manadsgroups_action'));
     $this->load->library('Table_Builder');
     $this->table_builder->clear();
     $this->table_builder->insert_empty_cells = true;
     $this->table_builder->init_sort_vars('manadsgroups', 'id_campaign', 'asc');
     $this->load->model('pagination_post');
     $this->pagination_post->set_form_name('manadsgroups');
     $total_function = 'total';
     $total = $this->groups->{$total_function}($this->id_campaign, $this->temporary['manadsgroups_filt'], $this->date_range);
     $this->pagination_post->set_total_records($total['cnt']);
     $this->pagination_post->read_variables('manadsgroups', 1, $this->global_variables->get('GroupsPerPage'));
     $select_function = 'select';
     $groups = $this->groups->{$select_function}($this->id_campaign, $this->temporary['manadsgroups_page'], $this->temporary['manadsgroups_per_page'], $this->table_builder->sort_field, $this->table_builder->sort_direction, $this->temporary['manadsgroups_filt'], $this->date_range);
     $row = 0;
     //build column map
     $colIndex = 0;
     $colMap = array('chkbox' => $colIndex++, 'id' => $colIndex++, 'name' => $colIndex++, 'status' => $colIndex++, 'ads' => $colIndex++, 'siteChannels' => $colIndex++, 'spent' => $colIndex++, 'impressions' => $colIndex++, 'clicks' => $colIndex++, 'ctr' => $colIndex++, 'action' => $colIndex++);
     // register additional columns from plugins
     foreach ($this->_hooks as $hookObj) {
         $colMap = $hookObj->extendColumnMap($colMap);
     }
     // create columns
     $this->table_builder->set_cell_content($row, $colMap['chkbox'], array('name' => 'checkAll', 'extra' => 'onclick="return select_all(\'manadsgroups\', this)"'), 'checkbox');
     $this->table_builder->sorted_column($colMap['id'], "id_group", "ID", "asc");
     $this->table_builder->sorted_column($colMap['name'], "name", "Group Name", "asc");
     $this->table_builder->sorted_column($colMap['status'], "status", "Current Status", "asc");
     $this->table_builder->sorted_column($colMap['ads'], "ads", "Ads", "desc");
     $col_name = "Sites/Channels";
     $this->table_builder->sorted_column($colMap['siteChannels'], "site_channels", $col_name, "desc");
     $this->table_builder->set_cell_content($row, $colMap['spent'], __("Spent"));
     $this->table_builder->set_cell_content($row, $colMap['impressions'], __("Impressions"));
     $this->table_builder->set_cell_content($row, $colMap['clicks'], __("Clicks"));
     $this->table_builder->set_cell_content($row, $colMap['ctr'], __("CTR"));
     $this->table_builder->set_cell_content($row, $colMap['action'], __('Action'));
     // create additional columns from plugins
     foreach ($this->_hooks as $hookObj) {
         $hookObj->createColumns($colMap, $this->table_builder);
     }
     $this->table_builder->add_row_attribute($row, 'class', 'th');
     //прописывание стилей для ячеек
     $this->table_builder->add_col_attribute($colMap['chkbox'], 'class', '"chkbox"');
     $this->table_builder->add_col_attribute($colMap['id'], 'class', '"w20"');
     $this->table_builder->add_col_attribute($colMap['status'], 'class', '"w100  center"');
     $this->table_builder->add_col_attribute($colMap['ads'], 'class', '"w50   right"');
     $this->table_builder->add_col_attribute($colMap['siteChannels'], 'class', '"w100   right"');
     $this->table_builder->add_col_attribute($colMap['spent'], 'class', '"w100  right"');
     $this->table_builder->add_col_attribute($colMap['impressions'], 'class', '"w100   right"');
     $this->table_builder->add_col_attribute($colMap['clicks'], 'class', '"w50   right"');
     $this->table_builder->add_col_attribute($colMap['ctr'], 'class', '"w50   right"');
     $this->table_builder->add_col_attribute($colMap['action'], 'class', '"nowrap center"');
     // add styles for additional columns from plugins
     foreach ($this->_hooks as $hookObj) {
         $hookObj->defineColumnStyles($colMap, $this->table_builder);
     }
     $this->table_builder->add_attribute('class', 'xTable');
     $clone_icon = __('Edit');
     $row++;
     $page_total = array('ads' => 0, 'sites_channels' => 0, 'spent' => 0, 'impressions' => 0, 'clicks' => 0);
     // register additional per page statistic fields
     foreach ($this->_hooks as $hookObj) {
         $page_total = $hookObj->registerPerPageStatisticFields($page_total);
     }
     foreach ($groups as $id_group => $group) {
         // calculate per page statistic
         $page_total['ads'] += $group['ads'];
         $page_total['sites_channels'] += $group['site_channels'];
         $page_total['spent'] += $group['spent'];
         $page_total['impressions'] += $group['impressions'];
         $page_total['clicks'] += $group['clicks'];
         // calculate per page statistic for additional columns from plugins
         foreach ($this->_hooks as $hookObj) {
             $page_total = $hookObj->calculatePerPageStatistic($page_total, $group);
         }
         $code = type_to_str($id_group, 'textcode');
         // checkbox
         $this->table_builder->set_cell_content($row, $colMap['chkbox'], array('name' => 'id_groups[]', 'value' => $code, 'extra' => "id=chk{$row} onclick=\"checktr('chk{$row}','tr{$row}')\""), 'checkbox');
         // id
         $this->table_builder->set_cell_content($row, $colMap['id'], $id_group);
         // name
         $this->table_builder->set_cell_content($row, $colMap['name'], array('name' => limit_str_and_hint($group['name'], 30), 'href' => "#select_group", 'extra' => "jframe='no' onclick='return top.show_ads(\"{$code}\",\"\");'"), 'link');
         // status
         $this->table_builder->set_cell_content($row, $colMap['status'], __('grp_' . $group['status']));
         // ads
         $this->table_builder->set_cell_content($row, $colMap['ads'], array('name' => type_to_str($group['ads'], 'integer'), 'href' => "#select_ads", 'extra' => "jframe='no' onclick='return top.show_ads(\"{$code}\", \"ads\");'"), 'link');
         // site/channels
         $this->table_builder->set_cell_content($row, $colMap['siteChannels'], array('name' => type_to_str($group['site_channels'], 'integer'), 'href' => "#select_sitechannels", 'extra' => "jframe='no' onclick='return top.show_ads(\"{$code}\", \"channels\");'"), 'link');
         // spent
         $this->table_builder->set_cell_content($row, $colMap['spent'], type_to_str($group['spent'], 'money'));
         // impressions
         $this->table_builder->set_cell_content($row, $colMap['impressions'], type_to_str($group['impressions'], 'integer'));
         // clicks
         $this->table_builder->set_cell_content($row, $colMap['clicks'], type_to_str($group['clicks'], 'integer'));
         // ctr
         $this->table_builder->set_cell_content($row, $colMap['ctr'], type_to_str($group['ctr'], 'procent'));
         // action
         $this->table_builder->set_cell_content($row, $colMap['action'], array('name' => $clone_icon, 'href' => "#edit_group", 'extra' => "jframe='no' class='guibutton floatl ico ico-edit' value='{$clone_icon}' title='{$clone_icon}' onclick='top.editGroup(\"{$code_campaign}\",\"{$code}\");'"), 'link');
         // render additional columns from plugins
         foreach ($this->_hooks as $hookObj) {
             $hookObj->renderRow($row, $colMap, $group, $this->table_builder);
         }
         // add id attribute to the table row
         $this->table_builder->add_row_attribute($row, 'id', "tr{$row}");
         $row++;
     }
     if (0 == count($groups)) {
         $this->table_builder->insert_empty_cells = false;
         $this->table_builder->set_cell_content($row, 0, '&nbsp;&nbsp;' . __('Records not found'));
         $this->table_builder->cell($row, 0)->add_attribute('class', 'nodata');
         $this->table_builder->cell($row, 0)->add_attribute('colspan', count($colMap));
     } else {
         // render per page statistic row
         $this->table_builder->set_cell_content($row, $colMap['name'], __("Page total"));
         $this->table_builder->set_cell_content($row, $colMap['ads'], type_to_str($page_total['ads'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['siteChannels'], type_to_str($page_total['sites_channels'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['spent'], type_to_str($page_total['spent'], 'money'));
         $this->table_builder->set_cell_content($row, $colMap['impressions'], type_to_str($page_total['impressions'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['clicks'], type_to_str($page_total['clicks'], 'integer'));
         $ctr = $page_total['impressions'] ? $page_total['clicks'] / $page_total['impressions'] * 100 : 0;
         $this->table_builder->set_cell_content($row, $colMap['ctr'], type_to_str($ctr, 'procent'));
         $this->table_builder->clear_row_attributes($row);
         $this->table_builder->add_row_attribute($row, 'class', 'pagetotal');
         // render per page statistic for additional columns from plugins
         foreach ($this->_hooks as $hookObj) {
             $hookObj->renderPageStatisticRow($row, $colMap, $page_total, $this->table_builder);
         }
         // render summary statistic row
         $row++;
         $this->table_builder->set_cell_content($row, $colMap['name'], __("Total"));
         $this->table_builder->set_cell_content($row, $colMap['ads'], type_to_str($total['ads'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['siteChannels'], type_to_str($total['site_channels'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['spent'], type_to_str($total['spent'], 'money'));
         $this->table_builder->set_cell_content($row, $colMap['impressions'], type_to_str($total['impressions'], 'integer'));
         $this->table_builder->set_cell_content($row, $colMap['clicks'], type_to_str($total['clicks'], 'integer'));
         $ctr = $total['impressions'] ? $total['clicks'] / $total['impressions'] * 100 : 0;
         $this->table_builder->set_cell_content($row, $colMap['ctr'], type_to_str($ctr, 'procent'));
         $this->table_builder->clear_row_attributes($row);
         $this->table_builder->add_row_attribute($row, 'class', 'alltotal');
         // render summary statistic for additional columns from plugins
         foreach ($this->_hooks as $hookObj) {
             $hookObj->renderSummaryRow($row, $colMap, $total, $this->table_builder);
         }
     }
     // Устанавливаем возможность выбора колонок
     $this->table_builder->use_select_columns();
     $invariable_columns = array($colMap['id'], $colMap['name'], $colMap['action']);
     $this->table_builder->set_invariable_columns($invariable_columns);
     $html = str_replace('<%GROUPS%>', $this->table_builder->get_sort_html(), $html);
     $html = str_replace('<%PAGINATION%>', $this->pagination_post->create_form(), $html);
     $buttons = $this->load->view('advertiser/manage_ads/groups/buttons.html', '', TRUE);
     $buttons = str_replace('<%CAMPAIGN%>', $code_campaign, $buttons);
     $html = str_replace('<%BUTTONST%>', str_replace('<%ID%>', 'top_', $buttons), $html);
     $html = str_replace('<%BUTTONSB%>', str_replace('<%ID%>', 'bottom_', $buttons), $html);
     $html = str_replace('<%COLUMNS%>', $this->table_builder->get_columns_html(), $html);
     $this->_set_content($html);
     $this->_display();
 }
Exemple #19
0
 /**
  * работа с формой и вывод на экран результатов работы,
  * для получения/сохранения данных для полей формы
  * вызывает либо методы модели данных
  *  - load($id), create($fields), save($id, $fields),
  * либо, если модель не задана, методы вызывавшего класа
  *  - _load($id), _create($fields), _save($id, $fields),
  *
  * @param string $mode режим работы с формой
  *                       "create" - создание новой записи данных
  *                       "modify" - изменение существующей записи данных
  *                       "save"   - проверка и сохранение записи данных
  *                       "filter" - форма фильтрации, изменения объектов нет
  * @param array $form описание формы и ее полей
  *  $form = array(
  *     "name"         => "formname",                имя формы в HTML коде
  *     "id"           => "id_record",               переданный код записи данных, "" - новая запись
  *     "model"        => "account",                 модель для работы с данными формы, при отсутствии - используются методы _load и _save
  *     "view"         => "form_test",               отображение формы
  *     "vars"         => array ("tag" => "value"),  (опционально) массив с переменными для отображения
  *     "redirect"     => "controller",              если задан, то при успехе вызывается контроллер, если не задан - success_view
  *     "success_view" => "form_test_success",       отображение при успешном изменении данных (если не задан redirect)
  *     "no_errors"    => "true",                    (опционально) не выводить текст ошибки под неправильными полями
  *     "action"       => 'http://site.com/page.php' (опционально) перебивает сгенерированный action на заданный
  *     "fields"       => array(                     описание полей формы
  *        "field_name" => array(                    имя поля
  *           "id_field_type"    => "string",        тип данных поля (string, int, money, procent, date, time, date_time, float, bool)
  *           "form_field_type"  => "textarea",      тип HTML поля (text, password, hidden, file, textarea, checkbox, radio, select)
  *           "validation_rules" => "required",      (опционально) правила проверки поля (required, matches, min_length, max_length, exact_length, alpha, alpha_numeric, alpha_dash, numeric, integer, valid_email, valid_ip, valid_base64)
  *           "options" => array(                    (опционально) либо модель списка, либо массив со значениями элементов списка
  *              "value" => "text",                  (только для массива) список значений и строк
  *              ...
  *           ),
  *           "params" => array(                     (только для модели, опционально) список параметров для извлечения списка моделью
  *              "name" => "value",                  (для параметров) список имен параметров и значений
  *              ...
  *           ),
  *           "default"          => "default",       (опционально) значение поля по умолчанию,
  *                                                  если NULL данные при чтении формы не обновляются
  *           "max"    => 32                         (опционально для text) максимальная длина вводимой строки
  *        ),
  *        ...
  *     ),
  *     "kill"         => array(                     список удаляемых блоков в HTML коде
  *        "id_div", ...                             параметр id блока div, который необходимо удалить
  *     )
  *  );
  * @param array $input массив с входными параметрами контроллера
  * @param object $caller объект контроллера, вызвавшего данную модель
  * @return ничего не возвращвет
  */
 public function show_form($mode, &$form, $input, $caller)
 {
     $id = array_key_exists("id", $form) ? $form["id"] : "";
     if ($input->post("form_mode")) {
         $old_mode = $mode;
         $mode = $input->post("form_mode");
     }
     $active_form = '';
     if ($input->post('active_form')) {
         $active_form = $input->post('active_form');
     }
     $CI =& get_instance();
     $CI->load->library("Form_Setter");
     $error = "";
     $field_errors = array();
     $fields = array();
     $rules = array();
     if ("save" == $mode && $active_form == $form['name']) {
         foreach ($form["fields"] as $fname => $field) {
             //$fields[$fname] = isset($fields[$fname]) ? $fields[$fname].', ' : '';
             if (array_key_exists('id_field_type', $form["fields"][$fname])) {
                 $fields[$fname] = type_cast($input->post($fname), $form["fields"][$fname]["id_field_type"]);
             } else {
                 $fields[$fname] = $input->post($fname);
             }
             $form["fields"][$fname]["default"] = $input->post($fname);
             /**
              * Всё те же dirty hacks для datepickera
              * @author Semerenko
              */
             /*         
                         if(in_array($fname,array('from','to'))){
              
                            $form['fields'][$fname]['default'] = date('m.d.Y', type_cast($form["fields"][$fname]["default"],'date'));
                                     
                         }*/
             if (array_key_exists("validation_rules", $field)) {
                 $rules_arr = explode('|', $field["validation_rules"]);
                 foreach ($rules_arr as &$rules_arr_val) {
                     switch ($rules_arr_val) {
                         case "date":
                             $rules_arr_val = "callback_check_date";
                             break;
                         case "datetime":
                             $rules_arr_val = "callback_check_datetime";
                             break;
                         case "hostname":
                             $rules_arr_val = "callback_check_hostname";
                             break;
                         case "url":
                             $rules_arr_val = "callback_check_url";
                             break;
                         case "float":
                             $rules_arr_val = "callback_check_float";
                             break;
                         case "positive":
                             $rules_arr_val = "callback_check_positive";
                             break;
                         case "non_negative":
                             $rules_arr_val = "callback_check_non_negative";
                             break;
                         case "int":
                         case "integer":
                             $rules_arr_val = "callback_check_integer";
                             break;
                         case "ip":
                             $rules_arr_val = "callback_check_ip";
                             break;
                         case "ip_part":
                             $rules_arr_val = "callback_check_ip_part";
                             break;
                         case "ip_re":
                             $rules_arr_val = "callback_check_ip_re";
                             break;
                         default:
                             if (0 === strpos($rules_arr_val, 'min_val') || 0 === strpos($rules_arr_val, 'max_val') || 0 === strpos($rules_arr_val, 'interval') || 0 === strpos($rules_arr_val, 'float') || 0 === strpos($rules_arr_val, 'full_url')) {
                                 $rules_arr_val = "callback_check_" . $rules_arr_val;
                             }
                     }
                     $rules_arr_val = str_replace('md5', 'callback_check_password', $rules_arr_val);
                 }
                 $rules[$fname] = implode('|', $rules_arr);
             }
         }
         $CI->load->library('validation');
         $CI->validation->set_rules($rules);
         $int_validator = count($rules) == 0 || $CI->validation->run();
         $ext_validator = TRUE;
         if (method_exists($caller, '_validator')) {
             $ext_validator = $caller->_validator($fields, $int_validator);
         }
         if ($ext_validator && $int_validator) {
             $error = '';
             if ("save" == $mode) {
                 if (array_key_exists("model", $form)) {
                     $CI->load->model($form["model"]);
                     if ("" == $id) {
                         $error = $CI->{$form}["model"]->create($fields);
                     } else {
                         $error = $CI->{$form}["model"]->save($id, $fields);
                     }
                 } else {
                     if ("" == $id) {
                         $error = $caller->_create($fields);
                     } else {
                         $error = $caller->_save($id, $fields);
                     }
                 }
             }
             if ("" == $error) {
                 if (array_key_exists("redirect", $form)) {
                     redirect($form["redirect"]);
                 } else {
                     $CI->load->view($form["success_view"]);
                     return;
                 }
             }
         } else {
             foreach ($form["fields"] as $fname => $field) {
                 if (isset($CI->validation->{$fname . "_error"})) {
                     if ($CI->validation->{$fname . "_error"} != "") {
                         $field_errors[$fname] = $CI->validation->{$fname . "_error"};
                     }
                 }
             }
             $error = "You must fill all required fields!";
             //$CI->validation->error_string;
             // call form validation error callback:
             if (method_exists($caller, '_validationFailed')) {
                 $caller->_validationFailed($fields, $field_errors);
             }
         }
     }
     if ("modify" == $mode || 'save' == $mode && $active_form != $form['name'] && $old_mode == "modify") {
         if (array_key_exists("model", $form)) {
             $CI->load->model($form["model"]);
             $fields = $CI->{$form}["model"]->load($id);
         } else {
             $fields = $caller->_load($id);
         }
         foreach ($form["fields"] as $fname => $field) {
             if (array_key_exists($fname, $fields)) {
                 if (array_key_exists("default", $form["fields"][$fname]) && is_null($form["fields"][$fname]["default"])) {
                     $form["fields"][$fname]["default"] = "";
                 } else {
                     $form["fields"][$fname]["default"] = type_to_str($fields[$fname], $form["fields"][$fname]["id_field_type"]);
                     /**
                      * Для дэйтпикера dirty hack
                      * Если это поля to & from, то их не нужно форматировать
                      * @author Semerenko
                      */
                     /*
                     if(in_array($fname,array('to','from')) && $form["fields"][$fname]["id_field_type"] == 'date'){
                        // ничего не делать. А всё форматирование пусть будет в else.
                     }else{
                        $form["fields"][$fname]["default"] =
                           type_to_str($fields[$fname], $form["fields"][$fname]["id_field_type"]);
                     }
                     */
                 }
             }
         }
     }
     if (array_key_exists('vars', $form)) {
         $CI->form_setter->set_html($CI->parser->parse($form["view"], $form['vars'], TRUE));
     } else {
         $CI->form_setter->set_html($CI->load->view($form["view"], '', TRUE));
     }
     $CI->form_setter->use_form($form["name"]);
     if (isset($form['action'])) {
         $CI->form_setter->set_action($form['action']);
     } else {
         $CI->form_setter->set_action($CI->config->site_url($CI->uri->uri_string()));
     }
     foreach ($form["fields"] as $fname => $field) {
         switch ($field["form_field_type"]) {
             case "text":
             case "textarea":
             case "password":
             case "file":
             case "hidden":
                 $text = "";
                 if (array_key_exists("default", $field)) {
                     $text = $field["default"];
                 }
                 $max = isset($field['max']) ? $field['max'] : NULL;
                 $CI->form_setter->set_text($fname, $text, $max);
                 break;
             case "checkbox":
             case "radio":
                 if (array_key_exists("default", $field)) {
                     $value = $field["default"];
                     if ("" != $value) {
                         $CI->form_setter->set_state($fname, $value, TRUE);
                     }
                 }
                 break;
             case "select":
                 if (is_array($field["options"])) {
                     $options = $field["options"];
                 } else {
                     $options_model = $field["options"];
                     $CI->load->model($options_model, 'form_temp_model', TRUE);
                     $params = array();
                     if (array_key_exists("params", $field)) {
                         $params = $field["params"];
                     }
                     $options = $CI->form_temp_model->get_list($params);
                     $CI->load->unload_model('form_temp_model');
                 }
                 $default = array_key_exists("default", $field) ? $field["default"] : NULL;
                 $CI->form_setter->set_options($fname, $options, $default);
                 break;
         }
     }
     if ("" != $id) {
         $CI->form_setter->add_hidden("id", $id);
     }
     if ($mode != "filter") {
         $CI->form_setter->add_hidden("form_mode", "save");
         $CI->form_setter->add_hidden("active_form", $form['name']);
     }
     $CI->form_setter->set_error(__($error));
     foreach ($field_errors as $fname => $ferror) {
         $matches = NULL;
         preg_match_all('/{@([\\S]*?)@}/', $ferror, $matches);
         foreach ($matches[1] as $sfname) {
             if (array_key_exists($sfname, $form["fields"])) {
                 if (array_key_exists("display_name", $form["fields"][$sfname])) {
                     $ferror = str_replace("{@{$sfname}@}", "'" . __($form["fields"][$sfname]["display_name"]) . "'", $ferror);
                 }
                 if (array_key_exists('no_errors', $form)) {
                     $ferror = '';
                 }
             }
         }
         $CI->form_setter->set_field_error($fname, $ferror);
     }
     if (array_key_exists("kill", $form)) {
         $CI->form_setter->kill_blocks($form["kill"]);
     }
     $CI->output->set_output($CI->form_setter->get_html());
 }
 /**
  * Отображение сообщения об успешном редактировании новости
  *
  */
 public function edit_complete($site_code = NULL)
 {
     $site_channels_list = NULL;
     if (!is_null($site_code)) {
         $this->load->model('channel');
         $id_site = type_cast($site_code, 'textcode');
         $site_channels_list = $this->channel->get_sites_channels(array('fields' => 'channels.id_channel', 'site_id_filter' => $id_site, 'show_deleted_channels' => false, 'disable_site_ordering' => true));
     }
     if (is_null($site_channels_list)) {
         $redirect_url = $this->site_url . $this->index_page . $this->role . '/manage_sites_channels';
     } else {
         $redirect_url = $this->site_url . $this->index_page . $this->role . '/edit_site_channel_layout/index/' . $id_site;
     }
     $data = array('MESSAGE' => __('Site was edited successfully'), 'REDIRECT' => $redirect_url);
     $content = $this->parser->parse('common/infobox.html', $data, FALSE);
     $this->_set_content($content);
     $this->_display();
 }
 public function _create($fields)
 {
     $this->load->model('groups', '', TRUE);
     $default_bid = $this->campaign_type == 'cpc' ? type_to_str($this->global_variables->get('DefaultTextBid', 0, '0.01'), 'float') : 0;
     $default_bid_image = $this->campaign_type == 'cpc' ? type_to_str($this->global_variables->get('DefaultImageBid', 0, '0.01'), 'float') : 0;
     $id_group = $this->groups->add(type_cast($fields['campaign'], 'textcode'), $fields['group_name'], $default_bid, $default_bid_image);
     if ($this->campaign_type == 'cpc') {
         if ($fields['budget'] != '') {
             $this->groups->set_daily_budget($id_group, $fields['budget']);
         }
     }
 }
 public function get_channel_details()
 {
     $channel_code = $this->input->post('channel_code');
     $site_code = $this->input->post('site_code');
     $error_flag = false;
     $error_message = '';
     if (!$channel_code || !$site_code) {
         $error_flag = true;
         $error_message = __('Site or Channel code is not specified');
     }
     if (!$error_flag) {
         $plugin_work = $this->plugins->run('get_channel_details', array($this, $channel_code, type_cast($site_code, 'textcode')));
         if (in_array(true, $plugin_work)) {
             return;
         }
         $this->load->model('channel');
         $this->load->model('site');
         $id_site = type_cast($site_code, 'textcode');
         $id_channel = type_cast($channel_code, 'textcode');
         $channel_info = $this->channel->get_info($id_channel);
         $site_info = $this->site->get_info($id_site);
         $this->load->model('sites_channels');
         $id_site_channel = $this->sites_channels->get_id_site_channel($id_site, $id_channel);
         if (!is_null($id_site_channel)) {
             $slot_info = $this->sites_channels->get_slot_info($id_site_channel->id_site_channel);
             $buyed_flat_rate = $slot_info['free'] == 0 || $slot_info['type'] == 'image' && $slot_info['free'] != $slot_info['max'];
         } else {
             $buyed_flat_rate = false;
         }
         if (is_null($channel_info)) {
             $error_flag = true;
             $error_message = __('Channel is not found');
         }
         if (is_null($site_info)) {
             $error_flag = true;
             $error_message = __('Site is not found');
         }
     }
     if ($error_flag) {
         echo json_encode(array('error_flag' => true, 'error_message' => $error_message));
         return;
     }
     $result = array('error_flag' => false);
     $supported_cost_models = array();
     $this->load->model('channel_program');
     $channel_program_types = $this->channel_program->get_channel_program_types($id_channel);
     $price_list = $this->channel_program->get_list(array('fields' => 'program_type,title,id_program,volume,cost_text,cost_image', 'id_channel' => $id_channel, 'order_bye' => 'volume'));
     foreach ($channel_program_types as $program_type) {
         $supported_cost_models[] = __($program_type);
     }
     $allowedTypes = explode(',', $channel_info->ad_type);
     $allowedTypesLabels = array();
     $max_ad_slots = 1;
     if (in_array(Sppc_Channel::AD_TYPE_TEXT, $allowedTypes)) {
         $allowedTypesLabels[] = __('Text');
         $max_ad_slots = $channel_info->max_ad_slots;
     }
     if (in_array(Sppc_Channel::AD_TYPE_IMAGE, $allowedTypes)) {
         $allowedTypesLabels[] = __('Image');
     }
     $channel_ad_type_text = implode(', ', $allowedTypesLabels);
     $channel_data = array('name' => $channel_info->name, 'type' => $channel_ad_type_text, 'format' => $channel_info->width . '&times;' . $channel_info->height, 'slots' => $max_ad_slots, 'cost_models' => implode(', ', $supported_cost_models), 'id_dimension' => $channel_info->id_dimension, 'buyed_flat_rate' => $buyed_flat_rate, 'prices' => array());
     if (!is_null($price_list)) {
         foreach ($price_list as $price) {
             $channel_data['prices'][$price['program_type']][$price['id_program']]['id_program'] = type_to_str($price['id_program'], 'textcode');
             $channel_data['prices'][$price['program_type']][$price['id_program']]['title'] = type_to_str($price['title'], 'encode');
             $channel_data['prices'][$price['program_type']][$price['id_program']]['volume'] = type_to_str($price['volume'], 'integer');
             $channel_data['prices'][$price['program_type']][$price['id_program']]['cost_text'] = type_to_str($price['cost_text'], 'money');
             $channel_data['prices'][$price['program_type']][$price['id_program']]['cost_image'] = $price['cost_image'] ? type_to_str($price['cost_image'], 'money') : '-';
         }
     }
     if (in_array(__('CPC'), $supported_cost_models)) {
         $channel_data['prices']['CPC']['id_program'] = type_to_str(0, 'textcode');
         $text_bid = $this->site->get_min_bid($id_site, 'text');
         $channel_data['prices']['CPC']['cost_text'] = $text_bid ? type_to_str($text_bid, 'money') : '-';
         $image_bid = $this->site->get_min_bid($id_site, 'image');
         $channel_data['prices']['CPC']['cost_image'] = $image_bid ? type_to_str($image_bid, 'money') : '-';
     }
     $result = array('error_flag' => false, 'channel' => $channel_data);
     echo json_encode($result);
 }
 public function add_site_channel_to_existing_campaign($site_code, $channel_code, $campaign_type, $program_type = null)
 {
     $reply = array('error_flag' => true, 'error_message' => __('Unknown error'));
     $group_code = $this->input->post('group_code');
     $result = $this->sites_channels->check_group_site_channel(type_cast($site_code, 'textcode'), type_cast($channel_code, 'textcode'), type_cast($group_code, 'textcode'));
     if ($result == true || $campaign_type == 'cpc') {
         switch ($campaign_type) {
             case 'cpm_flatrate':
                 $reply['redirect'] = $this->site_url . $this->index_page . 'advertiser/edit_channels/index/' . $group_code . '/' . $program_type;
                 $reply['error_flag'] = false;
                 break;
         }
         if (!$reply['error_flag']) {
             $this->session->set_userdata('add_site_channel', json_encode(array('site_code' => $site_code, 'channel_code' => $channel_code, 'program_type' => $campaign_type, 'program' => $program_type)));
         }
     } elseif ($result == false) {
         $reply = array('error_flag' => true, 'error_message' => __('This site and channel is added to group'));
     }
     echo json_encode($reply);
 }
Exemple #24
0
 /**
  * осуществление выплаты 
  * 
  * @param array $fields массив с полями формы
  * @return ничего не возвращает
  */
 public function withdraw($fields)
 {
     $CI =& get_instance();
     $CI->load->model('payment_gateways', '', TRUE);
     $CI->load->model('payment_requests', '', TRUE);
     $CI->load->model('entity', '', TRUE);
     $data = $CI->payment_gateways->data('paypal');
     $payment_request = $CI->payment_requests->get($fields['id_request']);
     // Деньги для вывода из системы
     $value = type_cast($fields['payout'], 'float') * (1 - $data->withdraw_comm / 100);
     // Общая сумма
     $amount = number_format(type_cast((string) $fields['charge'], 'float'), 2, '.', '');
     $sitename = $CI->global_variables->get('SiteName');
     $time = time();
     $email_from = $data->account_id_1;
     $email_to = $CI->entity->get_name_and_mail($payment_request->id_entity)->e_mail;
     $site_url = $CI->get_siteurl();
     $this->payment_requests->update($fields['id_request'], $fields['payout'], $fields['charge']);
     $trans_id = $this->save_transaction($email_from, $time, $amount, $value, $fields['id_request']);
     $data = array('AMOUNT' => $amount, 'EMAIL' => $email_to, 'ITEMNAME' => $sitename . ': Withdraw for ' . $email_to . ' ($' . type_to_str($amount, 'float') . ')', 'TIME' => $time, 'RETURN' => $site_url . 'admin/pay_to_publishers', 'CANCEL' => $site_url . 'admin/pay_to_publishers', 'NOTIFY' => $site_url . 'common/paypal_notify/withdraw', 'TRANSID' => $trans_id);
     echo $this->parser->parse('common/payments/paypal.html', $data, TRUE);
     exit;
 }
 /**
  * Получение таблицы сайтов по указанным критериям
  *
  */
 public function sites_table()
 {
     $this->load->model('channel_program');
     $filter_mode = $this->input->post('filter_mode');
     $this->load->helper('periods_helper');
     $this->table_builder->clear();
     $this->table_builder->init_sort_vars('iframe_channels', 'channel_name', 'asc');
     $this->table_builder->sorted_column(0, 'channel_name', "Channel Name", 'asc');
     $this->table_builder->sorted_column(1, 'id_dimension', 'Format', 'asc');
     $this->table_builder->set_cell_content(0, 2, __('Cost Model'));
     $this->table_builder->sorted_column(3, 'min_cpm_volume', __('Minimal CPM Package (Impressions)'), 'asc');
     $this->table_builder->sorted_column(4, 'min_cpm_cost_text', __('CPM Cost (Text Ads)'), 'asc');
     $this->table_builder->sorted_column(6, 'min_cpm_cost_image', __('CPM Cost (Text & Image)'), 'asc');
     $this->table_builder->sorted_column(8, 'min_flat_rate_volume', __('Minimal Flat Rate Package (Days)'), 'asc');
     $this->table_builder->sorted_column(9, 'min_flat_rate_cost_text', __('Flat Rate Cost (Text Ads)'), 'asc');
     $this->table_builder->sorted_column(11, 'min_flat_rate_cost_image', __('Flat Rate Cost (Text & Image)'), 'asc');
     $this->table_builder->sorted_column(13, 'impressions', 'Traffic Volume', 'asc');
     $this->table_builder->set_cell_content(0, 14, __('Action'));
     $this->table_builder->cell(0, 2)->add_attribute('class', 'simpleTitle');
     $this->table_builder->cell(0, 14)->add_attribute('class', 'simpleTitle');
     $this->table_builder->add_col_attribute(0, 'class', '');
     $this->table_builder->add_col_attribute(1, 'class', 'w80 center');
     $this->table_builder->add_col_attribute(2, 'class', 'w80 center');
     $this->table_builder->add_col_attribute(3, 'class', 'center');
     $this->table_builder->add_col_attribute(4, 'class', 'center');
     $this->table_builder->add_col_attribute(6, 'class', 'center');
     $this->table_builder->add_col_attribute(8, 'class', 'center');
     $this->table_builder->add_col_attribute(9, 'class', 'center');
     $this->table_builder->add_col_attribute(11, 'class', 'center');
     $this->table_builder->add_col_attribute(13, 'class', 'center');
     $this->table_builder->add_col_attribute(14, 'class', 'center');
     $this->table_builder->add_row_attribute(0, 'class', 'th f9px');
     $form_data = array("name" => "iframe_channels_form", "view" => "admin/adplacing/manage_sites_channels/choose_channels/iframe_channels_table.html", 'fields' => array('filter_mode' => array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $filter_mode)));
     switch ($filter_mode) {
         case 'by_category':
             $id_category = $this->input->post('id_category');
             if ($id_category) {
                 $form_data['fields']['id_category'] = array('id_field_type' => 'int', 'form_field_type' => 'hidden', 'default' => $id_category);
                 $channels_array = $this->channel->get_sites_channels(array('fields' => 'id_site_channel, channels.ad_type, channels.name as channel_name,' . ' sites.url as site_url, sites.id_site,' . ' channels.id_channel, channels.id_dimension, dimensions.width,' . ' dimensions.height, SUM(impressions) as impressions', 'category_id_filter' => $id_category, 'show_deleted_channels' => false, 'order_by' => $this->table_builder->sort_field, 'order_direction' => $this->table_builder->sort_direction, 'hide_wo_programs' => true, 'date_filter' => data_range(array('mode' => 'select', 'period' => 'lastmonth')), 'status' => 'active'));
             } else {
                 $channels_array = array();
             }
             break;
         case 'by_price':
             $price = $this->input->post('price');
             if ($price) {
                 $price = type_cast($price, 'float');
             } else {
                 $price = 0;
             }
             $price_program = $this->input->post('price_program');
             $ads_type = $this->input->post('ads_type');
             if ($price && $price_program) {
                 $form_data['fields']['price'] = array('id_field_type' => 'positive_float', 'form_field_type' => 'hidden', 'default' => type_to_str($price, 'float'));
                 $form_data['fields']['price_program'] = array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $price_program);
                 $form_data['fields']['ads_type'] = array('id_field_type' => 'string', 'form_field_type' => 'hidden', 'default' => $ads_type);
                 $channels_array = $this->channel->get_sites_channels(array('fields' => 'id_site_channel, channels.ad_type, channels.name as channel_name, ' . 'sites.url as site_url, sites.id_site, channels.id_channel, ' . 'channels.id_dimension, dimensions.width, dimensions.height, ' . 'SUM(impressions) as impressions', 'show_deleted_channels' => false, 'order_by' => $this->table_builder->sort_field, 'order_direction' => $this->table_builder->sort_direction, 'price_filter' => array('price' => $price, 'price_program' => $price_program, 'ads_type' => $ads_type), 'hide_wo_programs' => true, 'date_filter' => data_range(array('mode' => 'select', 'period' => 'lastmonth'))));
             } else {
                 $channels_array = array();
             }
             break;
     }
     //установка атрибутов таблицы
     $this->table_builder->add_attribute('class', 'xTable');
     //or set style here
     if (is_null($channels_array)) {
         $channels_array = array();
     }
     $data_rows_conut = sizeof($channels_array);
     $this->table_builder->insert_empty_cells = false;
     $row_counter = 1;
     $site_id = '';
     for ($i = 0; $i < $data_rows_conut; $i++) {
         if (!$this->channel_program->get_default_program(array('id_site_channel' => $channels_array[$i]['id_site_channel']))) {
             continue;
         }
         if ($site_id != $channels_array[$i]['id_site']) {
             $this->table_builder->set_cell_content($row_counter, 0, array('src' => $this->site_url . 'images/pixel.gif', 'onclick' => 'top.SwitchExpander(' . $channels_array[$i]['id_site'] . ',this)', 'extra' => 'class="minus"'), 'image');
             $this->table_builder->cell($row_counter, 0)->add_content(__('Site') . ':&nbsp<span class="green i">&bdquo;' . $channels_array[$i]['site_url'] . '&ldquo;</span>');
             $this->table_builder->cell($row_counter, 0)->add_attribute('colspan', 15);
             $this->table_builder->add_row_attribute($row_counter, 'class', 'group');
             $site_id = $channels_array[$i]['id_site'];
             $row_counter++;
         }
         $this->table_builder->set_cell_content($row_counter, 0, type_to_str($channels_array[$i]['channel_name'], 'encode'));
         $allowedTypes = explode(',', $channels_array[$i]['ad_type']);
         $this->table_builder->set_cell_content($row_counter, 1, '');
         if (in_array(Sppc_Channel::AD_TYPE_TEXT, $allowedTypes)) {
             $ico_path = $this->site_url . 'images/smartppc6/icons/script_code.png';
             $hint_title = __('Text Ad') . ' (' . $channels_array[$i]['width'] . '&times;' . $channels_array[$i]['height'] . ')';
             $img_prefix = 'txt_';
             $this->table_builder->cell($row_counter, 1)->add_content(array('src' => $ico_path, 'extra' => 'title="' . $hint_title . '" href="' . $this->site_url . 'images/dimensions_preview/' . $img_prefix . $channels_array[$i]['id_dimension'] . '.png" class="tooltip"'), 'image');
         }
         if (in_array(Sppc_Channel::AD_TYPE_IMAGE, $allowedTypes)) {
             $ico_path = $this->site_url . 'images/smartppc6/icons/image.png';
             $hint_title = __('Image Ad') . ' (' . $channels_array[$i]['width'] . '&times;' . $channels_array[$i]['height'] . ')';
             $img_prefix = 'img_';
             $this->table_builder->cell($row_counter, 1)->add_content(array('src' => $ico_path, 'extra' => 'title="' . $hint_title . '" href="' . $this->site_url . 'images/dimensions_preview/' . $img_prefix . $channels_array[$i]['id_dimension'] . '.png" class="tooltip"'), 'image');
         }
         $this->table_builder->cell($row_counter, 1)->add_content($channels_array[$i]['width'] . '&times;' . $channels_array[$i]['height'], '', '<br/> ');
         $program_type = "";
         $min_volume_cpm = "";
         $min_volume_flat_rate = "";
         if (!is_null($channels_array[$i]['min_cpm_volume'])) {
             $program_type .= __('CPM');
             $this->table_builder->set_cell_content($row_counter, 3, type_to_str($channels_array[$i]['min_cpm_volume'], 'integer'));
             if (in_array(Sppc_Channel::AD_TYPE_TEXT, $allowedTypes)) {
                 $this->table_builder->set_cell_content($row_counter, 4, type_to_str($channels_array[$i]['min_cpm_cost_text'], 'money'));
             } else {
                 $this->table_builder->set_cell_content($row_counter, 4, '&#151;');
             }
             if (in_array(Sppc_Channel::AD_TYPE_IMAGE, $allowedTypes) && $channels_array[$i]['min_cpm_cost_image'] > 0) {
                 $this->table_builder->set_cell_content($row_counter, 6, type_to_str($channels_array[$i]['min_cpm_cost_image'], 'money'));
             } else {
                 $this->table_builder->set_cell_content($row_counter, 6, '&#151;');
             }
         } else {
             $program_type .= '&#151;';
             $this->table_builder->set_cell_content($row_counter, 3, '&#151;');
             $this->table_builder->set_cell_content($row_counter, 4, '&#151;');
             $this->table_builder->set_cell_content($row_counter, 6, '&#151;');
         }
         if (!is_null($channels_array[$i]['min_flat_rate_volume'])) {
             $program_type .= ' / ' . __('Flat Rate');
             $this->table_builder->set_cell_content($row_counter, 8, type_to_str($channels_array[$i]['min_flat_rate_volume'], 'integer'));
             if (in_array(Sppc_Channel::AD_TYPE_TEXT, $allowedTypes)) {
                 $this->table_builder->set_cell_content($row_counter, 9, type_to_str($channels_array[$i]['min_flat_rate_cost_text'], 'money'));
             } else {
                 $this->table_builder->set_cell_content($row_counter, 9, '&#151;');
             }
             if (in_array(Sppc_Channel::AD_TYPE_IMAGE, $allowedTypes) && $channels_array[$i]['min_flat_rate_cost_image'] > 0) {
                 $this->table_builder->set_cell_content($row_counter, 11, type_to_str($channels_array[$i]['min_flat_rate_cost_image'], 'money'));
             } else {
                 $this->table_builder->set_cell_content($row_counter, 11, '&#151;');
             }
         } else {
             $program_type .= ' / &#151;';
             $this->table_builder->set_cell_content($row_counter, 8, '&#151;');
             $this->table_builder->set_cell_content($row_counter, 9, '&#151;');
             $this->table_builder->set_cell_content($row_counter, 11, '&#151;');
         }
         $this->table_builder->set_cell_content($row_counter, 2, $program_type);
         $this->table_builder->set_cell_content($row_counter, 13, type_to_str($channels_array[$i]['impressions'], 'impressions'));
         $this->table_builder->set_cell_content($row_counter, 14, array('name' => __('Add'), 'href' => '#', 'extra' => 'value="{@Add@}" title="{@Add@}" class="guibutton floatl ico ico-plusgreen" jframe="no" onclick="return addSiteChannelToGroup(' . $channels_array[$i]['id_site_channel'] . ');"'), 'link');
         $this->table_builder->add_row_attribute($row_counter, 'id', "tr{$channels_array[$i]['id_site']}");
         $this->table_builder->add_row_attribute($row_counter, 'id_site_channel', $channels_array[$i]['id_site_channel']);
         $row_counter++;
     }
     if (0 == $data_rows_conut) {
         $this->table_builder->set_cell_content(1, 0, __('Records not found'));
         $this->table_builder->cell(1, 0)->add_attribute('colspan', 15);
         $this->table_builder->cell(1, 0)->add_attribute('class', 'nodata');
     }
     // Устанавливаем возможность выбора колонок
     $this->table_builder->use_select_columns();
     $invariable_columns = array(0, 1, 2, 14);
     $this->table_builder->set_invariable_columns($invariable_columns);
     $channels_table = $this->table_builder->get_sort_html();
     $this->template = "common/parent/jq_iframe.html";
     $form_content = $this->form->get_form_content('create', $form_data, $this->input, $this);
     $form_content = str_replace('<%CHANNELS_TABLE%>', $channels_table, $form_content);
     $form_content = str_replace('<%COLUMNS%>', $this->table_builder->get_columns_html(), $form_content);
     $this->_set_content($form_content);
     $this->_display();
 }
 /**
  * сохраняет настройки кампании
  *
  * @param string $id шифрованный код кампании 
  * @param array $fields массив с полями формы
  * @return string пустая строка - знак успешного сохранения настроек
  */
 public function _save($id, $fields)
 {
     //$targeting = json_decode($fields['targeting']);
     $id_campaign = type_cast($id, 'textcode');
     $this->campaigns->update($id_campaign, array('campaign_name' => $fields['campaign_name'], 'targeting_type' => $fields['targeting_type']));
     //$this->campaigns->set_countries_by_id($id_campaign, $targeting->countries);
     //$this->campaigns->set_languages_by_id($id_campaign, $targeting->languages);
     $this->load->model('targeting_groups');
     //копирование таргетинга из временной группы
     $this->targeting_groups->copy(type_cast($fields['id_targeting_group_temp'], 'textcode'), type_cast($fields['id_targeting_group'], 'textcode'));
     //удаление временной группы
     $this->targeting_groups->cancel($this->user_id, $this->role, type_cast($fields['id_targeting_group_temp'], 'textcode'));
     $schedule = json_decode($fields['schedule']);
     if ($schedule->schedule_is_set) {
         $this->campaigns->set_schedule($id_campaign, $this->schedule->set($schedule->schedule));
     } else {
         $this->campaigns->set_schedule($id_campaign, NULL);
     }
     $this->schedule->kill_unused();
     return '';
 }
 /**
  * проверка поля на число с плавающей точкой
  * вызывается валидатором
  *
  * @param string $str значение поля
  * @return bool истина, если поле успешно прошло проверку
  */
 function check_non_negative($str)
 {
     $CI =& get_instance();
     $str_val = type_cast($str, 'float');
     if (is_numeric($str_val) && $str_val >= 0) {
         return TRUE;
     } else {
         if (class_exists("CI_Validation")) {
             $CI->validation->set_message('check_non_negative', 'The %s field must contain a non-negative number.');
         }
         return FALSE;
     }
 }
 protected function sites_table($sitecode = null)
 {
     $this->load->library('Table_Builder');
     $this->table_builder->clear();
     $this->table_builder->insert_empty_cells = false;
     $this->table_builder->init_sort_vars('site_directory', 'name', 'asc');
     $this->load->model('pagination_post');
     $this->pagination_post->set_form_name('site_directory');
     $this->load->model('site');
     $this->pagination_post->set_total_records($this->site->directory_total($this->ad_type_filter, $this->image_size_filter, $this->cost_model_filter, $this->category_filter, $this->keyword_filter));
     $siteInfo = null;
     if (!is_null($sitecode)) {
         $this->load->helper('fields');
         $siteId = type_cast($sitecode, 'textcode');
         $siteInfo = $this->site->get_info($siteId);
         if (!is_null($siteInfo)) {
             $currentSitePosition = $this->site->directory_total($this->ad_type_filter, $this->image_size_filter, $this->cost_model_filter, $this->category_filter, $this->keyword_filter, $siteInfo->name);
         }
     }
     if (is_null($siteInfo)) {
         $this->pagination_post->read_variables('site_directory', 1, $this->global_variables->get('SiteDirectoryPerPage'));
         $records = $this->site->directory_select($this->temporary['site_directory_page'], $this->temporary['site_directory_per_page'], $this->table_builder->sort_field, $this->table_builder->sort_direction, $this->ad_type_filter, $this->image_size_filter, $this->cost_model_filter, $this->category_filter, $this->keyword_filter);
     } else {
         $sitesPerPage = $this->global_variables->get('SiteDirectoryPerPage');
         $currentPage = 1;
         if ($currentSitePosition > $sitesPerPage) {
             $currentPage = ceil($currentSitePosition / $sitesPerPage);
         }
         $this->pagination_post->read_variables('site_directory', $currentPage, $sitesPerPage, true);
         $records = $this->site->directory_select($currentPage, $sitesPerPage, $this->table_builder->sort_field, $this->table_builder->sort_direction, $this->ad_type_filter, $this->image_size_filter, $this->cost_model_filter, $this->category_filter, $this->keyword_filter);
     }
     $this->table_builder->sorted_column(0, "name", __("Site Description"), "asc");
     $this->table_builder->set_cell_content(0, 1, __("Channels"));
     $this->table_builder->set_cell_content(0, 2, __("Cost Models"));
     $this->table_builder->add_col_attribute(0, 'class', 'nohl cursor-hand');
     $this->table_builder->add_col_attribute(1, 'class', 'center w100');
     $this->table_builder->add_col_attribute(2, 'class', 'center w100');
     $this->table_builder->add_row_attribute(0, 'class', 'th');
     $this->table_builder->add_attribute('class', 'xTable w100p');
     $description_template = $this->parser->parse('common/site_directory/description.html', array('ROLE' => $this->role));
     $row = 1;
     foreach ($records as $id => $record) {
         $description = str_replace('<%NAME%>', limit_str_and_hint(type_to_str($record['name'], 'encode'), 20), $description_template);
         $description = str_replace('<%URL%>', $record['url'], $description);
         $description = str_replace('<%URLQANCAST%>', implode(".", array_reverse(explode(".", preg_replace('/^.*?\\.([a-zA-Z0-9-]+\\.[a-zA-Z0-9-]+)/si', '$1', $record['url'])))), $description);
         $site_code = type_to_str($id, 'textcode');
         $description = str_replace('<%CODESITE%>', $site_code, $description);
         $record['description'] = str_replace("\n", '<br>', type_to_str($record['description'], 'encode'));
         $description = str_replace('<%DESCRIPTION%>', $record['description'], $description);
         $description = str_replace('<%IMAGE%>', $this->site->get_thumb($id), $description);
         $this->table_builder->set_cell_content($row, 0, $description);
         $ch_count = 0;
         $f_row = $row;
         $ad_type = array();
         $cost_models = array();
         if (isset($record['channels'])) {
             foreach ($record['channels'] as $channel) {
                 $cost_mods = explode(',', $channel['cost_model']);
                 //$cost_models = array();
                 foreach ($cost_mods as $cost_model) {
                     if (trim($cost_model) != '') {
                         $cost_models[] = __(trim($cost_model));
                     }
                 }
                 $allowedAdTypes = explode(',', $channel['ad_type']);
                 if (in_array(Sppc_Channel::AD_TYPE_TEXT, $allowedAdTypes)) {
                     $ad_type[] = __('Text');
                 }
                 if (in_array(Sppc_Channel::AD_TYPE_IMAGE, $allowedAdTypes)) {
                     $ad_type[] = __('Image');
                 }
             }
         }
         if ($ch_count == 0) {
             $this->table_builder->set_cell_content($row, 1, implode(', ', array_unique($ad_type)));
             $this->table_builder->set_cell_content($row, 2, implode(', ', array_unique($cost_models)));
         }
         $row++;
         $this->table_builder->set_cell_content($row, 0, "<a name='{$site_code}'></a><div id='{$site_code}' class='site_info'></div>");
         $this->table_builder->cell($row, 0)->add_attribute('colspan', 3);
         $this->table_builder->cell($row, 0)->add_attribute('style', 'padding-top: 0px; padding-bottom: 0px; height: 0px;');
         $row++;
     }
     if (0 == count($records)) {
         $this->table_builder->insert_empty_cells = false;
         $this->table_builder->set_cell_content(1, 0, __('Records not found'));
         $this->table_builder->cell(1, 0)->add_attribute('colspan', 3);
         $this->table_builder->cell(1, 0)->add_attribute('class', 'nodata');
     }
     return array('TABLE' => $this->table_builder->get_sort_html(), 'PAGINATION' => $this->pagination_post->create_form());
 }
 public function _load($id)
 {
     $this->load->model('ads', '', TRUE);
     $fields = $this->ads->get(type_cast($id, 'textcode'));
     if ($fields['ad_type'] == 'richmedia') {
         $fields['format'] = $fields['id_dimension'];
     }
     if (array_key_exists('id_dimension', $fields)) {
         $this->load->model('dimension');
         $dim_info = $this->dimension->get_info($fields['id_dimension']);
         $fields['img_w'] = $dim_info->width;
         $fields['img_h'] = $dim_info->height;
     }
     return $fields;
 }
 public function _save($id, $fields)
 {
     $this->new_campaign->init_storage($this->id_xml);
     $schedule = json_decode($fields['schedule']);
     if (is_null($schedule)) {
         return 'Schedule decoding failed';
     }
     $this->new_campaign->set_targeting(type_cast($fields['id_targeting_group'], 'textcode'));
     $this->new_campaign->set_targeting(type_cast($fields['id_targeting_group_temp'], 'textcode'), true);
     $this->targeting_groups->copy(type_cast($fields['id_targeting_group_temp'], 'textcode'), type_cast($fields['id_targeting_group'], 'textcode'));
     $this->new_campaign->set_targeting_type($fields['targeting_type']);
     $this->new_campaign->set_schedule($schedule);
     $this->new_campaign->set_name_date(array('name' => $fields['campaign_name']));
     $this->new_campaign->save_data();
 }