Ejemplo n.º 1
0
 public static function GetList($aSort = array(), $arFilter = array())
 {
     $err_mess = CFavorites::err_mess() . "<br>Function: GetList<br>Line: ";
     global $DB, $USER;
     $arSqlSearch = array();
     $strSqlSearch = "";
     if (is_array($arFilter)) {
         foreach ($arFilter as $key => $val) {
             if (strlen($val) <= 0 || $val == "NOT_REF") {
                 continue;
             }
             switch (strtoupper($key)) {
                 case "ID":
                     $arSqlSearch[] = GetFilterQuery("F.ID", $val, "N");
                     break;
                 case "USER_ID":
                     $arSqlSearch[] = "F.USER_ID = " . intval($val);
                     break;
                 case "MENU_FOR_USER":
                     $arSqlSearch[] = "(F.USER_ID=" . intval($val) . " OR F.COMMON='Y')";
                     break;
                 case "COMMON":
                     $arSqlSearch[] = "F.COMMON = '" . $DB->ForSql($val, 1) . "'";
                     break;
                 case "LANGUAGE_ID":
                     $arSqlSearch[] = "F.LANGUAGE_ID = '" . $DB->ForSql($val, 2) . "'";
                     break;
                 case "DATE1":
                     $arSqlSearch[] = "F.TIMESTAMP_X >= FROM_UNIXTIME('" . MkDateTime(FmtDate($val, "D.M.Y"), "d.m.Y") . "')";
                     break;
                 case "DATE2":
                     $arSqlSearch[] = "F.TIMESTAMP_X <= FROM_UNIXTIME('" . MkDateTime(FmtDate($val, "D.M.Y") . " 23:59:59", "d.m.Y") . "')";
                     break;
                 case "MODIFIED":
                     $arSqlSearch[] = GetFilterQuery("UM.ID, UM.LOGIN, UM.LAST_NAME, UM.NAME", $val);
                     break;
                 case "MODIFIED_ID":
                     $arSqlSearch[] = "F.MODIFIED_BY = " . intval($val);
                     break;
                 case "CREATED":
                     $arSqlSearch[] = GetFilterQuery("UC.ID, UC.LOGIN, UC.LAST_NAME, UC.NAME", $val);
                     break;
                 case "CREATED_ID":
                     $arSqlSearch[] = "F.CREATED_BY = " . intval($val);
                     break;
                 case "KEYWORDS":
                     $arSqlSearch[] = GetFilterQuery("F.COMMENTS", $val);
                     break;
                 case "NAME":
                     $arSqlSearch[] = GetFilterQuery("F.NAME", $val);
                     break;
                 case "URL":
                     $arSqlSearch[] = GetFilterQuery("F.URL", $val);
                     break;
                 case "MODULE_ID":
                     $arSqlSearch[] = "F.MODULE_ID='" . $DB->ForSql($val, 50) . "'";
                     break;
                 case "MENU_ID":
                     $arSqlSearch[] = "F.MENU_ID='" . $DB->ForSql($val, 255) . "'";
                     break;
             }
         }
     }
     $sOrder = "";
     foreach ($aSort as $key => $val) {
         $ord = strtoupper($val) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($key)) {
             case "ID":
                 $sOrder .= ", F.ID " . $ord;
                 break;
             case "LANGUAGE_ID":
                 $sOrder .= ", F.LANGUAGE_ID " . $ord;
                 break;
             case "COMMON":
                 $sOrder .= ", F.COMMON " . $ord;
                 break;
             case "USER_ID":
                 $sOrder .= ", F.USER_ID " . $ord;
                 break;
             case "TIMESTAMP_X":
                 $sOrder .= ", F.TIMESTAMP_X " . $ord;
                 break;
             case "MODIFIED_BY":
                 $sOrder .= ", F.MODIFIED_BY " . $ord;
                 break;
             case "NAME":
                 $sOrder .= ", F.NAME " . $ord;
                 break;
             case "URL":
                 $sOrder .= ", F.URL " . $ord;
                 break;
             case "SORT":
                 $sOrder .= ", F.C_SORT " . $ord;
                 break;
             case "MODULE_ID":
                 $sOrder .= ", F.MODULE_ID " . $ord;
                 break;
             case "MENU_ID":
                 $sOrder .= ", F.MENU_ID " . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = "F.ID DESC";
     }
     $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tF.ID, F.C_SORT, F.NAME, F.MENU_ID, F.URL, F.MODIFIED_BY, F.CREATED_BY, F.MODULE_ID, F.LANGUAGE_ID,\n\t\t\t\tF.COMMENTS, F.COMMON, F.USER_ID, UM.LOGIN AS M_LOGIN, UC.LOGIN as C_LOGIN, U.LOGIN, F.CODE_ID,\n\t\t\t\t" . $DB->DateToCharFunction("F.TIMESTAMP_X") . "\tTIMESTAMP_X,\n\t\t\t\t" . $DB->DateToCharFunction("F.DATE_CREATE") . "\tDATE_CREATE,\n\t\t\t\t" . $DB->Concat($DB->IsNull("UM.NAME", "''"), "' '", $DB->IsNull("UM.LAST_NAME", "''")) . " as M_USER_NAME,\n\t\t\t\t" . $DB->Concat($DB->IsNull("UC.NAME", "''"), "' '", $DB->IsNull("UC.LAST_NAME", "''")) . " as C_USER_NAME,\n\t\t\t\t" . $DB->Concat($DB->IsNull("U.NAME", "''"), "' '", $DB->IsNull("U.LAST_NAME", "''")) . " as USER_NAME\n\t\t\tFROM\n\t\t\t\tb_favorite F\n\t\t\t\tLEFT JOIN b_user UM ON (UM.ID = F.MODIFIED_BY)\n\t\t\t\tLEFT JOIN b_user UC ON (UC.ID = F.CREATED_BY)\n\t\t\t\tLEFT JOIN b_user U ON (U.ID = F.USER_ID)\n\t\t\tWHERE\n\t\t\t" . $strSqlSearch . "\n\t\t\t" . $strSqlOrder;
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     return $res;
 }
Ejemplo n.º 2
0
 /**
  * <p>Функция предназначена для получения списка обращений в техподдержку.</p>
  *
  *
  *
  *
  * @param varchar &$by  Идентификатор, позволяющий задать имя поля для сортировки.
  * Допустимы следующие значения: <ul> <li>s_id - по ID </li> <li>s_lid - по сайту,
  * для которого было создано обращение </li> <li>s_lamp - по индикатору </li>
  * <li>s_date_create - по дате создания </li> <li>s_timestamp - по дате изменения </li>
  * <li>s_date_close - по дате закрытия </li> <li>s_owner - по автору </li> <li>s_modified_by - по
  * ID пользователя - изменившего обращение </li> <li>s_title - по заголовку
  * </li> <li>s_responsible - по ID ответственного </li> <li>s_messages - по количеству
  * сообщений </li> <li>s_category - по ID категории </li> <li>s_criticality - по ID
  * критичности </li> <li>s_status - по ID статуса </li> <li>s_mark - по ID оценки </li>
  * <li>s_online - по количеству пользователей </li> </ul>
  *
  *
  *
  * @param varchar &$order  Порядок сортировки. Допустимы следующие значения: <ul> <li>desc - по
  * убыванию (значение по умолчанию) </li> <li>asc - по возрастанию </li> </ul>
  *
  *
  *
  * @param array $arFilter = array() Массив для фильтрации значений. Необязательный параметр. В
  * массиве допустимы следующие индексы: <ul> <li>ID - ID обращения
  * (допускается сложная логика) </li> <li>ID_EXACT_MATCH - "Y" - при фильтрации по
  * ID обращения будет искаться точное совпадение (по умолчанию); "N" - в
  * противном случае будет искаться вхождение </li> <li>LID - ID сайта </li>
  * <li>LID_EXACT_MATCH - "Y" - при фильтрации по ID языка будет искаться точное
  * совпадение (по умолчанию); "N" - в противном случае будет искаться
  * вхождение </li> <li>LAMP - массив индикаторов: "red", "yellow", "green", "green_s", "grey"
  * </li> <li>DATE_CREATE_1 - левая часть интервала для даты создания обращения
  * </li> <li>DATE_CREATE_2 - правая часть интервала для даты создания обращения
  * </li> <li>DATE_TIMESTAMP_1 - левая часть интервала для даты модификации
  * обращения </li> <li>DATE_TIMESTAMP_2 - правая часть интервала для даты
  * модификации обращения </li> <li>DATE_CLOSE_1 - левая часть интервала для
  * даты закрытия обращения </li> <li>DATE_CLOSE_2 - правая часть интервала для
  * даты закрытия обращения </li> <li>AUTO_CLOSE_DAYS1 - левая часть интервала
  * для количества дней по истечении которых обращение будет
  * автоматически закрыто при отсутствии ответа от автора </li>
  * <li>AUTO_CLOSE_DAYS2 - правая часть интервала для количества дней по
  * истечении которых обращение будет автоматически закрыто при
  * отсутствии ответа от автора </li> <li>TICKET_TIME_1 - левая часть интервала
  * для количества дней прошедших с даты создания до даты закрытия
  * обращения </li> <li>TICKET_TIME_2 - правая часть интервала для количества
  * дней прошедших с даты создания до даты закрытия обращения </li>
  * <li>TITLE - заголовок обращения (допускается сложная логика) </li>
  * <li>TITLE_EXACT_MATCH - "Y" - при фильтрации по заголовку обращения будет
  * искаться точное совпадение (по умолчанию); "N" - в противном случае
  * будет искаться вхождение </li> <li>MESSAGES1 - левая часть интервала для
  * количества сообщений в обращении </li> <li>MESSAGES2 - правая часть
  * интервала для количества сообщений в обращении </li> <li>OWNER - автор
  * обращения, поиск осуществляется по ID пользователя, логину, имени,
  * фамилии, символному коду (допускается сложная логика) </li>
  * <li>OWNER_EXACT_MATCH - "Y" - при фильтрации по автору обращения будет
  * искаться точное совпадение (по умолчанию); "N" - в противном случае
  * будет искаться вхождение </li> <li>CREATED_BY - кем было создано обращение,
  * поиск осуществляется по ID пользователя, логину, имени, фамилии,
  * названии модуля из которого было создано обращение (допускается
  * сложная логика) </li> <li>CREATED_BY_EXACT_MATCH - "Y" - при фильтрации по
  * создателю обращения будет искаться точное совпадение (по
  * умолчанию); "N" - в противном случае будет искаться вхождение </li>
  * <li>MODIFIED_BY - изменивший обращение, поиск осуществляется по ID
  * пользователя, логину, имени, фамилии, названии модуля из которого
  * было изменено обращение (допускается сложная логика) </li>
  * <li>MODIFIED_BY_EXACT_MATCH - "Y" - при фильтрации по символьному коду статуса
  * будет искаться точное совпадение (по умолчанию); "N" - в противном
  * случае будет искаться вхождение </li> <li>RESPONSIBLE - ответственный за
  * обращение, поиск осуществляется по ID пользователя, логину, имени,
  * фамилии (допускается сложная логика) </li> <li>RESPONSIBLE_EXACT_MATCH - "Y" - при
  * фильтрации по ответственному за обращение будет искаться точное
  * совпадение (по умолчанию); "N" - в противном случае будет искаться
  * вхождение </li> <li>RESPONSIBLE_ID - ID пользователя ответственного за
  * обращение, при задании "0" будут выбраны только те обращения у
  * которых нет ответственного </li> <li>CATEGORY - ID категории обращения (0 -
  * без категории) </li> <li>CATEGORY_SID - символьный код категории обращения
  * (допускается сложная логика) </li> <li>CATEGORY_SID_EXACT_MATCH - "Y" - при
  * фильтрации по символьному коду категории будет искаться точное
  * совпадение (по умолчанию); "N" - в противном случае будет искаться
  * вхождение </li> <li>CRITICALITY - ID критичности обращения (0 - без
  * критичности) </li> <li>CRITICALITY_SID - символьный код критичности
  * обращения (допускается сложная логика) </li> <li>CRITICALITY_SID_EXACT_MATCH - "Y" -
  * при фильтрации по символьному коду критичности будет искаться
  * точное совпадение (по умолчанию); "N" - в противном случае будет
  * искаться вхождение </li> <li>STATUS - ID статуса обращения (0 - без статуса)
  * </li> <li>STATUS_SID - символьный код статуса обращения (допускается
  * сложная логика) </li> <li>STATUS_SID_EXACT_MATCH - "Y" - при фильтрации по
  * символьному коду статуса будет искаться точное совпадение (по
  * умолчанию); "N" - в противном случае будет искаться вхождение </li>
  * <li>STATUS_SID_EXACT_MATCH - "Y" - при фильтрации по символьному коду оценки
  * ответа будет искаться точное совпадение (по умолчанию); "N" - в
  * противном случае будет искаться вхождение </li> <li>MARK - ID оценки
  * ответов (0 - без оценки) </li> <li>MARK_SID - символьный код оценки ответов
  * (допускается сложная логика) </li> <li>SOURCE - ID источника (0 - источник
  * "web") </li> <li>SOURCE_SID - символьный код источника (допускается сложная
  * логика) </li> <li>SOURCE_SID_EXACT_MATCH - "Y" - при фильтрации по символьному коду
  * источника будет искаться точное совпадение (по умолчанию); "N" - в
  * противном случае будет искаться вхождение </li> <li>MESSAGE - текст
  * сообщения (допускается сложная логика) </li> <li>MESSAGE_EXACT_MATCH - "Y" - при
  * фильтрации по сообщению будет искаться точное совпадение (по
  * умолчанию); "N" - в противном случае будет искаться вхождение </li>
  * <li>LAST_MESSAGE_USER_ID - ID пользователя написавшего последнее сообщение в
  * обращении (допускается сложная логика) </li> <li>LAST_MESSAGE_USER_ID_EXACT_MATCH - "Y"
  * - при фильтрации по ID пользователя написавшего последнее
  * сообщение в обращении будет искаться точное совпадение (по
  * умолчанию); "N" - в противном случае будет искаться вхождение </li>
  * <li>LAST_MESSAGE_SID - символьный идентификатор написавшего последнее
  * сообщение в обращении (если источник "email", то это может быть email,
  * если источник "телефон", то это может быть номер телефона)
  * (допускается сложная логика) </li> <li>LAST_MESSAGE_SID_EXACT_MATCH - "Y" - при
  * фильтрации по символьному идентификатору пользователя
  * написавшего последнее сообщение в обращении будет искаться
  * точное совпадение (по умолчанию); "N" - в противном случае будет
  * искаться вхождение </li> <li>SUPPORT_COMMENTS - комментарий техподдержки,
  * видимый в стандартных формах только для пользователей входящих в
  * группу техподдержки </li> <li>SUPPORT_COMMENTS_EXACT_MATCH - "Y" - при фильтрации по ID
  * пользователя написавшего последнее сообщение в обращении будет
  * искаться точное совпадение (по умолчанию); "N" - в противном случае
  * будет искаться вхождение </li> <li>SITE_ID - идентификатор сайта</li> <li>CLOSE
  * - Y\N - закрыт тикет, или нет</li> <li>S_SPAM - Y\N - флаг, является ли тикет
  * спамом</li> <li>IS_OVERDUE - Y\N - флаг, просрочен ли тикет.</li> <li>SLA_ID - по ID
  * уровня техподдержки (допускается сложная логика).</li>
  * <li>SUPPORTTEAM_GROUP_ID - по ID группы техподдержки (число или массив
  * чисел).</li> <li>CLIENT_GROUP_ID - Y\N - по ID группы клиентов (число или массив
  * чисел).</li> </ul>
  *
  *
  *
  * @param boolean &$is_filtered  Переменная возвращающая true в том случае если список результатов
  * отфильтрован по какому либо критерию; либо false в противном случае.
  * Изменен на <b>isFiltered</b> c 12.0.0
  *
  *
  *
  * @param char(1) $CHECK_RIGHTS = "Y" Необязательный параметр. "Y" - будут выбраны только те обращения
  * которые текущий пользователь может просматривать (по умолчанию);
  * "N" - выбирать все обращения независимо от прав текущего
  * пользователя. Изменен на <b>checkRights</b> c 12.0.0
  *
  *
  *
  * @param char(1) $get_user_name = "Y" Необязательный параметр. "Y" - при выборке обращений будут также
  * выбраны такие поля как OWNER_LOGIN, OWNER_NAME, RESPONSIBLE_LOGIN, RESPONSIBLE_NAME, MODIFIED_LOGIN,
  * MODIFIED_NAME, LAST_MESSAGE_LOGIN, LAST_MESSAGE_NAME, CREATED_LOGIN, CREATED_EMAIL, CREATED_NAME, описывающие
  * параметры пользователей имевших отношение к данному обращению
  * (по умолчанию); "N" - вышеперечисленные поля не будут выбраны, но
  * зато это ускорит работу функции. Изменен на <b>getUserName</b> c 12.0.0
  *
  *
  *
  * @param char(1) $get_dictionary_name = "Y" Необязательный параметр. "Y" - при выборке обращений будут также
  * выбраны такие поля как CATEGORY_NAME, CATEGORY_SID, CRITICALITY_NAME, CRITICALITY_SID, STATUS_NAME,
  * STATUS_SID, MARK_NAME, MARK_SID, SOURCE_NAME, SOURCE_SID, описывающие поля из справочника
  * техподдержки (по умолчанию); "N" - вышеперечисленные поля не будут
  * выбраны, но зато это ускорит работу функции. Удален с 4.0.6
  *
  *
  *
  * @param char(2) $lang = LANG Двухсимвольный код языка в формате которого необходимо выбрать
  * временные параметры обращения (время создания, изменения,
  * закрытия); необязательный параметр, по умолчанию - код текущего
  * сайта. Удален с 4.0.0
  *
  *
  *
  * @return record 
  *
  *
  * <h4>Example</h4> 
  * <pre>
  * &lt;?<br>$FilterArr = Array(<br>	"find_id",<br>	"find_lid",<br>	"find_lamp",<br>	"find_date_create1",<br>	"find_date_create2",<br>	"find_date_timestamp1",<br>	"find_date_timestamp2",<br>	"find_date_close1",<br>	"find_date_close2",<br>	"find_close",<br>	"find_ticket_time_1",<br>	"find_ticket_time_2",<br>	"find_title",<br>	"find_messages1",<br>	"find_messages2",<br>	"find_owner",<br>	"find_created_by",<br>	"find_responsible",<br>	"find_responsible_id",<br>	"find_category_id",<br>	"find_criticality_id",<br>	"find_status_id",<br>	"find_mark_id",<br>	"find_source_id",<br>	"find_modified_by",<br>	"find_message"<br>	);<br>if (strlen($set_filter)&gt;0) InitFilterEx($FilterArr,"TICKET_LIST","set",true); else InitFilterEx($FilterArr,"TICKET_LIST","get",true);<br>if (strlen($del_filter)&gt;0) DelFilterEx($FilterArr,"TICKET_LIST",true);<br>if (CheckFilter())<br>{<br>	$arFilter = Array(<br>		"ID"                =&gt; $find_id,<br>		"LID"               =&gt; $find_lid,<br>		"LAMP"              =&gt; $find_lamp,<br>		"DATE_CREATE_1"     =&gt; $find_date_create1,<br>		"DATE_CREATE_2"     =&gt; $find_date_create2,<br>		"DATE_TIMESTAMP_1"  =&gt; $find_date_timestamp1,<br>		"DATE_TIMESTAMP_2"  =&gt; $find_date_timestamp2,<br>		"DATE_CLOSE_1"      =&gt; $find_date_close1,<br>		"DATE_CLOSE_2"      =&gt; $find_date_close2,<br>		"CLOSE"             =&gt; $find_close,<br>		"TICKET_TIME_1"     =&gt; $find_ticket_time_1,<br>		"TICKET_TIME_2"     =&gt; $find_ticket_time_2,<br>		"TITLE"             =&gt; $find_title,<br>		"MESSAGES1"         =&gt; $find_messages1,<br>		"MESSAGES2"         =&gt; $find_messages2,<br>		"OWNER"             =&gt; $find_owner,<br>		"CREATED_BY"        =&gt; $find_created_by,<br>		"RESPONSIBLE"       =&gt; $find_responsible,<br>		"RESPONSIBLE_ID"    =&gt; $find_responsible_id,<br>		"CATEGORY"          =&gt; $find_category_id,<br>		"CRITICALITY"       =&gt; $find_criticality_id,<br>		"STATUS"            =&gt; $find_status_id,<br>		"MARK"              =&gt; $find_mark_id,<br>		"SOURCE"            =&gt; $find_source_id,<br>		"MODIFIED_BY"       =&gt; $find_modified_by,<br>		"MESSAGE"           =&gt; $find_message<br>		);<br>}<br>$tickets = <b>CTicket::GetList</b>($by, $order, $arFilter, $is_filtered);<br>?&gt;<br>
  * </pre>
  *
  *
  * @static
  * @link http://dev.1c-bitrix.ru/api_help/support/classes/cticket/getlist.php
  * @author Bitrix
  */
 public static function GetList(&$by, &$order, $arFilter = array(), &$isFiltered, $checkRights = "Y", $getUserName = "******", $getExtraNames = "Y", $siteID = false, $arParams = array())
 {
     $err_mess = CTicket::err_mess() . "<br>Function: GetList<br>Line: ";
     global $DB, $USER, $USER_FIELD_MANAGER;
     /** @var string $d_join Dictionary join */
     $d_join = "";
     $bAdmin = 'N';
     $bSupportTeam = 'N';
     $bSupportClient = 'N';
     $bDemo = 'N';
     /** @var string $messJoin Messages join */
     $messJoin = "";
     /** @var string $searchJoin Search table join */
     $searchJoin = '';
     $need_group = false;
     $arSqlHaving = array();
     if ($checkRights == 'Y') {
         $bAdmin = CTicket::IsAdmin() ? 'Y' : 'N';
         $bSupportTeam = CTicket::IsSupportTeam() ? 'Y' : 'N';
         $bSupportClient = CTicket::IsSupportClient() ? 'Y' : 'N';
         $bDemo = CTicket::IsDemo() ? 'Y' : 'N';
         $uid = intval($USER->GetID());
     } else {
         $bAdmin = 'Y';
         $bSupportTeam = 'Y';
         $bSupportClient = 'Y';
         $bDemo = 'Y';
         if (is_object($USER)) {
             $uid = intval($USER->GetID());
         } else {
             $uid = -1;
         }
     }
     if ($bAdmin != 'Y' && $bSupportTeam != 'Y' && $bSupportClient != 'Y' && $bDemo != 'Y') {
         return false;
     }
     if ($bSupportTeam == 'Y' || $bAdmin == 'Y' || $bDemo == 'Y') {
         $lamp = "\n\t\t\t\tif(ifnull(T.DATE_CLOSE,'x')<>'x', 'grey',\n\t\t\t\t\tif(ifnull(T.LAST_MESSAGE_USER_ID,0)='{$uid}', 'green',\n\t\t\t\t\t\tif(ifnull(T.OWNER_USER_ID,0)='{$uid}', 'red',\n\t\t\t\t\t\t\tif(T.LAST_MESSAGE_BY_SUPPORT_TEAM='Y','green_s',\n\t\t\t\t\t\t\t\tif(ifnull(T.RESPONSIBLE_USER_ID,0)='{$uid}', 'red',\n\t\t\t\t\t\t\t\t\t'yellow')))))\n\t\t\t\t";
     } else {
         $lamp = "\n\t\t\t\tif(ifnull(T.DATE_CLOSE,'x')<>'x', 'grey',\n\t\t\t\t\tif(T.LAST_MESSAGE_BY_SUPPORT_TEAM='Y', 'red', 'green'))\n\t\t\t\t";
     }
     $bJoinSupportTeamTbl = $bJoinClientTbl = false;
     $arSqlSearch = array();
     $strSqlSearch = "";
     if (is_array($arFilter)) {
         $filterKeys = array_keys($arFilter);
         $filterKeysCount = count($filterKeys);
         for ($i = 0; $i < $filterKeysCount; $i++) {
             $key = $filterKeys[$i];
             $val = $arFilter[$filterKeys[$i]];
             if (is_array($val) && count($val) <= 0 || !is_array($val) && (strlen($val) <= 0 || $val === 'NOT_REF')) {
                 continue;
             }
             $matchValueSet = in_array($key . "_EXACT_MATCH", $filterKeys) ? true : false;
             $key = strtoupper($key);
             switch ($key) {
                 case "ID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.ID", $val, $match);
                     break;
                 case "HOLD_ON":
                     $arSqlSearch[] = $val == "Y" ? "T.HOLD_ON='Y'" : "T.HOLD_ON = 'N'";
                     break;
                 case "LID":
                 case "SITE":
                 case "SITE_ID":
                     if (is_array($val)) {
                         $val = implode(" | ", $val);
                     }
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.SITE_ID", $val, $match);
                     break;
                 case "LAMP":
                     if (is_array($val)) {
                         if (count($val) > 0) {
                             $str = "";
                             foreach ($val as $value) {
                                 $str .= ", '" . $DB->ForSQL($value) . "'";
                             }
                             $str = TrimEx($str, ",");
                             $arSqlSearch[] = " " . $lamp . " in (" . $str . ")";
                         }
                     } elseif (strlen($val) > 0) {
                         $arSqlSearch[] = " " . $lamp . " = '" . $DB->ForSQL($val) . "'";
                     }
                     break;
                 case "DATE_CREATE_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CREATE>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_CREATE_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CREATE<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "DATE_TIMESTAMP_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.TIMESTAMP_X>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_TIMESTAMP_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.TIMESTAMP_X<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "DATE_CLOSE_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CLOSE>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_CLOSE_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CLOSE<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "CLOSE":
                     $arSqlSearch[] = $val == "Y" ? "T.DATE_CLOSE is not null" : "T.DATE_CLOSE is null";
                     break;
                 case "AUTO_CLOSE_DAYS1":
                     $arSqlSearch[] = "T.AUTO_CLOSE_DAYS>='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS2":
                     $arSqlSearch[] = "T.AUTO_CLOSE_DAYS<='" . intval($val) . "'";
                     break;
                 case "TICKET_TIME_1":
                     $arSqlSearch[] = "UNIX_TIMESTAMP(T.DATE_CLOSE) - UNIX_TIMESTAMP(T.DATE_CREATE)>='" . intval($val) * 86400 . "'";
                     break;
                 case "TICKET_TIME_2":
                     $arSqlSearch[] = "UNIX_TIMESTAMP(T.DATE_CLOSE) - UNIX_TIMESTAMP(T.DATE_CREATE)<='" . intval($val) * 86400 . "'";
                     break;
                 case "TITLE":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.TITLE", $val, $match);
                     break;
                 case "MESSAGES1":
                     $arSqlSearch[] = "T.MESSAGES>='" . intval($val) . "'";
                     break;
                 case "MESSAGES2":
                     $arSqlSearch[] = "T.MESSAGES<='" . intval($val) . "'";
                     break;
                 case "PROBLEM_TIME1":
                     $arSqlSearch[] = "T.PROBLEM_TIME>='" . intval($val) . "'";
                     break;
                 case "PROBLEM_TIME2":
                     $arSqlSearch[] = "T.PROBLEM_TIME<='" . intval($val) . "'";
                     break;
                 case "OVERDUE_MESSAGES1":
                     $arSqlSearch[] = "T.OVERDUE_MESSAGES>='" . intval($val) . "'";
                     break;
                 case "OVERDUE_MESSAGES2":
                     $arSqlSearch[] = "T.OVERDUE_MESSAGES<='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS_LEFT1":
                     $arSqlSearch[] = "CASE WHEN (UNIX_TIMESTAMP(T.DATE_CLOSE) IS NULL OR UNIX_TIMESTAMP(T.DATE_CLOSE) = 0) AND T.LAST_MESSAGE_BY_SUPPORT_TEAM = 'Y' THEN\n\t\t\t\t\t\t\tTO_DAYS(ADDDATE(T.LAST_MESSAGE_DATE, INTERVAL T.AUTO_CLOSE_DAYS DAY)) - TO_DAYS(now()) ELSE -1 END >='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS_LEFT2":
                     $arSqlSearch[] = "CASE WHEN (UNIX_TIMESTAMP(T.DATE_CLOSE) IS NULL OR UNIX_TIMESTAMP(T.DATE_CLOSE) = 0) AND T.LAST_MESSAGE_BY_SUPPORT_TEAM = 'Y' THEN\n\t\t\t\t\t\t\tTO_DAYS(ADDDATE(T.LAST_MESSAGE_DATE, INTERVAL T.AUTO_CLOSE_DAYS DAY))-TO_DAYS(now()) ELSE 999 END <='" . intval($val) . "'";
                     break;
                 case "OWNER":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("UO.ID, UO.LOGIN, UO.LAST_NAME, UO.NAME", $val, $match, array("@", "."));
                     //T.OWNER_USER_ID,
                     break;
                 case "OWNER_USER_ID":
                 case "OWNER_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
                 case "SLA_ID":
                 case "SLA":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.SLA_ID", $val, $match);
                     break;
                 case "CREATED_BY":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.CREATED_USER_ID, UC.LOGIN, UC.LAST_NAME, UC.NAME, T.CREATED_MODULE_NAME", $val, $match);
                     break;
                 case "RESPONSIBLE":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.RESPONSIBLE_USER_ID, UR.LOGIN, UR.LAST_NAME, UR.NAME", $val, $match);
                     break;
                 case "RESPONSIBLE_ID":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.RESPONSIBLE_USER_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.RESPONSIBLE_USER_ID is null or T.RESPONSIBLE_USER_ID=0)";
                     }
                     break;
                 case "CATEGORY_ID":
                 case "CATEGORY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.CATEGORY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.CATEGORY_ID is null or T.CATEGORY_ID=0)";
                     }
                     break;
                 case "CATEGORY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DC.SID", $val, $match);
                     $d_join = "\n\t\t\tLEFT JOIN b_ticket_dictionary DC ON (DC.ID = T.CATEGORY_ID and DC.C_TYPE = 'C')";
                     break;
                 case "CRITICALITY_ID":
                 case "CRITICALITY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.CRITICALITY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.CRITICALITY_ID is null or T.CRITICALITY_ID=0)";
                     }
                     break;
                 case "CRITICALITY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DK.SID", $val, $match);
                     break;
                 case "STATUS_ID":
                 case "STATUS":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.STATUS_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.STATUS_ID is null or T.STATUS_ID=0)";
                     }
                     break;
                 case "STATUS_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DS.SID", $val, $match);
                     break;
                 case "MARK_ID":
                 case "MARK":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.MARK_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.MARK_ID is null or T.MARK_ID=0)";
                     }
                     break;
                 case "MARK_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DM.SID", $val, $match);
                     break;
                 case "SOURCE_ID":
                 case "SOURCE":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.SOURCE_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.SOURCE_ID is null or T.SOURCE_ID=0)";
                     }
                     break;
                 case "SOURCE_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DSR.SID", $val, $match);
                     break;
                 case "DIFFICULTY_ID":
                 case "DIFFICULTY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.DIFFICULTY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.DIFFICULTY_ID is null or T.DIFFICULTY_ID=0)";
                     }
                     break;
                 case "DIFFICULTY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DD.SID", $val, $match);
                     break;
                 case "MODIFIED_BY":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.MODIFIED_USER_ID, T.MODIFIED_MODULE_NAME, UM.LOGIN, UM.LAST_NAME, UM.NAME", $val, $match);
                     break;
                 case "MESSAGE":
                     global $strError;
                     if (strlen($val) <= 0) {
                         break;
                     }
                     if (CSupportSearch::CheckModule() && CSupportSearch::isIndexExists()) {
                         // new indexed search
                         $searchSqlParams = CSupportSearch::getSql($val);
                         $searchOn = $searchSqlParams['WHERE'];
                         $searchHaving = $searchSqlParams['HAVING'];
                         if ($searchOn) {
                             $searchJoin = 'INNER JOIN b_ticket_search TS ON TS.TICKET_ID = T.ID AND ' . $searchOn;
                             if (!empty($searchHaving)) {
                                 // 2 or more search words
                                 $arSqlHaving[] = $searchHaving;
                                 $need_group = true;
                             }
                         }
                     } else {
                         if ($bSupportTeam == "Y" || $bAdmin == "Y" || $bDemo == "Y") {
                             $messJoin = "INNER JOIN b_ticket_message M ON (M.TICKET_ID=T.ID)";
                         } else {
                             $messJoin = "INNER JOIN b_ticket_message M ON (M.TICKET_ID=T.ID and M.IS_HIDDEN='N' and M.IS_LOG='N')";
                         }
                         $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                         $f = new CFilterQuery("OR", "yes", $match, array(), "N", "Y", "N");
                         $query = $f->GetQueryString("T.TITLE,M.MESSAGE_SEARCH", $val);
                         $error = $f->error;
                         if (strlen(trim($error)) > 0) {
                             $strError .= $error . "<br>";
                             $query = "0";
                         } else {
                             $arSqlSearch[] = $query;
                         }
                     }
                     break;
                 case "LAST_MESSAGE_USER_ID":
                 case "LAST_MESSAGE_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
                 case "LAST_MESSAGE_BY_SUPPORT_TEAM":
                     $arSqlSearch[] = "T.LAST_MESSAGE_BY_SUPPORT_TEAM= '" . ($val == 'Y' ? 'Y' : 'N') . "'";
                     break;
                 case "SUPPORT_COMMENTS":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.SUPPORT_COMMENTS", $val, $match);
                     break;
                 case "IS_SPAM":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_SPAM ='Y'" : "(T.IS_SPAM = 'N' or T.IS_SPAM is null)";
                     break;
                 case "IS_OVERDUE":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_OVERDUE ='Y'" : "(T.IS_OVERDUE = 'N' or T.IS_OVERDUE is null)";
                     break;
                 case "IS_SPAM_MAYBE":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_SPAM='N'" : "(T.IS_SPAM='Y' or T.IS_SPAM is null)";
                     break;
                 case 'SUPPORTTEAM_GROUP_ID':
                 case 'CLIENT_GROUP_ID':
                     if ($key == 'SUPPORTTEAM_GROUP_ID') {
                         $table = 'UGS';
                         $bJoinSupportTeamTbl = true;
                     } else {
                         $table = 'UGC';
                         $bJoinClientTbl = true;
                     }
                     if (is_array($val)) {
                         $val = array_map('intval', $val);
                         $val = array_unique($val);
                         $val = array_filter($val);
                         if (count($val) > 0) {
                             $arSqlSearch[] = '(' . $table . '.GROUP_ID IS NOT NULL AND ' . $table . '.GROUP_ID IN (' . implode(',', $val) . '))';
                         }
                     } else {
                         $val = intval($val);
                         if ($val > 0) {
                             $arSqlSearch[] = '(' . $table . '.GROUP_ID IS NOT NULL AND ' . $table . '.GROUP_ID=\'' . $val . '\')';
                         }
                     }
                     break;
                 case 'COUPON':
                     $match = $matchValueSet && $arFilter[$key . "_EXACT_MATCH"] != "Y" ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
             }
         }
     }
     $obUserFieldsSql = new CUserTypeSQL();
     $obUserFieldsSql->SetEntity("SUPPORT", "T.ID");
     $obUserFieldsSql->SetSelect($arParams["SELECT"]);
     $obUserFieldsSql->SetFilter($arFilter);
     $obUserFieldsSql->SetOrder(array($by => $order));
     if ($by == "s_id") {
         $strSqlOrder = "ORDER BY T.ID";
     } elseif ($by == "s_last_message_date") {
         $strSqlOrder = "ORDER BY T.LAST_MESSAGE_DATE";
     } elseif ($by == "s_site_id" || $by == "s_lid") {
         $strSqlOrder = "ORDER BY T.SITE_ID";
     } elseif ($by == "s_lamp") {
         $strSqlOrder = "ORDER BY LAMP";
     } elseif ($by == "s_is_overdue") {
         $strSqlOrder = "ORDER BY T.IS_OVERDUE";
     } elseif ($by == "s_is_notified") {
         $strSqlOrder = "ORDER BY T.IS_NOTIFIED";
     } elseif ($by == "s_date_create") {
         $strSqlOrder = "ORDER BY T.DATE_CREATE";
     } elseif ($by == "s_timestamp" || $by == "s_timestamp_x") {
         $strSqlOrder = "ORDER BY T.TIMESTAMP_X";
     } elseif ($by == "s_date_close") {
         $strSqlOrder = "ORDER BY T.DATE_CLOSE";
     } elseif ($by == "s_owner") {
         $strSqlOrder = "ORDER BY T.OWNER_USER_ID";
     } elseif ($by == "s_modified_by") {
         $strSqlOrder = "ORDER BY T.MODIFIED_USER_ID";
     } elseif ($by == "s_title") {
         $strSqlOrder = "ORDER BY T.TITLE ";
     } elseif ($by == "s_responsible") {
         $strSqlOrder = "ORDER BY T.RESPONSIBLE_USER_ID";
     } elseif ($by == "s_messages") {
         $strSqlOrder = "ORDER BY T.MESSAGES";
     } elseif ($by == "s_category") {
         $strSqlOrder = "ORDER BY T.CATEGORY_ID";
     } elseif ($by == "s_criticality") {
         $strSqlOrder = "ORDER BY T.CRITICALITY_ID";
     } elseif ($by == "s_sla") {
         $strSqlOrder = "ORDER BY T.SLA_ID";
     } elseif ($by == "s_status") {
         $strSqlOrder = "ORDER BY T.STATUS_ID";
     } elseif ($by == "s_difficulty") {
         $strSqlOrder = "ORDER BY T.DIFFICULTY_ID";
     } elseif ($by == "s_problem_time") {
         $strSqlOrder = "ORDER BY T.PROBLEM_TIME";
     } elseif ($by == "s_mark") {
         $strSqlOrder = "ORDER BY T.MARK_ID";
     } elseif ($by == "s_online") {
         $strSqlOrder = "ORDER BY USERS_ONLINE";
     } elseif ($by == "s_support_comments") {
         $strSqlOrder = "ORDER BY T.SUPPORT_COMMENTS";
     } elseif ($by == "s_auto_close_days_left") {
         $strSqlOrder = "ORDER BY AUTO_CLOSE_DAYS_LEFT";
     } elseif ($by == 's_coupon') {
         $strSqlOrder = 'ORDER BY T.COUPON';
     } elseif ($by == 's_deadline') {
         $strSqlOrder = 'ORDER BY T.SUPPORT_DEADLINE';
     } elseif ($s = $obUserFieldsSql->GetOrder($by)) {
         $strSqlOrder = "ORDER BY " . strtoupper($s);
     } else {
         $by = "s_default";
         $strSqlOrder = "ORDER BY IS_SUPER_TICKET DESC, T.IS_OVERDUE DESC, T.IS_NOTIFIED DESC, T.LAST_MESSAGE_DATE";
     }
     if ($order != "asc") {
         $strSqlOrder .= " desc ";
         $order = "desc";
     }
     $arSqlSearch[] = $obUserFieldsSql->GetFilter();
     if ($getUserName == "Y") {
         $u_select = "\n\t\t\t\t,\n\t\t\t\tUO.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tOWNER_LOGIN,\n\t\t\t\tUO.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tOWNER_EMAIL,\n\t\t\t\tconcat(ifnull(UO.NAME,''),' ',ifnull(UO.LAST_NAME,''))\t\tOWNER_NAME,\n\t\t\t\tUR.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tRESPONSIBLE_LOGIN,\n\t\t\t\tUR.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tRESPONSIBLE_EMAIL,\n\t\t\t\tconcat(ifnull(UR.NAME,''),' ',ifnull(UR.LAST_NAME,''))\t\tRESPONSIBLE_NAME,\n\t\t\t\tUM.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_BY_LOGIN,\n\t\t\t\tUM.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_BY_EMAIL,\n\t\t\t\tconcat(ifnull(UM.NAME,''),' ',ifnull(UM.LAST_NAME,''))\t\tMODIFIED_BY_NAME,\n\t\t\t\tUM.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_LOGIN,\n\t\t\t\tUM.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_EMAIL,\n\t\t\t\tconcat(ifnull(UM.NAME,''),' ',ifnull(UM.LAST_NAME,''))\t\tMODIFIED_NAME,\n\t\t\t\tUL.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tLAST_MESSAGE_LOGIN,\n\t\t\t\tUL.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tLAST_MESSAGE_EMAIL,\n\t\t\t\tconcat(ifnull(UL.NAME,''),' ',ifnull(UL.LAST_NAME,''))\t\tLAST_MESSAGE_NAME,\n\t\t\t\tUC.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tCREATED_LOGIN,\n\t\t\t\tUC.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tCREATED_EMAIL,\n\t\t\t\tconcat(ifnull(UC.NAME,''),' ',ifnull(UC.LAST_NAME,''))\t\tCREATED_NAME\n\t\t\t";
         $u_join = "\n\t\t\tLEFT JOIN b_user UO ON (UO.ID = T.OWNER_USER_ID)\n\t\t\tLEFT JOIN b_user UR ON (UR.ID = T.RESPONSIBLE_USER_ID)\n\t\t\tLEFT JOIN b_user UM ON (UM.ID = T.MODIFIED_USER_ID)\n\t\t\tLEFT JOIN b_user UL ON (UL.ID = T.LAST_MESSAGE_USER_ID)\n\t\t\tLEFT JOIN b_user UC ON (UC.ID = T.CREATED_USER_ID)\n\t\t\t";
     }
     if ($getExtraNames == "Y") {
         $d_select = "\n\t\t\t\t,\n\t\t\t\tDC.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_NAME,\n\t\t\t\tDC.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_DESC,\n\t\t\t\tDC.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_SID,\n\t\t\t\tDK.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_NAME,\n\t\t\t\tDK.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_DESC,\n\t\t\t\tDK.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_SID,\n\t\t\t\tDS.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_NAME,\n\t\t\t\tDS.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_DESC,\n\t\t\t\tDS.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_SID,\n\t\t\t\tDM.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_NAME,\n\t\t\t\tDM.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_DESC,\n\t\t\t\tDM.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_SID,\n\t\t\t\tDSR.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_NAME,\n\t\t\t\tDSR.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_DESC,\n\t\t\t\tDSR.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_SID,\n\t\t\t\tDD.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_NAME,\n\t\t\t\tDD.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_DESC,\n\t\t\t\tDD.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_SID,\n\t\t\t\tSLA.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tSLA_NAME\n\t\t\t";
         $d_join = "\n\t\t\tLEFT JOIN b_ticket_dictionary DC ON (DC.ID = T.CATEGORY_ID and DC.C_TYPE = 'C')\n\t\t\tLEFT JOIN b_ticket_dictionary DK ON (DK.ID = T.CRITICALITY_ID and DK.C_TYPE = 'K')\n\t\t\tLEFT JOIN b_ticket_dictionary DS ON (DS.ID = T.STATUS_ID and DS.C_TYPE = 'S')\n\t\t\tLEFT JOIN b_ticket_dictionary DM ON (DM.ID = T.MARK_ID and DM.C_TYPE = 'M')\n\t\t\tLEFT JOIN b_ticket_dictionary DSR ON (DSR.ID = T.SOURCE_ID and DSR.C_TYPE = 'SR')\n\t\t\tLEFT JOIN b_ticket_dictionary DD ON (DD.ID = T.DIFFICULTY_ID and DD.C_TYPE = 'D')\n\t\t\tLEFT JOIN b_ticket_sla SLA ON (SLA.ID = T.SLA_ID)\n\t\t\t";
     }
     if (strlen($siteID) > 0) {
         $dates_select = "\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "FULL", $siteID, true) . "\tDATE_CREATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "FULL", $siteID, true) . "\tTIMESTAMP_X,\n\t\t\t\t" . $DB->DateToCharFunction("T.LAST_MESSAGE_DATE", "FULL", $siteID, true) . "\tLAST_MESSAGE_DATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "FULL", $siteID, true) . "\tDATE_CLOSE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "SHORT", $siteID, true) . "\tDATE_CREATE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "SHORT", $siteID, true) . "\tTIMESTAMP_X_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "SHORT", $siteID, true) . "\tDATE_CLOSE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.SUPPORT_DEADLINE", "FULL", $siteID, true) . "\tSUPPORT_DEADLINE,\n\t\t\t\tCASE WHEN (UNIX_TIMESTAMP(T.DATE_CLOSE) IS NULL OR UNIX_TIMESTAMP(T.DATE_CLOSE) = 0) AND T.LAST_MESSAGE_BY_SUPPORT_TEAM = 'Y' THEN " . $DB->DateToCharFunction("ADDDATE(T.LAST_MESSAGE_DATE, INTERVAL T.AUTO_CLOSE_DAYS DAY)", "FULL", $siteID, true) . " ELSE NULL END AUTO_CLOSE_DATE\n\t\t\t";
     } else {
         $dates_select = "\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "FULL") . "\t\tDATE_CREATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "FULL") . "\t\tTIMESTAMP_X,\n\t\t\t\t" . $DB->DateToCharFunction("T.LAST_MESSAGE_DATE", "FULL") . "\tLAST_MESSAGE_DATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "FULL") . "\t\tDATE_CLOSE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "SHORT") . "\tDATE_CREATE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "SHORT") . "\tTIMESTAMP_X_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "SHORT") . "\t\tDATE_CLOSE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.SUPPORT_DEADLINE", "FULL") . "\tSUPPORT_DEADLINE,\n\t\t\t\tCASE WHEN (UNIX_TIMESTAMP(T.DATE_CLOSE) IS NULL OR UNIX_TIMESTAMP(T.DATE_CLOSE) = 0) AND T.LAST_MESSAGE_BY_SUPPORT_TEAM = 'Y' THEN " . $DB->DateToCharFunction("ADDDATE(T.LAST_MESSAGE_DATE, INTERVAL T.AUTO_CLOSE_DAYS DAY)", "FULL") . " ELSE NULL END AUTO_CLOSE_DATE\n\t\t\t";
     }
     $ugroupJoin = '';
     if ($bJoinSupportTeamTbl) {
         $ugroupJoin .= "\n\t\t\tLEFT JOIN b_ticket_user_ugroup UGS ON (UGS.USER_ID = T.RESPONSIBLE_USER_ID) ";
         $need_group = true;
     }
     if ($bJoinClientTbl) {
         $ugroupJoin .= "\n\t\t\tLEFT JOIN b_ticket_user_ugroup UGC ON (UGC.USER_ID = T.OWNER_USER_ID) ";
         $need_group = true;
     }
     // add permissions check
     if (!($bAdmin == 'Y' || $bDemo == 'Y')) {
         // a list of users who own or are responsible for tickets, which we can show to our current user
         $ticketUsers = array($uid);
         // check if user has groups
         $result = $DB->Query('SELECT GROUP_ID FROM b_ticket_user_ugroup WHERE USER_ID = ' . $uid . ' AND CAN_VIEW_GROUP_MESSAGES = \'Y\'');
         if ($result) {
             // collect members of these groups
             $uGroups = array();
             while ($row = $result->Fetch()) {
                 $uGroups[] = $row['GROUP_ID'];
             }
             if (!empty($uGroups)) {
                 $result = $DB->Query('SELECT USER_ID FROM b_ticket_user_ugroup WHERE GROUP_ID IN (' . join(',', $uGroups) . ')');
                 if ($result) {
                     while ($row = $result->Fetch()) {
                         $ticketUsers[] = $row['USER_ID'];
                     }
                 }
             }
         }
         // build sql
         $strSqlSearchUser = "";
         if ($bSupportTeam == 'Y') {
             $strSqlSearchUser = '******' . join(',', $ticketUsers) . ')';
         } elseif ($bSupportClient == 'Y') {
             $strSqlSearchUser = '******' . join(',', $ticketUsers) . ')';
         }
         $arSqlSearch[] = $strSqlSearchUser;
     }
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $onlineInterval = intval(COption::GetOptionString("support", "ONLINE_INTERVAL"));
     $strSqlSelect = "\n\t\t\tSELECT\n\t\t\t\tT.*,\n\t\t\t\tT.SITE_ID,\n\t\t\t\tT.SITE_ID\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLID,\n\t\t\t\t{$dates_select},\n\t\t\t\tUNIX_TIMESTAMP(T.DATE_CLOSE)-UNIX_TIMESTAMP(T.DATE_CREATE)\t\t\t\t\t\t\tTICKET_TIME,\n\t\t\t\tCASE WHEN (UNIX_TIMESTAMP(T.DATE_CLOSE) IS NULL OR UNIX_TIMESTAMP(T.DATE_CLOSE) = 0) AND T.LAST_MESSAGE_BY_SUPPORT_TEAM = 'Y' THEN\n\t\t\t\t\tTO_DAYS(\n\t\t\t\t\t\tADDDATE(\n\t\t\t\t\t\t\tT.LAST_MESSAGE_DATE, INTERVAL T.AUTO_CLOSE_DAYS DAY\n\t\t\t\t\t\t)\n\t\t\t\t\t) - TO_DAYS(now())\n\t\t\t\tELSE -1 END AUTO_CLOSE_DAYS_LEFT,\n\t\t\t\t(SELECT COUNT(DISTINCT USER_ID) FROM b_ticket_online WHERE TICKET_ID = T.ID AND TIMESTAMP_X >= DATE_ADD(now(), INTERVAL - " . $onlineInterval . " SECOND)) USERS_ONLINE,\n\t\t\t\tif(T.COUPON IS NOT NULL, 1, 0)\t\t\t\t\t\t\t\t\t\t\t\t\t\tIS_SUPER_TICKET,\n\t\t\t\t{$lamp}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLAMP\n\t\t\t\t{$d_select}\n\t\t\t\t{$u_select}\n\t\t\t\t" . $obUserFieldsSql->GetSelect();
     $strSqlFrom = "\n\t\t\tFROM\n\t\t\t\tb_ticket T\n\t\t\t{$u_join}\n\t\t\t{$d_join}\n\t\t\t{$messJoin}\n\t\t\t{$searchJoin}\n\t\t\t{$ugroupJoin}\n\t\t\t\t" . $obUserFieldsSql->GetJoin("T.ID");
     $strSqlWhere = "\n\t\t\tWHERE\n\t\t\t{$strSqlSearch}\n\t\t";
     $strSqlGroup = $need_group ? ' GROUP BY T.ID  ' : '';
     $strSqlHaving = $arSqlHaving ? ' HAVING ' . join(' AND ', $arSqlHaving) . ' ' : '';
     $strSql = $strSqlSelect . $strSqlFrom . $strSqlWhere . $strSqlGroup . $strSqlHaving . $strSqlOrder;
     if (is_array($arParams) && isset($arParams["NAV_PARAMS"]) && is_array($arParams["NAV_PARAMS"])) {
         $nTopCount = isset($arParams['NAV_PARAMS']['nTopCount']) ? intval($arParams['NAV_PARAMS']['nTopCount']) : 0;
         if ($nTopCount > 0) {
             $strSql = $DB->TopSql($strSql, $nTopCount);
             $res = $DB->Query($strSql, false, $err_mess . __LINE__);
             $res->SetUserFields($USER_FIELD_MANAGER->GetUserFields("SUPPORT"));
         } else {
             $cntSql = "SELECT COUNT(T.ID) as C " . $strSqlFrom . $strSqlWhere . $strSqlGroup . $strSqlHaving;
             if (!empty($strSqlGroup)) {
                 $cntSql = 'SELECT COUNT(1) AS C FROM (' . $cntSql . ') tt';
             }
             $res_cnt = $DB->Query($cntSql);
             $res_cnt = $res_cnt->Fetch();
             $res = new CDBResult();
             $res->SetUserFields($USER_FIELD_MANAGER->GetUserFields("SUPPORT"));
             $res->NavQuery($strSql, $res_cnt["C"], $arParams["NAV_PARAMS"]);
         }
     } else {
         $res = $DB->Query($strSql, false, $err_mess . __LINE__);
         $res->SetUserFields($USER_FIELD_MANAGER->GetUserFields("SUPPORT"));
     }
     $isFiltered = IsFiltered($strSqlSearch);
     return $res;
 }
Ejemplo n.º 3
0
 function GetList(&$by, &$order, $arFilter = array(), &$isFiltered, $checkRights = "Y", $getUserName = "******", $getExtraNames = "Y", $siteID = false, $arParams = array())
 {
     $err_mess = CTicket::err_mess() . "<br>Function: GetList<br>Line: ";
     global $DB, $USER, $USER_FIELD_MANAGER;
     $bAdmin = 'N';
     $bSupportTeam = 'N';
     $bSupportClient = 'N';
     $bDemo = 'N';
     $messJoin = "";
     if ($checkRights == 'Y') {
         $bAdmin = CTicket::IsAdmin() ? 'Y' : 'N';
         $bSupportTeam = CTicket::IsSupportTeam() ? 'Y' : 'N';
         $bSupportClient = CTicket::IsSupportClient() ? 'Y' : 'N';
         $bDemo = CTicket::IsDemo() ? 'Y' : 'N';
         $uid = intval($USER->GetID());
     } else {
         $bAdmin = 'Y';
         $bSupportTeam = 'Y';
         $bSupportClient = 'Y';
         $bDemo = 'Y';
         if (is_object($USER)) {
             $uid = intval($USER->GetID());
         } else {
             $uid = -1;
         }
     }
     if ($bAdmin != 'Y' && $bSupportTeam != 'Y' && $bSupportClient != 'Y' && $bDemo != 'Y') {
         return false;
     }
     if ($bSupportTeam == 'Y' || $bAdmin == 'Y' || $bDemo == 'Y') {
         $lamp = "\n\t\t\t\tif(ifnull(T.DATE_CLOSE,'x')<>'x', 'grey',\n\t\t\t\t\tif(ifnull(T.LAST_MESSAGE_USER_ID,0)='{$uid}', 'green',\n\t\t\t\t\t\tif(ifnull(T.OWNER_USER_ID,0)='{$uid}', 'red',\n\t\t\t\t\t\t\tif(T.LAST_MESSAGE_BY_SUPPORT_TEAM='Y','green_s',\n\t\t\t\t\t\t\t\tif(ifnull(T.RESPONSIBLE_USER_ID,0)='{$uid}', 'red',\n\t\t\t\t\t\t\t\t\t'yellow')))))\n\t\t\t\t";
     } else {
         $lamp = "\n\t\t\t\tif(ifnull(T.DATE_CLOSE,'x')<>'x', 'grey',\n\t\t\t\t\tif(ifnull(T.LAST_MESSAGE_USER_ID,0)='{$uid}', 'green', 'red'))\n\t\t\t\t";
     }
     $bJoinSupportTeamTbl = $bJoinClientTbl = false;
     $arSqlSearch = array();
     $strSqlSearch = "";
     if (is_array($arFilter)) {
         $filterKeys = array_keys($arFilter);
         for ($i = 0; $i < count($filterKeys); $i++) {
             $key = $filterKeys[$i];
             $val = $arFilter[$filterKeys[$i]];
             if (is_array($val) && count($val) <= 0 || !is_array($val) && (strlen($val) <= 0 || $val === 'NOT_REF')) {
                 continue;
             }
             $matchValueSet = in_array($key . "_EXACT_MATCH", $filterKeys) ? true : false;
             $key = strtoupper($key);
             switch ($key) {
                 case "ID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.ID", $val, $match);
                     break;
                 case "HOLD_ON":
                     $arSqlSearch[] = $val == "Y" ? "T.HOLD_ON='Y'" : "T.HOLD_ON = 'N'";
                     break;
                 case "LID":
                 case "SITE":
                 case "SITE_ID":
                     if (is_array($val)) {
                         $val = implode(" | ", $val);
                     }
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.SITE_ID", $val, $match);
                     break;
                 case "LAMP":
                     if (is_array($val)) {
                         if (count($val) > 0) {
                             foreach ($val as $value) {
                                 $str .= ", '" . $DB->ForSQL($value) . "'";
                             }
                             $str = TrimEx($str, ",");
                             $arSqlSearch[] = " " . $lamp . " in (" . $str . ")";
                         }
                     } elseif (strlen($val) > 0) {
                         $arSqlSearch[] = " " . $lamp . " = '" . $DB->ForSQL($val) . "'";
                     }
                     break;
                 case "DATE_CREATE_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CREATE>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_CREATE_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CREATE<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "DATE_TIMESTAMP_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.TIMESTAMP_X>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_TIMESTAMP_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.TIMESTAMP_X<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "DATE_CLOSE_1":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CLOSE>=" . $DB->CharToDateFunction($val, "SHORT");
                     }
                     break;
                 case "DATE_CLOSE_2":
                     if (CheckDateTime($val)) {
                         $arSqlSearch[] = "T.DATE_CLOSE<" . $DB->CharToDateFunction($val, "SHORT") . " + INTERVAL 1 DAY";
                     }
                     break;
                 case "CLOSE":
                     $arSqlSearch[] = $val == "Y" ? "T.DATE_CLOSE is not null" : "T.DATE_CLOSE is null";
                     break;
                 case "AUTO_CLOSE_DAYS1":
                     $arSqlSearch[] = "T.AUTO_CLOSE_DAYS>='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS2":
                     $arSqlSearch[] = "T.AUTO_CLOSE_DAYS<='" . intval($val) . "'";
                     break;
                 case "TICKET_TIME_1":
                     $arSqlSearch[] = "UNIX_TIMESTAMP(T.DATE_CLOSE) - UNIX_TIMESTAMP(T.DATE_CREATE)>='" . intval($val) * 86400 . "'";
                     break;
                 case "TICKET_TIME_2":
                     $arSqlSearch[] = "UNIX_TIMESTAMP(T.DATE_CLOSE) - UNIX_TIMESTAMP(T.DATE_CREATE)<='" . intval($val) * 86400 . "'";
                     break;
                 case "TITLE":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.TITLE", $val, $match);
                     break;
                 case "MESSAGES1":
                     $arSqlSearch[] = "T.MESSAGES>='" . intval($val) . "'";
                     break;
                 case "MESSAGES2":
                     $arSqlSearch[] = "T.MESSAGES<='" . intval($val) . "'";
                     break;
                 case "PROBLEM_TIME1":
                     $arSqlSearch[] = "T.PROBLEM_TIME>='" . intval($val) . "'";
                     break;
                 case "PROBLEM_TIME2":
                     $arSqlSearch[] = "T.PROBLEM_TIME<='" . intval($val) . "'";
                     break;
                 case "OVERDUE_MESSAGES1":
                     $arSqlSearch[] = "T.OVERDUE_MESSAGES>='" . intval($val) . "'";
                     break;
                 case "OVERDUE_MESSAGES2":
                     $arSqlSearch[] = "T.OVERDUE_MESSAGES<='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS_LEFT1":
                     $arSqlSearch[] = "TO_DAYS(ADDDATE(T.TIMESTAMP_X, INTERVAL T.AUTO_CLOSE_DAYS DAY))-TO_DAYS(now())>='" . intval($val) . "'";
                     break;
                 case "AUTO_CLOSE_DAYS_LEFT2":
                     $arSqlSearch[] = "TO_DAYS(ADDDATE(T.TIMESTAMP_X, INTERVAL T.AUTO_CLOSE_DAYS DAY))-TO_DAYS(now())<='" . intval($val) . "'";
                     break;
                 case "OWNER":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.OWNER_USER_ID, UO.LOGIN, UO.LAST_NAME, UO.NAME, T.OWNER_SID", $val, $match, array("@", "."));
                     break;
                 case "OWNER_USER_ID":
                 case "OWNER_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
                 case "SLA_ID":
                 case "SLA":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T.SLA_ID", $val, $match);
                     break;
                 case "CREATED_BY":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.CREATED_USER_ID, UC.LOGIN, UC.LAST_NAME, UC.NAME, T.CREATED_MODULE_NAME", $val, $match);
                     break;
                 case "RESPONSIBLE":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.RESPONSIBLE_USER_ID, UR.LOGIN, UR.LAST_NAME, UR.NAME", $val, $match);
                     break;
                 case "RESPONSIBLE_ID":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.RESPONSIBLE_USER_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.RESPONSIBLE_USER_ID is null or T.RESPONSIBLE_USER_ID=0)";
                     }
                     break;
                 case "CATEGORY_ID":
                 case "CATEGORY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.CATEGORY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.CATEGORY_ID is null or T.CATEGORY_ID=0)";
                     }
                     break;
                 case "CATEGORY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DC.SID", $val, $match);
                     break;
                 case "CRITICALITY_ID":
                 case "CRITICALITY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.CRITICALITY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.CRITICALITY_ID is null or T.CRITICALITY_ID=0)";
                     }
                     break;
                 case "CRITICALITY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DK.SID", $val, $match);
                     break;
                 case "STATUS_ID":
                 case "STATUS":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.STATUS_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.STATUS_ID is null or T.STATUS_ID=0)";
                     }
                     break;
                 case "STATUS_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DS.SID", $val, $match);
                     break;
                 case "MARK_ID":
                 case "MARK":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.MARK_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.MARK_ID is null or T.MARK_ID=0)";
                     }
                     break;
                 case "MARK_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DM.SID", $val, $match);
                     break;
                 case "SOURCE_ID":
                 case "SOURCE":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.SOURCE_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.SOURCE_ID is null or T.SOURCE_ID=0)";
                     }
                     break;
                 case "SOURCE_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DSR.SID", $val, $match);
                     break;
                 case "DIFFICULTY_ID":
                 case "DIFFICULTY":
                     if (intval($val) > 0) {
                         $arSqlSearch[] = "T.DIFFICULTY_ID = '" . intval($val) . "'";
                     } elseif ($val == 0) {
                         $arSqlSearch[] = "(T.DIFFICULTY_ID is null or T.DIFFICULTY_ID=0)";
                     }
                     break;
                 case "DIFFICULTY_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("DD.SID", $val, $match);
                     break;
                 case "MODIFIED_BY":
                     $getUserName = "******";
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.MODIFIED_USER_ID, T.MODIFIED_MODULE_NAME, UM.LOGIN, UM.LAST_NAME, UM.NAME", $val, $match);
                     break;
                 case "MESSAGE":
                     global $strError;
                     if (strlen($val) <= 0) {
                         break;
                     }
                     if ($bSupportTeam == "Y" || $bAdmin == "Y" || $bDemo == "Y") {
                         $messJoin = "INNER JOIN b_ticket_message M ON (M.TICKET_ID=T.ID)";
                     } else {
                         $messJoin = "INNER JOIN b_ticket_message M ON (M.TICKET_ID=T.ID and M.IS_HIDDEN='N' and M.IS_LOG='N')";
                     }
                     if (CSupportSearch::checkModule()) {
                         $arSqlSearch[] = CSupportSearch::GetFilterQuery($val, "M.ID", "T.TITLE", "M.MESSAGE", $strError);
                     } else {
                         $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                         $f = new CFilterQuery("OR", "yes", $match, array(), "N", "Y", "N");
                         $query = $f->GetQueryString("T.TITLE,M.MESSAGE_SEARCH", $val);
                         $error = $f->error;
                         if (strlen(trim($error)) > 0) {
                             $strError .= $error . "<br>";
                             $query = "0";
                         } else {
                             $arSqlSearch[] = $query;
                         }
                     }
                     break;
                 case "LAST_MESSAGE_USER_ID":
                 case "LAST_MESSAGE_SID":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "N" && $matchValueSet ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
                 case "SUPPORT_COMMENTS":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $matchValueSet ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("T.SUPPORT_COMMENTS", $val, $match);
                     break;
                 case "IS_SPAM":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_SPAM ='Y'" : "(T.IS_SPAM = 'N' or T.IS_SPAM is null)";
                     break;
                 case "IS_OVERDUE":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_OVERDUE ='Y'" : "(T.IS_OVERDUE = 'N' or T.IS_OVERDUE is null)";
                     break;
                 case "IS_SPAM_MAYBE":
                     $arSqlSearch[] = $val == "Y" ? "T.IS_SPAM='N'" : "(T.IS_SPAM='Y' or T.IS_SPAM is null)";
                     break;
                 case 'SUPPORTTEAM_GROUP_ID':
                 case 'CLIENT_GROUP_ID':
                     if ($key == 'SUPPORTTEAM_GROUP_ID') {
                         $table = 'UGS';
                         $bJoinSupportTeamTbl = true;
                     } else {
                         $table = 'UGC';
                         $bJoinClientTbl = true;
                     }
                     if (is_array($val)) {
                         $val = array_map('intval', $val);
                         $val = array_unique($val);
                         $val = array_filter($val);
                         if (count($val) > 0) {
                             $arSqlSearch[] = '(' . $table . '.GROUP_ID IS NOT NULL AND ' . $table . '.GROUP_ID IN (' . implode(',', $val) . '))';
                         }
                     } else {
                         $val = intval($val);
                         if ($val > 0) {
                             $arSqlSearch[] = '(' . $table . '.GROUP_ID IS NOT NULL AND ' . $table . '.GROUP_ID=\'' . $val . '\')';
                         }
                     }
                     break;
                 case 'COUPON':
                     $match = $matchValueSet && $arFilter[$key . "_EXACT_MATCH"] != "Y" ? "Y" : "N";
                     $arSqlSearch[] = GetFilterQuery("T." . $key, $val, $match);
                     break;
             }
         }
     }
     $obUserFieldsSql = new CUserTypeSQL();
     $obUserFieldsSql->SetEntity("SUPPORT", "T.ID");
     $obUserFieldsSql->SetSelect($arParams["SELECT"]);
     $obUserFieldsSql->SetFilter($arFilter);
     $obUserFieldsSql->SetOrder(array($by => $order));
     if ($by == "s_id") {
         $strSqlOrder = "ORDER BY T.ID";
     } elseif ($by == "s_last_message_date") {
         $strSqlOrder = "ORDER BY T.LAST_MESSAGE_DATE";
     } elseif ($by == "s_site_id" || $by == "s_lid") {
         $strSqlOrder = "ORDER BY T.SITE_ID";
     } elseif ($by == "s_lamp") {
         $strSqlOrder = "ORDER BY LAMP";
     } elseif ($by == "s_is_overdue") {
         $strSqlOrder = "ORDER BY T.IS_OVERDUE";
     } elseif ($by == "s_is_notified") {
         $strSqlOrder = "ORDER BY T.IS_NOTIFIED";
     } elseif ($by == "s_date_create") {
         $strSqlOrder = "ORDER BY T.DATE_CREATE";
     } elseif ($by == "s_timestamp") {
         $strSqlOrder = "ORDER BY T.TIMESTAMP_X";
     } elseif ($by == "s_date_close") {
         $strSqlOrder = "ORDER BY T.DATE_CLOSE";
     } elseif ($by == "s_owner") {
         $strSqlOrder = "ORDER BY T.OWNER_USER_ID";
     } elseif ($by == "s_modified_by") {
         $strSqlOrder = "ORDER BY T.MODIFIED_USER_ID";
     } elseif ($by == "s_title") {
         $strSqlOrder = "ORDER BY T.TITLE ";
     } elseif ($by == "s_responsible") {
         $strSqlOrder = "ORDER BY T.RESPONSIBLE_USER_ID";
     } elseif ($by == "s_messages") {
         $strSqlOrder = "ORDER BY T.MESSAGES";
     } elseif ($by == "s_category") {
         $strSqlOrder = "ORDER BY T.CATEGORY_ID";
     } elseif ($by == "s_criticality") {
         $strSqlOrder = "ORDER BY T.CRITICALITY_ID";
     } elseif ($by == "s_sla") {
         $strSqlOrder = "ORDER BY T.SLA_ID";
     } elseif ($by == "s_status") {
         $strSqlOrder = "ORDER BY T.STATUS_ID";
     } elseif ($by == "s_difficulty") {
         $strSqlOrder = "ORDER BY T.DIFFICULTY_ID";
     } elseif ($by == "s_problem_time") {
         $strSqlOrder = "ORDER BY T.PROBLEM_TIME";
     } elseif ($by == "s_mark") {
         $strSqlOrder = "ORDER BY T.MARK_ID";
     } elseif ($by == "s_online") {
         $strSqlOrder = "ORDER BY USERS_ONLINE";
     } elseif ($by == "s_support_comments") {
         $strSqlOrder = "ORDER BY T.SUPPORT_COMMENTS";
     } elseif ($by == "s_auto_close_days_left") {
         $strSqlOrder = "ORDER BY AUTO_CLOSE_DAYS_LEFT";
     } elseif ($by == 's_coupon') {
         $strSqlOrder = 'ORDER BY T.COUPON';
     } elseif ($by == 's_deadline') {
         $strSqlOrder = 'ORDER BY T.SUPPORT_DEADLINE';
     } elseif ($s = $obUserFieldsSql->GetOrder($by)) {
         $strSqlOrder = "ORDER BY " . strtoupper($s);
     } else {
         $by = "s_default";
         $strSqlOrder = "ORDER BY IS_SUPER_TICKET DESC, T.IS_OVERDUE DESC, T.IS_NOTIFIED DESC, T.LAST_MESSAGE_DATE";
     }
     if ($order != "asc") {
         $strSqlOrder .= " desc ";
         $order = "desc";
     }
     $arSqlSearch[] = $obUserFieldsSql->GetFilter();
     if ($getUserName == "Y") {
         $u_select = "\n\t\t\t\t,\n\t\t\t\tUO.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tOWNER_LOGIN,\n\t\t\t\tUO.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tOWNER_EMAIL,\n\t\t\t\tconcat(ifnull(UO.NAME,''),' ',ifnull(UO.LAST_NAME,''))\t\tOWNER_NAME,\n\t\t\t\tUR.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tRESPONSIBLE_LOGIN,\n\t\t\t\tUR.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tRESPONSIBLE_EMAIL,\n\t\t\t\tconcat(ifnull(UR.NAME,''),' ',ifnull(UR.LAST_NAME,''))\t\tRESPONSIBLE_NAME,\n\t\t\t\tUM.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_BY_LOGIN,\n\t\t\t\tUM.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_BY_EMAIL,\n\t\t\t\tconcat(ifnull(UM.NAME,''),' ',ifnull(UM.LAST_NAME,''))\t\tMODIFIED_BY_NAME,\n\t\t\t\tUM.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_LOGIN,\n\t\t\t\tUM.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tMODIFIED_EMAIL,\n\t\t\t\tconcat(ifnull(UM.NAME,''),' ',ifnull(UM.LAST_NAME,''))\t\tMODIFIED_NAME,\n\t\t\t\tUL.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tLAST_MESSAGE_LOGIN,\n\t\t\t\tUL.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tLAST_MESSAGE_EMAIL,\n\t\t\t\tconcat(ifnull(UL.NAME,''),' ',ifnull(UL.LAST_NAME,''))\t\tLAST_MESSAGE_NAME,\n\t\t\t\tUC.LOGIN\t\t\t\t\t\t\t\t\t\t\t\t\tCREATED_LOGIN,\n\t\t\t\tUC.EMAIL\t\t\t\t\t\t\t\t\t\t\t\t\tCREATED_EMAIL,\n\t\t\t\tconcat(ifnull(UC.NAME,''),' ',ifnull(UC.LAST_NAME,''))\t\tCREATED_NAME\n\t\t\t";
         $u_join = "\n\t\t\tLEFT JOIN b_user UO ON (UO.ID = T.OWNER_USER_ID)\n\t\t\tLEFT JOIN b_user UR ON (UR.ID = T.RESPONSIBLE_USER_ID)\n\t\t\tLEFT JOIN b_user UM ON (UM.ID = T.MODIFIED_USER_ID)\n\t\t\tLEFT JOIN b_user UL ON (UL.ID = T.LAST_MESSAGE_USER_ID)\n\t\t\tLEFT JOIN b_user UC ON (UC.ID = T.CREATED_USER_ID)\n\t\t\t";
     }
     if ($getExtraNames == "Y") {
         $d_select = "\n\t\t\t\t,\n\t\t\t\tDC.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_NAME,\n\t\t\t\tDC.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_DESC,\n\t\t\t\tDC.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tCATEGORY_SID,\n\t\t\t\tDK.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_NAME,\n\t\t\t\tDK.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_DESC,\n\t\t\t\tDK.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tCRITICALITY_SID,\n\t\t\t\tDS.NAME\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_NAME,\n\t\t\t\tDS.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_DESC,\n\t\t\t\tDS.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATUS_SID,\n\t\t\t\tDM.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_NAME,\n\t\t\t\tDM.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_DESC,\n\t\t\t\tDM.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tMARK_SID,\n\t\t\t\tDSR.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_NAME,\n\t\t\t\tDSR.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_DESC,\n\t\t\t\tDSR.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tSOURCE_SID,\n\t\t\t\tDD.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_NAME,\n\t\t\t\tDD.DESCR\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_DESC,\n\t\t\t\tDD.SID\t\t\t\t\t\t\t\t\t\t\t\t\t\tDIFFICULTY_SID,\n\t\t\t\tSLA.NAME\t\t\t\t\t\t\t\t\t\t\t\t\tSLA_NAME\n\t\t\t";
         $d_join = "\n\t\t\tLEFT JOIN b_ticket_dictionary DC ON (DC.ID = T.CATEGORY_ID and DC.C_TYPE = 'C')\n\t\t\tLEFT JOIN b_ticket_dictionary DK ON (DK.ID = T.CRITICALITY_ID and DK.C_TYPE = 'K')\n\t\t\tLEFT JOIN b_ticket_dictionary DS ON (DS.ID = T.STATUS_ID and DS.C_TYPE = 'S')\n\t\t\tLEFT JOIN b_ticket_dictionary DM ON (DM.ID = T.MARK_ID and DM.C_TYPE = 'M')\n\t\t\tLEFT JOIN b_ticket_dictionary DSR ON (DSR.ID = T.SOURCE_ID and DSR.C_TYPE = 'SR')\n\t\t\tLEFT JOIN b_ticket_dictionary DD ON (DD.ID = T.DIFFICULTY_ID and DD.C_TYPE = 'D')\n\t\t\tLEFT JOIN b_ticket_sla SLA ON (SLA.ID = T.SLA_ID)\n\t\t\t";
     }
     if (strlen($siteID) > 0) {
         $dates_select = "\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "FULL", $siteID, true) . "\tDATE_CREATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "FULL", $siteID, true) . "\tTIMESTAMP_X,\n\t\t\t\t" . $DB->DateToCharFunction("T.LAST_MESSAGE_DATE", "FULL", $siteID, true) . "\tLAST_MESSAGE_DATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "FULL", $siteID, true) . "\tDATE_CLOSE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "SHORT", $siteID, true) . "\tDATE_CREATE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "SHORT", $siteID, true) . "\tTIMESTAMP_X_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "SHORT", $siteID, true) . "\tDATE_CLOSE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.SUPPORT_DEADLINE", "FULL", $siteID, true) . "\tSUPPORT_DEADLINE,\n\t\t\t\t" . $DB->DateToCharFunction("ADDDATE(T.TIMESTAMP_X, INTERVAL T.AUTO_CLOSE_DAYS DAY)", "FULL", $siteID, true) . "\tAUTO_CLOSE_DATE\n\t\t\t";
     } else {
         $dates_select = "\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "FULL") . "\t\tDATE_CREATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "FULL") . "\t\tTIMESTAMP_X,\n\t\t\t\t" . $DB->DateToCharFunction("T.LAST_MESSAGE_DATE", "FULL") . "\tLAST_MESSAGE_DATE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "FULL") . "\t\tDATE_CLOSE,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CREATE", "SHORT") . "\tDATE_CREATE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.TIMESTAMP_X", "SHORT") . "\tTIMESTAMP_X_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.DATE_CLOSE", "SHORT") . "\t\tDATE_CLOSE_SHORT,\n\t\t\t\t" . $DB->DateToCharFunction("T.SUPPORT_DEADLINE", "FULL") . "\tSUPPORT_DEADLINE,\n\t\t\t\t" . $DB->DateToCharFunction("ADDDATE(T.TIMESTAMP_X, INTERVAL T.AUTO_CLOSE_DAYS DAY)", "FULL") . "\tAUTO_CLOSE_DATE\n\t\t\t";
     }
     $ugroupJoin = '';
     $strSqlSearchUser = '';
     if ($bJoinSupportTeamTbl || !($bAdmin == 'Y' || $bDemo == 'Y') && $bSupportTeam == 'Y') {
         $ugroupJoin .= "\n\t\t\t\tLEFT JOIN b_ticket_user_ugroup UGS ON (UGS.USER_ID = T.RESPONSIBLE_USER_ID) ";
     }
     if ($bJoinClientTbl || !($bAdmin == 'Y' || $bDemo == 'Y') && $bSupportClient == 'Y') {
         $ugroupJoin .= "\n\t\t\t\tLEFT JOIN b_ticket_user_ugroup UGC ON (UGC.USER_ID = T.OWNER_USER_ID) ";
     }
     if (!($bAdmin == 'Y' || $bDemo == 'Y')) {
         $strSqlSearchUser = "******";
         if ($bSupportTeam == 'Y') {
             $strSqlSearchUser .= " OR (UGS2.USER_ID IS NOT NULL AND UGS2.USER_ID='{$uid}' AND UUS.IS_TEAM_GROUP IS NOT NULL AND UUS.IS_TEAM_GROUP='Y')";
             $ugroupJoin .= "\n\t\t\t\t\tLEFT JOIN b_ticket_user_ugroup UGS2 ON (UGS2.GROUP_ID = UGS.GROUP_ID AND UGS2.CAN_VIEW_GROUP_MESSAGES = 'Y')\n\t\t\t\t\tLEFT JOIN b_ticket_ugroups UUS ON (UUS.ID = UGS.GROUP_ID) ";
         } elseif ($bSupportClient == 'Y') {
             $strSqlSearchUser .= " OR (UGC2.USER_ID IS NOT NULL AND UGC2.USER_ID='{$uid}' AND UUC.IS_TEAM_GROUP IS NOT NULL AND UUC.IS_TEAM_GROUP<>'Y')";
             $ugroupJoin .= "\n\t\t\t\t\tLEFT JOIN b_ticket_user_ugroup UGC2 ON (UGC2.GROUP_ID = UGC.GROUP_ID AND UGC2.CAN_VIEW_GROUP_MESSAGES = 'Y')\n\t\t\t\t\tLEFT JOIN b_ticket_ugroups UUC ON (UUC.ID = UGC.GROUP_ID) ";
         }
         $strSqlSearchUser .= ')';
         $arSqlSearch[] = $strSqlSearchUser;
     }
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $onlineInterval = intval(COption::GetOptionString("support", "ONLINE_INTERVAL"));
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tT.*,\n\t\t\t\tT.SITE_ID,\n\t\t\t\tT.SITE_ID\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLID,\n\t\t\t\t{$dates_select},\n\t\t\t\tUNIX_TIMESTAMP(T.DATE_CLOSE)-UNIX_TIMESTAMP(T.DATE_CREATE)\t\t\t\t\t\t\tTICKET_TIME,\n\t\t\t\tTO_DAYS(ADDDATE(T.TIMESTAMP_X, INTERVAL T.AUTO_CLOSE_DAYS DAY))-TO_DAYS(now())\t\tAUTO_CLOSE_DAYS_LEFT,\n\t\t\t\tcount(distinct TN.USER_ID)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUSERS_ONLINE,\n\t\t\t\tif(T.COUPON IS NOT NULL, 1, 0)\t\t\t\t\t\t\t\t\t\t\t\t\t\tIS_SUPER_TICKET,\n\t\t\t\t{$lamp}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLAMP\n\t\t\t\t{$d_select}\n\t\t\t\t{$u_select}\n\t\t\t\t" . $obUserFieldsSql->GetSelect() . "\n\t\t\tFROM\n\t\t\t\tb_ticket T\n\t\t\tLEFT JOIN b_ticket_online TN ON (TN.TICKET_ID = T.ID and TN.TIMESTAMP_X >= DATE_ADD(now(), INTERVAL - {$onlineInterval} SECOND))\n\t\t\t{$u_join}\n\t\t\t{$d_join}\n\t\t\t{$messJoin}\n\t\t\t{$ugroupJoin}\n\t\t\t\t" . $obUserFieldsSql->GetJoin("T.ID") . "\n\t\t\tWHERE\n\t\t\t{$strSqlSearch}\n\t\t\tGROUP BY\n\t\t\t\tT.ID\n\t\t\t{$strSqlOrder}\n\t\t\t";
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     $res->SetUserFields($USER_FIELD_MANAGER->GetUserFields("SUPPORT"));
     $isFiltered = IsFiltered($strSqlSearch);
     return $res;
 }
Ejemplo n.º 4
0
&dm=<?php 
    echo $DIAMETER;
    ?>
"></td>
		<td width="100%" valign="top"><table cellspacing=0 cellpadding=1 width="100%">
				<?php 
    if (!is_array($arrAnswers)) {
        $arrAnswers = array();
    }
    usort($arrAnswers, create_function('$v1,$v2', 'if ($v1[\'COUNTER\']>$v2[\'COUNTER\']) return -1; elseif ($v1[\'COUNTER\']<$v2[\'COUNTER\']) return 1;'));
    $sum = $total = 0;
    $arr = array();
    while (list(, $arAnswer) = each($arrAnswers)) {
        $total++;
        $sum += $arAnswer["COUNTER"];
        $arr[] = array("ORIGINAL_COLOR" => TrimEx($arAnswer["COLOR"], "#"), "COUNTER" => $arAnswer["COUNTER"], "MESSAGE" => $arAnswer["MESSAGE"]);
    }
    $color = "";
    reset($arr);
    while (list($key, $ar) = each($arr)) {
        $ar["PROCENT"] = $sum > 0 ? number_format($ar["COUNTER"] * 100 / $sum, 2, ',', '') : 0;
        $color = GetNextRGB($color, $total);
        $ar["SHOW_COLOR"] = strlen($ar["ORIGINAL_COLOR"]) <= 0 ? $color : $ar["ORIGINAL_COLOR"];
        $arr[$key] = $ar;
    }
    reset($arr);
    foreach ($arr as $ar) {
        ?>
				<tr>
					<td  valign="top"><table cellspacing="0" cellpadding="0">
						<tr>
Ejemplo n.º 5
0
 function Set_sendMails($nf, $v, $arFields)
 {
     $I_Email = null;
     $U_Email = null;
     if (!$v->isNew) {
         $U_Email = "Y";
     } else {
         $I_Email = "Y";
     }
     IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/support/classes/general/messages.php", $v->arrSite["LANGUAGE_ID"]);
     $mf = self::GetCSupportTableFields("EventFields");
     $mf->ADMIN_EDIT_URL = "/bitrix/admin/ticket_edit.php";
     $mf->LANGUAGE = $v->arrSite["LANGUAGE_ID"];
     $mf->LANGUAGE_ID = $v->arrSite["LANGUAGE_ID"];
     $arrSet = array("ID" => "ID", "DATE_CREATE" => "DATE_CREATE", "TIMESTAMP" => "TIMESTAMP_X", "DATE_CLOSE" => "DATE_CLOSE", "TITLE" => "TITLE", "CATEGORY" => "CATEGORY_NAME", "CRITICALITY" => "CRITICALITY_NAME", "DIFFICULTY" => "DIFFICULTY_NAME", "STATUS" => "STATUS_NAME", "SLA" => "SLA_NAME", "OWNER_USER_ID" => "OWNER_USER_ID", "OWNER_GUEST_ID" => "OWNER_GUEST_ID", "OWNER_SID" => "OWNER_SID", "OWNER_USER_NAME" => "OWNER_NAME", "OWNER_USER_LOGIN" => "OWNER_LOGIN", "OWNER_USER_EMAIL" => "OWNER_EMAIL", "RESPONSIBLE_USER_ID" => "RESPONSIBLE_USER_ID", "RESPONSIBLE_USER_NAME" => "RESPONSIBLE_NAME", "RESPONSIBLE_USER_LOGIN" => "RESPONSIBLE_LOGIN", "RESPONSIBLE_USER_EMAIL" => "RESPONSIBLE_EMAIL", "CREATED_USER_ID" => "CREATED_USER_ID", "CREATED_GUEST_ID" => "CREATED_GUEST_ID", "CREATED_USER_LOGIN" => "CREATED_LOGIN", "CREATED_USER_EMAIL" => "CREATED_EMAIL", "CREATED_USER_NAME" => "CREATED_NAME");
     if (!$v->isNew) {
         $arrSet["MODIFIED_USER_ID"] = "MODIFIED_USER_ID";
         $arrSet["MODIFIED_GUEST_ID"] = "MODIFIED_GUEST_ID";
         $arrSet["MODIFIED_USER_LOGIN"] = "******";
         $arrSet["MODIFIED_USER_EMAIL"] = "MODIFIED_EMAIL";
         $arrSet["MODIFIED_USER_NAME"] = "MODIFIED_NAME";
         $arrSet["RATE"] = "MARK_NAME";
         $arrSet["MESSAGES_AMOUNT"] = "MESSAGES";
     }
     $mf->FromArray((array) $nf, $arrSet);
     $arUserIDs = array($mf->OWNER_USER_ID, $mf->CREATED_USER_ID, $mf->MODIFIED_USER_ID, $mf->RESPONSIBLE_USER_ID);
     $arGuestIDs = array($mf->OWNER_GUEST_ID, $mf->CREATED_GUEST_ID, $mf->MODIFIED_GUEST_ID);
     $arStrUsers = CTicket::GetUsersPropertiesArray($arUserIDs, $arGuestIDs);
     // set name, login, email
     $userCategories = array('OWNER', 'RESPONSIBLE', 'CREATED');
     if (!$v->isNew) {
         $userCategories[] = 'MODIFIED';
     }
     foreach ($userCategories as $userCategory) {
         $propertyId = $userCategory . '_USER_ID';
         if ($mf->{$propertyId} > 0 && isset($arStrUsers['arUsers'][$mf->{$propertyId}])) {
             $name = CUser::FormatName(CSite::GetNameFormat(), $arStrUsers['arUsers'][$mf->{$propertyId}], true, true);
             $propertyName = $userCategory . '_USER_NAME';
             $mf->{$propertyName} = $name;
             $propertyLogin = $userCategory . '_USER_LOGIN';
             $mf->{$propertyLogin} = $arStrUsers['arUsers'][$mf->{$propertyId}]['LOGIN'];
             $propertyEmail = $userCategory . '_USER_EMAIL';
             $mf->{$propertyEmail} = $arStrUsers['arUsers'][$mf->{$propertyId}]['EMAIL'];
         }
     }
     $mf->FILES_LINKS = self::Set_getFilesLinks($v->arrFILES, $v->arrSite["LANGUAGE_ID"]);
     $mf->IMAGE_LINK = $mf->FILES_LINKS;
     $mf->MESSAGE_BODY = PrepareTxtForEmail($arFields["MESSAGE"], $v->arrSite["LANGUAGE_ID"], false, false);
     // сформируем email автора
     // Событие: "TICKET_CHANGE_BY_AUTHOR_FOR_AUTHOR"	- #DEFAULT_EMAIL_FROM# -> #OWNER_EMAIL# (Обращение изменено автором (для автора))
     // Событие: "TICKET_CHANGE_BY_SUPPORT_FOR_AUTHOR"	- #DEFAULT_EMAIL_FROM# -> #OWNER_EMAIL# (Обращение изменено сотрудником техподдержки (для автора))
     // Событие: "TICKET_NEW_FOR_AUTHOR"					- #DEFAULT_EMAIL_FROM# -> #OWNER_EMAIL# (Новое обращение (для автора))
     $ownerEmail = "";
     if ($mf->OWNER_USER_ID > 0 && isset($arStrUsers["arUsers"][$mf->OWNER_USER_ID])) {
         $ownerEmail = $arStrUsers["arUsers"][$mf->OWNER_USER_ID]["EMAIL"];
     } elseif ($mf->OWNER_GUEST_ID > 0 && isset($arStrUsers["arGuests"][$mf->OWNER_GUEST_ID])) {
         $ownerEmail = $arStrUsers["arGuests"][$mf->OWNER_GUEST_ID]["EMAIL"];
     }
     $arrOwnerEmails = self::EmailsFromStringToArray($mf->OWNER_SID, array($ownerEmail));
     if (intval($mf->OWNER_USER_ID) > 0) {
         $rs = CTicket::GetResponsibleList($mf->OWNER_USER_ID, $I_Email, $U_Email);
         while ($arr0 = $rs->Fetch()) {
             if (strlen($arr0['EMAIL']) > 0) {
                 $arrOwnerEmails[] = $arr0['EMAIL'];
             }
         }
     }
     $mf->OWNER_EMAIL = implode(", ", array_unique($arrOwnerEmails));
     // выбираем административные email'ы
     $arrAdminEMails = CTicket::GetAdminEmails();
     if (!is_array($arrAdminEMails)) {
         $arrAdminEMails = array();
     }
     TrimArr($arrAdminEMails);
     // сформируем email техподдержки
     // Событие: "TICKET_OVERDUE_REMINDER"				- #DEFAULT_EMAIL_FROM# -> #SUPPORT_EMAIL# (Напоминание о необходимости ответа (для техподдержки))
     // Событие: "TICKET_CHANGE_FOR_TECHSUPPORT"			- #DEFAULT_EMAIL_FROM# -> #SUPPORT_EMAIL# (Изменения в обращении (для техподдержки))
     // Событие: "TICKET_NEW_FOR_TECHSUPPORT"			- #DEFAULT_EMAIL_FROM# -> #SUPPORT_EMAIL# (Новое обращение (для техподдержки))
     $arrSupportEmails = array();
     if ($mf->RESPONSIBLE_USER_ID > 0 && isset($arStrUsers["arUsers"][$mf->RESPONSIBLE_USER_ID])) {
         $arrSupportEmails[] = $arStrUsers["arUsers"][$mf->RESPONSIBLE_USER_ID]["EMAIL"];
         // из группы ответсвенного, выбираем всех пользователей кто имеет доступ к рассылке
         $rs = CTicket::GetResponsibleList($mf->RESPONSIBLE_USER_ID, $I_Email, $U_Email, "Y");
         while ($arr0 = $rs->Fetch()) {
             if (strlen($arr0['EMAIL']) > 0) {
                 $arrSupportEmails[] = $arr0['EMAIL'];
             }
         }
     }
     if (count($arrSupportEmails) <= 0) {
         $arrSupportEmails = $arrAdminEMails;
     }
     if (count($arrSupportEmails) <= 0) {
         $se = COption::GetOptionString("main", "email_from", "");
         if (strlen($se) > 0) {
             $arrSupportEmails[] = $se;
         }
     }
     TrimArr($arrSupportEmails);
     $mf->SUPPORT_EMAIL = count($arrSupportEmails) > 0 ? TrimEx(implode(",", array_unique($arrSupportEmails)), ",") : "";
     // удалим продублированные адреса из макроса #SUPPORT_ADMIN_EMAIL#
     if (count($arrSupportEmails) > 0) {
         foreach ($arrSupportEmails as $e) {
             unset($arrAdminEMails[$e]);
         }
     }
     $mf->SUPPORT_ADMIN_EMAIL = count($arrAdminEMails) > 0 ? TrimEx(implode(",", $arrAdminEMails), ",") : "";
     if (array_key_exists('PUBLIC_EDIT_URL', $arFields) && strlen($arFields['PUBLIC_EDIT_URL']) > 0) {
         $mf->PUBLIC_EDIT_URL = $arFields['PUBLIC_EDIT_URL'];
     } else {
         $peurl = COption::GetOptionString("support", "SUPPORT_DIR");
         $peurl = str_replace("#LANG_DIR#", $v->arrSite["DIR"], $peurl);
         // совместимость
         $peurl = str_replace("#SITE_DIR#", $v->arrSite["DIR"], $peurl);
         $peurl = str_replace("\\", "/", $peurl);
         $peurl = str_replace("//", "/", $peurl);
         $peurl = TrimEx($peurl, "/");
         $mf->PUBLIC_EDIT_URL = "/" . $peurl . "/" . COption::GetOptionString("support", "SUPPORT_EDIT");
     }
     $mf->SUPPORT_COMMENTS = PrepareTxtForEmail($arFields["SUPPORT_COMMENTS"], $v->arrSite["LANGUAGE_ID"]);
     if (strlen($mf->SUPPORT_COMMENTS) > 0) {
         $mf->SUPPORT_COMMENTS = "\n\n" . $mf->SUPPORT_COMMENTS . "\n";
     }
     $mf->SOURCE = strlen($nf->SOURCE_NAME) <= 0 ? "" : "[" . $nf->SOURCE_NAME . "] ";
     $oUID = intval($mf->OWNER_USER_ID);
     $oGID = intval($mf->OWNER_GUEST_ID);
     if ($oGID > 0) {
         $mf->OWNER_TEXT = $arStrUsers["arGuests"][$oGID]["HTML_NAME_S"];
         if ($oUID > 0) {
             $mf->OWNER_TEXT .= self::addSupportText($oUID);
         }
     } elseif ($oUID > 0) {
         $mf->OWNER_TEXT = $arStrUsers["arUsers"][$oUID]["HTML_NAME_S"];
         $mf->OWNER_TEXT .= self::addSupportText($oUID);
     }
     if (strlen(trim($mf->OWNER_SID)) > 0 && $mf->OWNER_SID != null) {
         $mf->OWNER_TEXT = " / " . $mf->OWNER_TEXT;
     }
     if ($nf->CREATED_MODULE_NAME == "support" || strlen($nf->CREATED_MODULE_NAME) <= 0) {
         $cUID = intval($mf->CREATED_USER_ID);
         $cGID = intval($mf->CREATED_GUEST_ID);
         if ($cGID > 0) {
             $mf->CREATED_TEXT = $arStrUsers["arGuests"][$cGID]["HTML_NAME_S"];
         } elseif ($cUID > 0) {
             $mf->CREATED_TEXT = $arStrUsers["arUsers"][$cUID]["HTML_NAME_S"];
         }
     } else {
         $mf->CREATED_MODULE_NAME = "[" . $nf->CREATED_MODULE_NAME . "]";
     }
     $rUID = intval($mf->RESPONSIBLE_USER_ID);
     if ($rUID > 0) {
         $mf->RESPONSIBLE_TEXT = $arStrUsers["arUsers"][$rUID]["HTML_NAME_S"];
         $mf->RESPONSIBLE_TEXT .= self::addSupportText($rUID);
     }
     /*
     if($mf->OWNER_USER_ID > 0 || strlen(trim($mf->OWNER_USER_LOGIN)) > 0)
     {
     	$mf->OWNER_TEXT = "[" . $mf->OWNER_USER_ID . "] (" . $mf->OWNER_USER_LOGIN . ") " . $mf->OWNER_USER_NAME;
     	if(strlen(trim($mf->OWNER_SID)) > 0 && $mf->OWNER_SID != null) $mf->OWNER_TEXT = " / " . $mf->OWNER_TEXT;
     	$mf->OWNER_TEXT .= self::addSupportText($mf->OWNER_USER_ID);
     }
     
     if($nf->CREATED_MODULE_NAME == "support")
     {
     	$mf->CREATED_MODULE_NAME = "";
     	if($mf->CREATED_USER_ID > 0)
     	{
     		$mf->CREATED_TEXT = "[" . $mf->CREATED_USER_ID . "] (" . $mf->CREATED_USER_LOGIN . ") " . $mf->CREATED_USER_NAME . self::addSupportText($mf->CREATED_USER_ID);
     	}
     }
     else
     {
     	$mf->CREATED_MODULE_NAME = "[" . $nf->CREATED_MODULE_NAME . "]";
     }
     
     if($mf->RESPONSIBLE_USER_ID > 0)
     {
     	$mf->RESPONSIBLE_TEXT = "[" . $mf->RESPONSIBLE_USER_ID . "] (" . $nf->RESPONSIBLE_LOGIN . ") " . $nf->RESPONSIBLE_NAME;
     	$mf->RESPONSIBLE_TEXT .= self::addSupportText($mf->RESPONSIBLE_USER_ID);
     }
     */
     if (!$v->isNew) {
         /*
         if($nf->MODIFIED_MODULE_NAME == "support" && strlen($nf->MODIFIED_MODULE_NAME) > 0)
         {
         	$mf->MODIFIED_MODULE_NAME = "";
         	if($mf->MODIFIED_USER_ID > 0)
         	{
         		$mf->MODIFIED_TEXT = "[" . $mf->MODIFIED_USER_ID . "] (" . $mf->MODIFIED_USER_LOGIN . ") " . $mf->MODIFIED_USER_NAME;
         		$mf->MODIFIED_TEXT .= self::addSupportText($mf->MODIFIED_USER_ID);
         	}
         }
         else $mf->MODIFIED_MODULE_NAME = "[" . $nf->MODIFIED_MODULE_NAME . "]";
         */
         if ($nf->MODIFIED_MODULE_NAME == "support" || strlen($nf->MODIFIED_MODULE_NAME) <= 0) {
             $rUID = intval($mf->MODIFIED_USER_ID);
             $rGID = intval($mf->MODIFIED_GUEST_ID);
             if ($rGID > 0) {
                 $mf->MODIFIED_TEXT = $arStrUsers["arGuests"][$rGID]["HTML_NAME_S"];
                 if ($rUID > 0) {
                     $mf->MODIFIED_TEXT .= self::addSupportText($rUID);
                 }
             } elseif ($rUID > 0) {
                 $mf->MODIFIED_TEXT = $arStrUsers["arUsers"][$rUID]["HTML_NAME_S"];
                 $mf->MODIFIED_TEXT .= self::addSupportText($rUID);
             }
         } else {
             $mf->MODIFIED_MODULE_NAME = "[" . $nf->MODIFIED_MODULE_NAME . "]";
         }
         $mf->MESSAGE_SOURCE = "";
         if ($rsSource = CTicketDictionary::GetByID($arFields["MESSAGE_SOURCE_ID"])) {
             $arSource = $rsSource->Fetch();
             $mf->MESSAGE_SOURCE = array_key_exists("NAME", $arSource) && strlen($arSource["NAME"]) > 0 ? "[" . $arSource["NAME"] . "] " : "";
         }
         if ((strlen(trim($arFields["MESSAGE_AUTHOR_SID"])) > 0 || intval($arFields["MESSAGE_AUTHOR_USER_ID"]) > 0) && $v->bSupportTeam) {
             $mf->MESSAGE_AUTHOR_USER_ID = $arFields["MESSAGE_AUTHOR_USER_ID"];
             $mf->MESSAGE_AUTHOR_SID = $arFields["MESSAGE_AUTHOR_SID"];
         } else {
             $mf->MESSAGE_AUTHOR_USER_ID = $v->uid;
         }
         $arMA = array();
         if ($rsMA = CUser::GetByID($mf->MESSAGE_AUTHOR_USER_ID)) {
             $arMA = $rsMA->Fetch();
         }
         if ($mf->MESSAGE_AUTHOR_USER_ID > 0 || strlen(trim($arMA["LOGIN"])) > 0) {
             $mf->MESSAGE_AUTHOR_TEXT = "[" . $mf->MESSAGE_AUTHOR_USER_ID . "] (" . $arMA["LOGIN"] . ") " . $arMA["NAME"] . " " . $arMA["LAST_NAME"];
             if (strlen(trim($arFields["MESSAGE_AUTHOR_SID"])) > 0) {
                 $mf->MESSAGE_AUTHOR_TEXT = " / " . $mf->MESSAGE_AUTHOR_TEXT;
             }
             if ($mf->MESSAGE_AUTHOR_USER_ID > 0) {
                 $mf->MESSAGE_AUTHOR_TEXT .= self::addSupportText($mf->MESSAGE_AUTHOR_USER_ID);
             }
         }
         if (strlen(trim($arMA["NAME"])) > 0 || strlen(trim($arMA["LAST_NAME"])) > 0) {
             $mf->MESSAGE_AUTHOR_USER_NAME = trim($arMA["NAME"]) . " " . trim($arMA["LAST_NAME"]);
         }
         if (strlen(trim($arMA["LOGIN"])) > 0) {
             $mf->MESSAGE_AUTHOR_USER_LOGIN = $arMA["LOGIN"];
         }
         if (strlen(trim($arMA["EMAIL"])) > 0) {
             $mf->MESSAGE_AUTHOR_USER_EMAIL = $arMA["EMAIL"];
         }
         $mf->MESSAGE_HEADER = str_repeat("=", 23) . " " . GetMessage("SUP_MAIL_MESSAGE") . " " . str_repeat("=", 34);
     }
     $mf->SPAM_MARK = "";
     if (strlen($nf->IS_SPAM) > 0) {
         if ($nf->IS_SPAM == "Y") {
             $mf->SPAM_MARK = "\n" . GetMessage("SUP_EXACTLY_SPAM") . "\n";
         } else {
             $mf->SPAM_MARK = "\n" . GetMessage("SUP_POSSIBLE_SPAM") . "\n";
         }
     }
     self::Set_WriteLog($nf, $v, $mf);
     //$v  +change, +change_hidden
     if (!$v->isNew) {
         $mf->MESSAGE_FOOTER = str_repeat("=", strlen($mf->MESSAGE_HEADER));
     }
     if ($v->isNew && $v->bActiveCoupon) {
         $mf->COUPON = $v->V_COUPON;
     }
     $arEventFields_author = $mf->ToArray(CSupportTableFields::ALL);
     //, array(CSupportTableFields::NOT_NULL)
     $arEventFields_support = $arEventFields_author;
     // отсылаем письмо автору
     if ($v->SEND_EMAIL_TO_AUTHOR == "Y" && ($v->isNew || strlen($v->change) > 0)) {
         $EventType = "TICKET_NEW_FOR_AUTHOR";
         if (!$v->isNew) {
             // HIDDEN
             if ($arFields["HIDDEN"] == "Y") {
                 $arrUnsetHidden = array("MESSAGE_BODY", "IMAGE_LINK");
                 foreach ($arrUnsetHidden as $value) {
                     $arEventFields_author[$value] = "";
                 }
             }
             $EventType = "TICKET_CHANGE_BY_AUTHOR_FOR_AUTHOR";
             if (CTicket::IsSupportTeam($mf->MESSAGE_AUTHOR_USER_ID) || CTicket::IsAdmin($mf->MESSAGE_AUTHOR_USER_ID)) {
                 $EventType = "TICKET_CHANGE_BY_SUPPORT_FOR_AUTHOR";
             }
         }
         $arEventFields_author = CTicket::ExecuteEvents('OnBeforeSendMailToAuthor', $arEventFields_author, $v->isNew, $EventType);
         if ($arEventFields_author) {
             CEvent::Send($EventType, $v->arrSite["ID"], $arEventFields_author);
         }
     }
     // отсылаем письмо техподдержке
     if ($v->SEND_EMAIL_TO_TECHSUPPORT == "Y" && ($v->isNew || strlen($v->change) > 0 || strlen($v->change_hidden) > 0)) {
         $EventType = "TICKET_NEW_FOR_TECHSUPPORT";
         if (!$v->isNew) {
             $arEventFields_support["WHAT_CHANGE"] .= $v->change_hidden;
             $EventType = "TICKET_CHANGE_FOR_TECHSUPPORT";
         }
         $arEventFields_support = CTicket::ExecuteEvents('OnBeforeSendMailToSupport', $arEventFields_support, $v->isNew);
         if ($arEventFields_support) {
             CEvent::Send($EventType, $v->arrSite["ID"], $arEventFields_support);
         }
     }
 }
Ejemplo n.º 6
0
 function Set($arFields, $OLD_SID, $CHECK_RIGHTS = "Y")
 {
     $err_mess = CAdvType_all::err_mess() . "<br>Function: Set<br>Line: ";
     global $DB, $USER;
     $SID = false;
     $OLD_SID = trim($OLD_SID);
     if (CAdvType::CheckFields($arFields, $OLD_SID, $CHECK_RIGHTS)) {
         $arFields_i = array();
         $arrKeys = array_keys($arFields);
         if (in_array("SID", $arrKeys)) {
             $arFields_i["SID"] = "'" . $DB->ForSql($arFields["SID"], 255) . "'";
         }
         if (in_array("ACTIVE", $arrKeys) && ($arFields["ACTIVE"] == "Y" || $arFields["ACTIVE"] == "N")) {
             $arFields_i["ACTIVE"] = "'" . $arFields["ACTIVE"] . "'";
         }
         if (in_array("SORT", $arrKeys)) {
             $arFields_i["SORT"] = "'" . intval($arFields["SORT"]) . "'";
         }
         if (in_array("NAME", $arrKeys)) {
             $arFields_i["NAME"] = "'" . $DB->ForSql($arFields["NAME"], 255) . "'";
         }
         if (in_array("DESCRIPTION", $arrKeys)) {
             $arFields_i["DESCRIPTION"] = "'" . $DB->ForSql($arFields["DESCRIPTION"], 2000) . "'";
         }
         if (count($arFields_i) > 0) {
             if (strlen($OLD_SID) > 0) {
                 if (in_array("DATE_MODIFY", $arrKeys) && CheckDateTime($arFields["DATE_MODIFY"])) {
                     $arFields_i["DATE_MODIFY"] = $DB->CharToDateFunction($arFields["DATE_MODIFY"]);
                 } else {
                     $arFields_i["DATE_MODIFY"] = $DB->GetNowFunction();
                 }
                 if (in_array("MODIFIED_BY", $arrKeys)) {
                     $arFields_i["MODIFIED_BY"] = intval($arFields["MODIFIED_BY"]);
                 } else {
                     $arFields_i["MODIFIED_BY"] = $USER->GetID();
                 }
                 $str = "";
                 while (list($field, $value) = each($arFields_i)) {
                     if (strlen($value) <= 0) {
                         $str .= "{$field} = '', ";
                     } else {
                         $str .= "{$field} = {$value}, ";
                     }
                 }
                 $str = TrimEx($str, ",");
                 $strSql = "UPDATE b_adv_type SET " . $str . " WHERE SID='" . $DB->ForSql($OLD_SID, 255) . "'";
                 $DB->Query($strSql, false, $err_mess . __LINE__);
                 if (in_array("SID", $arrKeys)) {
                     $SID = $arFields["SID"];
                     // если SID изменился то
                     if ($arFields["SID"] != $OLD_SID) {
                         // обновим тип у баннеров
                         $arF = array("TYPE_SID" => "'" . $DB->ForSql($arFields["SID"], 255) . "'");
                         $DB->Update("b_adv_banner", $arF, "WHERE TYPE_SID='" . $DB->ForSql($OLD_SID, 255) . "'", $err_mess . __LINE__);
                         // обновим тип у баннеров
                         $arF = array("TYPE_SID" => "'" . $DB->ForSql($arFields["SID"], 255) . "'");
                         $DB->Update("b_adv_contract_2_type", $arF, "WHERE TYPE_SID='" . $DB->ForSql($OLD_SID, 255) . "'", $err_mess . __LINE__);
                     }
                 } else {
                     $SID = $OLD_SID;
                 }
             } elseif (strlen($arFields_i["SID"]) > 0) {
                 if (in_array("DATE_CREATE", $arrKeys) && CheckDateTime($arFields["DATE_CREATE"])) {
                     $arFields_i["DATE_CREATE"] = $DB->CharToDateFunction($arFields["DATE_CREATE"]);
                 } else {
                     $arFields_i["DATE_CREATE"] = $DB->GetNowFunction();
                 }
                 if (in_array("CREATED_BY", $arrKeys)) {
                     $arFields_i["CREATED_BY"] = intval($arFields["CREATED_BY"]);
                 } else {
                     $arFields_i["CREATED_BY"] = $USER->GetID();
                 }
                 if (in_array("DATE_MODIFY", $arrKeys) && CheckDateTime($arFields["DATE_MODIFY"])) {
                     $arFields_i["DATE_MODIFY"] = $DB->CharToDateFunction($arFields["DATE_MODIFY"]);
                 } else {
                     $arFields_i["DATE_MODIFY"] = $DB->GetNowFunction();
                 }
                 if (in_array("MODIFIED_BY", $arrKeys)) {
                     $arFields_i["MODIFIED_BY"] = intval($arFields["MODIFIED_BY"]);
                 } else {
                     $arFields_i["MODIFIED_BY"] = $USER->GetID();
                 }
                 $str1 = $str2 = "";
                 while (list($field, $value) = each($arFields_i)) {
                     $str1 .= $field . ", ";
                     if (strlen($value) <= 0) {
                         $str2 .= "'', ";
                     } else {
                         $str2 .= "{$value}, ";
                     }
                 }
                 $str1 = TrimEx($str1, ",");
                 $str2 = TrimEx($str2, ",");
                 $strSql = "INSERT INTO b_adv_type (" . $str1 . ") VALUES (" . $str2 . ")";
                 $DB->Query($strSql, false, $err_mess . __LINE__);
                 $SID = $arFields["SID"];
             }
         }
     } else {
         $SID = $arFields["SID"];
     }
     return $SID;
 }
Ejemplo n.º 7
0
 public static function GetList($arSort = array(), $arFilter = array())
 {
     global $DB;
     $arSqlSearch = array();
     if (is_array($arFilter)) {
         $filter_keys = array_keys($arFilter);
         for ($i = 0, $ic = count($filter_keys); $i < $ic; $i++) {
             $val = $arFilter[$filter_keys[$i]];
             if (strlen($val) <= 0 || $val == 'NOT_REF') {
                 continue;
             }
             switch (strtoupper($filter_keys[$i])) {
                 case 'ID':
                     $arSqlSearch[] = GetFilterQuery('CS.ID', $val, 'N');
                     break;
                 case 'ENTITY_ID':
                     $arSqlSearch[] = GetFilterQuery('CS.ENTITY_ID', $val);
                     break;
                 case 'STATUS_ID':
                     $arSqlSearch[] = GetFilterQuery('CS.STATUS_ID', $val);
                     break;
                 case 'NAME':
                     $arSqlSearch[] = GetFilterQuery('CS.NAME', $val);
                     break;
                 case 'SORT':
                     $arSqlSearch[] = GetFilterQuery('CS.SORT', $val);
                     break;
                 case 'SYSTEM':
                     $arSqlSearch[] = $val == 'Y' ? "CS.SYSTEM='Y'" : "CS.SYSTEM='N'";
                     break;
             }
         }
     }
     $sOrder = '';
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != 'ASC' ? 'DESC' : 'ASC';
         switch (strtoupper($key)) {
             case 'ID':
                 $sOrder .= ', CS.ID ' . $ord;
                 break;
             case 'ENTITY_ID':
                 $sOrder .= ', CS.ENTITY_ID ' . $ord;
                 break;
             case 'STATUS_ID':
                 $sOrder .= ', CS.STATUS_ID ' . $ord;
                 break;
             case 'NAME':
                 $sOrder .= ', CS.NAME ' . $ord;
                 break;
             case 'SORT':
                 $sOrder .= ', CS.SORT ' . $ord;
                 break;
             case 'SYSTEM':
                 $sOrder .= ', CS.SYSTEM ' . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = 'CS.ID DESC';
     }
     $strSqlOrder = ' ORDER BY ' . TrimEx($sOrder, ',');
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tCS.ID, CS.ENTITY_ID, CS.STATUS_ID, CS.NAME, CS.NAME_INIT, CS.SORT, CS.SYSTEM\n\t\t\tFROM\n\t\t\t\tb_crm_status CS\n\t\t\tWHERE\n\t\t\t{$strSqlSearch}\n\t\t\t{$strSqlOrder}";
     $res = $DB->Query($strSql, false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
     return $res;
 }
Ejemplo n.º 8
0
function i2c_create_db(&$total_reindex, &$reindex_success, &$step_reindex, &$int_prev, $step = 0, $file_name = false, $file_type = false, $file_db = false, $file_idx = false)
{
    $step = intval($step);
    if ($file_name === false) {
        $file_name = IP_DEFAULT_SOURCE_FILENAME;
    }
    if ($file_type === false) {
        $file_type = IP_DEFAULT_SOURCE_TYPE;
    }
    if ($file_db === false) {
        $file_db = IP_DB_FILENAME;
    }
    if ($file_idx === false) {
        $file_idx = IP_IDX_FILENAME;
    }
    $start = getmicrotime();
    $bExtTotal = is_array($total_reindex);
    if ($bExtTotal) {
        $my_total_reindex = $total_reindex[0];
        $fseek = $total_reindex[1];
    } else {
        $fseek = $total_reindex;
        $my_total_reindex = $total_reindex;
    }
    if ($fp = fopen($_SERVER["DOCUMENT_ROOT"] . $file_name, "rb")) {
        if ($fseek <= 0) {
            $mode = "wb";
        } else {
            $mode = "ab";
        }
        $f_db = fopen($_SERVER["DOCUMENT_ROOT"] . $file_db, $mode);
        $f_idx = fopen($_SERVER["DOCUMENT_ROOT"] . $file_idx, $mode);
        $d = 1000000;
        if ($fseek <= 0) {
            fwrite($f_idx, $d . "\n0,0\n");
        }
        $src_db_lines = 0;
        $step_reindex = 0;
        if ($bExtTotal) {
            fseek($fp, $fseek);
        }
        while ($fp > 0 && !feof($fp)) {
            $arr = fgetcsv($fp, 1000, ",");
            if (is_array($arr) && $file_type == "maxmind.com" && !isset($beginIpNum)) {
                while (list($key, $value) = each($arr)) {
                    $value = trim($value);
                    if ($value == "beginIpNum" || $value == "endIpNum" || $value == "countryCode") {
                        ${$value} = $key;
                    }
                }
            }
            $src_db_lines++;
            if (!$bExtTotal) {
                if ($fseek > 0 && $src_db_lines <= $fseek) {
                    continue;
                }
            }
            if ($file_type == "maxmind.com") {
                $ix_beginIpNum = !isset($beginIpNum) ? 2 : intval($beginIpNum);
                $ip_from = TrimEx($arr[$ix_beginIpNum], "\"");
                $ix_endIpNum = !isset($endIpNum) ? 3 : intval($endIpNum);
                $ip_to = TrimEx($arr[$ix_endIpNum], "\"");
                $ip_to = (double) $ip_to;
                if ($ip_to <= 0) {
                    continue;
                }
                $ix_countryCode = !isset($countryCode) ? 4 : intval($countryCode);
                $country_id = TrimEx($arr[$ix_countryCode], "\"");
            } else {
                $ip_from = TrimEx($arr[0], "\"");
                $ip_to = TrimEx($arr[1], "\"");
                $country_id = TrimEx($arr[2], "\"");
            }
            if (strlen($country_id) <= 0 && strlen($country_id) != 2) {
                continue;
            }
            $ip_from_p = str_pad($ip_from, 10, "0", STR_PAD_LEFT);
            $ip_to_p = str_pad($ip_to, 10, "0", STR_PAD_LEFT);
            fwrite($f_db, $ip_from_p . $ip_to_p . $country_id . "\n");
            $step_reindex++;
            $int = floor($ip_from / $d);
            if ($int != $int_prev) {
                fwrite($f_idx, $int . "," . ($my_total_reindex + $step_reindex) . "\n");
            }
            $int_prev = $int;
            if ($step > 0 && getmicrotime() - $start > $step) {
                $reindex_success = "N";
                break;
            }
        }
        if ($reindex_success != "N") {
            $reindex_success = "Y";
        }
        if ($bExtTotal) {
            $total_reindex[0] += $step_reindex;
            $total_reindex[1] = ftell($fp);
        } else {
            $total_reindex += $step_reindex;
        }
        fclose($fp);
        fclose($f_db);
        fclose($f_idx);
    }
}
Ejemplo n.º 9
0
     $arAnswer["PERCENT"] = $arAnswer["PERCENT2"] = $arAnswer["PERCENT3"];
     if ($counterSum > 0) {
         $arAnswer["PERCENT"] = $arAnswer["PERCENT2"] = $arAnswer["PERCENT3"] = $percentage = $arAnswer["COUNTER"] * 100 / $counter;
         if (is_float($percentage)) {
             $arAnswer["PERCENT"] = number_format($percentage, 0, ".", "");
             $arAnswer["PERCENT2"] = number_format($percentage, 1, ".", "");
             if ($arAnswer["PERCENT2"] != $percentage) {
                 $arAnswer["PERCENT3"] = number_format($percentage, 2, ".", "");
             }
         }
         $sum1 += $arAnswer["PERCENT"];
         $sum2 += $arAnswer["PERCENT2"];
         $sum3 += $arAnswer["PERCENT3"];
     }
     $arAnswer["BAR_PERCENT"] = $arAnswer["FIELD_TYPE"] == 0 || $arAnswer["FIELD_TYPE"] == 2 ? $counterMax > 0 ? round($arAnswer["COUNTER"] * 100 / $counterMax) : 0 : round($arAnswer["PERCENT"]);
     $arAnswer["COLOR"] = empty($arAnswer["COLOR"]) && ($color = GetNextRGB($color, count($arQuestion["ANSWERS"]))) ? $color : TrimEx($arAnswer["COLOR"], "#");
     $arQuestion["ANSWERS"][$aID] = $arAnswer;
 }
 $var = $sum1 == 100 ? 1 : ($sum2 == 100 ? 2 : 3);
 if ($var > 1) {
     foreach ($arQuestion["ANSWERS"] as $aID => $arAnswer) {
         $arQuestion["ANSWERS"][$aID]["PERCENT"] = $arQuestion["ANSWERS"][$aID]["PERCENT" . $var];
     }
 }
 $arResult["QUESTIONS"][$qID]["COUNTER_SUM"] = $counterSum;
 $arResult["QUESTIONS"][$qID]["COUNTER_MAX"] = $counterMax;
 //Images
 $arResult["QUESTIONS"][$qID]["IMAGE"] = CFile::GetFileArray($arResult["QUESTIONS"][$qID]["IMAGE_ID"]);
 //Diagram type
 if (!empty($arParams["QUESTION_DIAGRAM_" . $qID]) && $arParams["QUESTION_DIAGRAM_" . $qID] != "-") {
     $arResult["QUESTIONS"][$qID]["DIAGRAM_TYPE"] = trim($arParams["QUESTION_DIAGRAM_" . $qID]);
Ejemplo n.º 10
0
 public static function SupportDeadlineNotify($arrTicket0)
 {
     //SUPPORT_DEADLINE_NOTIFY
     //SUPPORT_DEADLINE			= EXPIRATION_DATE
     //SUPPORT_DEADLINE_STMP		= EXPIRATION_DATE_STMP
     $err_mess = CAllTicketReminder::err_mess() . "<br>Function: SupportDeadlineNotify<br>Line: ";
     $rs = CTicket::GetByID($arrTicket0["ID"], false, "N");
     if (!($arTicket = $rs->Fetch())) {
         return false;
     }
     $rsMessage = CTicket::GetMessageByID(intval($arTicket["ID_1_USER_M_AFTER_SUP_M"]), "N", "N");
     if (!($arMessage = $rsMessage->Fetch())) {
         return false;
     }
     $arMessage["EXPIRATION_DATE"] = $arrTicket0["SUPPORT_DEADLINE"];
     $arMessage["EXPIRATION_DATE_STMP"] = MakeTimeStamp($arMessage["EXPIRATION_DATE"]);
     //$SUPPORT_DEADLINE_STMP = MakeTimeStamp($arrTicket0["SUPPORT_DEADLINE"]);
     $rsSite = CSite::GetByID($arTicket["SITE_ID"]);
     $arSite = $rsSite->Fetch();
     global $MESS, $DB;
     //$oldMess = $MESS;
     IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/support/classes/general/messages.php", $arSite["LANGUAGE_ID"]);
     $sourceName = strlen($arTicket["SOURCE_NAME"]) <= 0 ? "" : "[" . $arTicket["SOURCE_NAME"] . "] ";
     if (intval($arTicket["OWNER_USER_ID"]) > 0 || strlen(trim($arTicket["OWNER_LOGIN"])) > 0) {
         $ownerText = "[" . $arTicket["OWNER_USER_ID"] . "] (" . $arTicket["OWNER_LOGIN"] . ") " . $arTicket["OWNER_NAME"];
         //if(strlen(trim($OWNER_SID)) > 0 && $OWNER_SID != "null") $ownerText = " / " . $ownerText;
     }
     if (intval($arTicket["RESPONSIBLE_USER_ID"]) > 0) {
         $responsibleText = "[" . $arTicket["RESPONSIBLE_USER_ID"] . "] (" . $arTicket["RESPONSIBLE_LOGIN"] . ") " . $arTicket["RESPONSIBLE_NAME"];
         if (CTicket::IsSupportTeam($arTicket["RESPONSIBLE_USER_ID"]) || CTicket::IsAdmin($arTicket["RESPONSIBLE_USER_ID"])) {
             $responsibleText .= " " . GetMessage("SUP_TECHSUPPORT_HINT");
         }
     }
     $arAdminEMails = CTicket::GetAdminEmails();
     if (count($arAdminEMails) > 0) {
         $support_admin_email = implode(",", $arAdminEMails);
     }
     // prepare email to author
     $arrOwnerEMail = array($arTicket["OWNER_EMAIL"]);
     $arrEmails = explode(",", $arTicket["OWNER_SID"]);
     if (is_array($arrEmails) && count($arrEmails) > 0) {
         foreach ($arrEmails as $email) {
             $email = trim($email);
             if (strlen($email) > 0) {
                 preg_match_all("#[<\\[\\(](.*?)[>\\]\\)]#i" . BX_UTF_PCRE_MODIFIER, $email, $arr);
                 if (is_array($arr[1]) && count($arr[1]) > 0) {
                     foreach ($arr[1] as $email) {
                         $email = trim($email);
                         if (strlen($email) > 0 && !in_array($email, $arrOwnerEMail) && check_email($email)) {
                             $arrOwnerEMail[] = $email;
                         }
                     }
                 } elseif (!in_array($email, $arrOwnerEMail) && check_email($email)) {
                     $arrOwnerEMail[] = $email;
                 }
             }
         }
     }
     TrimArr($arrOwnerEMail);
     $ownerEmail = implode(", ", $arrOwnerEMail);
     // prepare email to support
     $support_email = $arTicket["RESPONSIBLE_EMAIL"];
     if (strlen($support_email) <= 0) {
         $support_email = $support_admin_email;
     }
     if (strlen($support_email) <= 0) {
         $support_email = COption::GetOptionString("main", "email_from", "");
     }
     $arr = explode(",", $support_email);
     $arr = array_unique($arr);
     $support_email = implode(",", $arr);
     if (is_array($arr) && count($arr) > 0) {
         foreach ($arr as $email) {
             unset($arAdminEMails[$email]);
         }
     }
     $support_admin_email = implode(",", $arAdminEMails);
     $createdModuleName = "";
     if ($arTicket["CREATED_MODULE_NAME"] == "support" || !strlen($arTicket["CREATED_MODULE_NAME"])) {
         if (intval($arTicket["CREATED_USER_ID"]) > 0) {
             $createdText = "[" . $arTicket["CREATED_USER_ID"] . "] (" . $arTicket["CREATED_LOGIN"] . ") " . $arTicket["CREATED_NAME"];
             if (CTicket::IsSupportTeam($arTicket["CREATED_USER_ID"]) || CTicket::IsAdmin($arTicket["CREATED_USER_ID"])) {
                 $createdText .= " " . GetMessage("SUP_TECHSUPPORT_HINT");
             }
         }
     } else {
         $createdModuleName = "[" . $arTicket["CREATED_MODULE_NAME"] . "]";
     }
     $MESSAGE = PrepareTxtForEmail($arMessage["MESSAGE"], $arSite["LANGUAGE_ID"], false, false);
     $remainedTime = $arMessage["EXPIRATION_DATE_STMP"] - time();
     if ($remainedTime > 0) {
         $strRemainedTime = "";
         $hours = intval($remainedTime / 3600);
         if ($hours > 0) {
             $strRemainedTime .= $hours . " " . GetMessage("SUP_HOUR") . " ";
             $remainedTime = $remainedTime - $hours * 3600;
         }
         $strRemainedTime .= intval($remainedTime / 60) . " " . GetMessage("SUP_MIN") . " ";
         $strRemainedTime .= $remainedTime % 60 . " " . GetMessage("SUP_SEC");
     }
     $arFields_notify = array("ID" => $arTicket["ID"], "LANGUAGE_ID" => $arSite["LANGUAGE_ID"], "DATE_CREATE" => $arTicket["DATE_CREATE"], "TITLE" => $arTicket["TITLE"], "STATUS" => $arTicket["STATUS_NAME"], "CATEGORY" => $arTicket["CATEGORY_NAME"], "CRITICALITY" => $arTicket["CRITICALITY_NAME"], "DIFFICULTY" => $arTicket["DIFFICULTY_NAME"], "RATE" => $arTicket["MARK_NAME"], "SLA" => $arTicket["SLA_NAME"], "SOURCE" => $sourceName, "ADMIN_EDIT_URL" => "/bitrix/admin/ticket_edit.php", "EXPIRATION_DATE" => $arMessage["EXPIRATION_DATE"], "REMAINED_TIME" => $strRemainedTime, "OWNER_EMAIL" => TrimEx($ownerEmail, ","), "OWNER_USER_ID" => $arTicket["OWNER_USER_ID"], "OWNER_USER_NAME" => $arTicket["OWNER_NAME"], "OWNER_USER_LOGIN" => $arTicket["OWNER_LOGIN"], "OWNER_USER_EMAIL" => $arTicket["OWNER_EMAIL"], "OWNER_TEXT" => $ownerText, "OWNER_SID" => $arTicket["OWNER_SID"], "SUPPORT_EMAIL" => TrimEx($support_email, ","), "RESPONSIBLE_USER_ID" => $arTicket["RESPONSIBLE_USER_ID"], "RESPONSIBLE_USER_NAME" => $arTicket["RESPONSIBLE_NAME"], "RESPONSIBLE_USER_LOGIN" => $arTicket["RESPONSIBLE_LOGIN"], "RESPONSIBLE_USER_EMAIL" => $arTicket["RESPONSIBLE_EMAIL"], "RESPONSIBLE_TEXT" => $responsibleText, "SUPPORT_ADMIN_EMAIL" => TrimEx($support_admin_email, ","), "CREATED_USER_ID" => $arTicket["CREATED_USER_ID"], "CREATED_USER_LOGIN" => $arTicket["CREATED_LOGIN"], "CREATED_USER_EMAIL" => $arTicket["CREATED_EMAIL"], "CREATED_USER_NAME" => $arTicket["CREATED_NAME"], "CREATED_MODULE_NAME" => $createdModuleName, "CREATED_TEXT" => $createdText, "MESSAGE_BODY" => $MESSAGE);
     //$MESS = $oldMess;
     $arFields = array("NOTIFY_AGENT_ID" => "null", "IS_NOTIFIED" => "'Y'");
     // execute event
     $rs = GetModuleEvents('support', 'OnBeforeTicketNotify');
     while ($arr = $rs->Fetch()) {
         $arFields = ExecuteModuleEventEx($arr, array($arTicket["ID"], $arFields));
         if (!$arFields) {
             return false;
         }
     }
     // check value again and send notification
     if (isset($arFields['IS_NOTIFIED']) && $arFields['IS_NOTIFIED'] === "'Y'") {
         CEvent::Send("TICKET_OVERDUE_REMINDER", $arTicket["SITE_ID"], $arFields_notify);
     }
     // event for notification
     $DB->Update("b_ticket", $arFields, "WHERE ID='" . $arTicket["ID"] . "'", $err_mess . __LINE__);
     $arFields = array("NOTIFY_AGENT_DONE" => "'Y'");
     $DB->Update("b_ticket_message", $arFields, "WHERE ID='" . $arMessage["ID"] . "'", $err_mess . __LINE__);
 }
Ejemplo n.º 11
0
 public static function GetList($arSort = array(), $arFilter = array())
 {
     global $DB;
     $arSqlSearch = array();
     $err_mess = self::err_mess() . '<br />Function: GetList<br>Line: ';
     if (is_array($arFilter)) {
         self::PrepareSearchQuery($arFilter, $arSqlSearch);
     }
     $sOrder = '';
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != 'ASC' ? 'DESC' : 'ASC';
         switch (strtoupper($key)) {
             case 'ID':
                 $sOrder .= ', CFM.ID ' . $ord;
                 break;
             case 'ENTITY_ID':
                 $sOrder .= ', CFM.ENTITY_ID ' . $ord;
                 break;
             case 'ELEMENT_ID':
                 $sOrder .= ', CFM.ELEMENT_ID ' . $ord;
                 break;
             case 'TYPE_ID':
                 $sOrder .= ', CFM.TYPE_ID ' . $ord;
                 break;
             case 'VALUE_TYPE':
                 $sOrder .= ', CFM.VALUE_TYPE ' . $ord;
                 break;
             case 'COMPLEX_ID':
                 $sOrder .= ', CFM.COMPLEX_ID ' . $ord;
                 break;
             case 'VALUE':
                 $sOrder .= ', CFM.VALUE ' . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = 'CFM.ID DESC';
     }
     $strSqlOrder = ' ORDER BY ' . TrimEx($sOrder, ",");
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tCFM.ID, CFM.ENTITY_ID, CFM.ELEMENT_ID, CFM.TYPE_ID, CFM.VALUE_TYPE, CFM.COMPLEX_ID, CFM.VALUE\n\t\t\tFROM\n\t\t\t\tb_crm_field_multi CFM\n\t\t\tWHERE\n\t\t\t{$strSqlSearch}\n\t\t\t{$strSqlOrder}";
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     return $res;
 }
Ejemplo n.º 12
0
			$counterMax = max(intVal($arAnswer["COUNTER"]), $counterMax);
		}

		if ($arParams["NEED_SORT"] != "N")
			uasort($arQuestion["ANSWERS"], "_vote_answer_sort");
		$color = "";

		foreach ($arQuestion["ANSWERS"] as $aID => $arAnswer)
		{
			$arResult["LAST_VOTE"] = ($arResult["LAST_VOTE"] === false ? $arAnswer["LAST_VOTE"] : $arResult["LAST_VOTE"]);
			$arResult["LAST_VOTE"] = min($arResult["LAST_VOTE"], $arAnswer["LAST_VOTE"]);
			$arAnswer["PERCENT"] = ($counterSum > 0 ? number_format(($arAnswer["COUNTER"]*100/$counter),0,",","") : 0);
			$arAnswer["BAR_PERCENT"] = ($arAnswer["FIELD_TYPE"] == 0 || $arAnswer["FIELD_TYPE"] == 2 ?  /* radio || dropdown */
				($counterMax > 0 ? round($arAnswer["COUNTER"]*100/$counterMax) : 0) : round($arAnswer["PERCENT"]));
			$arAnswer["COLOR"] = (empty($arAnswer["COLOR"]) && ($color = GetNextRGB($color, count($arQuestion["ANSWERS"]))) ?
				$color : TrimEx($arAnswer["COLOR"], "#"));
			$arQuestion["ANSWERS"][$aID] = $arAnswer;
		}
		$arResult["QUESTIONS"][$qID]["COUNTER_SUM"] = $counterSum;
		$arResult["QUESTIONS"][$qID]["COUNTER_MAX"] = $counterMax;

		//Images
		$arResult["QUESTIONS"][$qID]["IMAGE"] = CFile::GetFileArray($arResult["QUESTIONS"][$qID]["IMAGE_ID"]);

		//Diagram type
		if (!empty($arParams["QUESTION_DIAGRAM_".$qID]) && $arParams["QUESTION_DIAGRAM_".$qID]!="-")
			$arResult["QUESTIONS"][$qID]["DIAGRAM_TYPE"] = trim($arParams["QUESTION_DIAGRAM_".$qID]);

		//Answers
		$arResult["QUESTIONS"][$qID]["ANSWERS"] = $arQuestion["ANSWERS"];
	}
Ejemplo n.º 13
0
 public static function GetList($arSort = array(), $arFilter = array(), $nPageTop = false)
 {
     global $DB, $USER;
     $currentUser = isset($USER) && (get_class($USER) === 'CUser' || $USER instanceof CUser) ? $USER : new CUser();
     $arSqlSearch = array();
     $strSqlSearch = "";
     $err_mess = self::err_mess() . '<br />Function: GetList<br />Line: ';
     if (isset($arFilter['ENTITY'])) {
         $ar = explode('_', $arFilter['ENTITY']);
         $arFilter['ENTITY_TYPE'] = CUserTypeCrm::GetLongEntityType($ar[0]);
         $arFilter['ENTITY_ID'] = intval($ar[1]);
         unset($arFilter['ENTITY']);
     }
     // permission check
     $strPermission = "";
     if (!$currentUser->IsAdmin()) {
         $CCrmPerms = new CCrmPerms($currentUser->GetID());
         $arUserAttr = array();
         $arEntity = array();
         if (empty($arFilter['ENTITY_TYPE'])) {
             $arEntity = array('LEAD', 'DEAL', 'CONTACT', 'COMPANY', 'QUOTE');
         } else {
             if (is_array($arFilter['ENTITY_TYPE'])) {
                 $arEntity = $arFilter['ENTITY_TYPE'];
             } else {
                 $arEntity = array($arFilter['ENTITY_TYPE']);
             }
         }
         $arInEntity = array();
         foreach ($arEntity as $sEntityType) {
             $arEntityAttr = $CCrmPerms->GetUserAttrForSelectEntity($sEntityType, 'READ');
             $arUserAttr[$sEntityType] = $arEntityAttr;
         }
         if (empty($arUserAttr)) {
             $CDBResult = new CDBResult();
             $CDBResult->InitFromArray(array());
             return $CDBResult;
         }
         $arUserPerm = array();
         foreach ($arUserAttr as $sEntityType => $_arAttrs) {
             if (isset($_arAttrs[0]) && is_array($_arAttrs[0]) && empty($_arAttrs[0])) {
                 $arInEntity[] = $sEntityType;
                 continue;
             }
             foreach ($_arAttrs as $_arAttr) {
                 if (empty($_arAttr)) {
                     continue;
                 }
                 $_icnt = count($_arAttr);
                 $_idcnt = -1;
                 foreach ($_arAttr as $sAttr) {
                     if ($sAttr[0] == 'D') {
                         $_idcnt++;
                     }
                 }
                 if ($_icnt == 1 && ($_idcnt == 1 || $_idcnt == -1)) {
                     $_idcnt = 0;
                 }
                 $arUserPerm[] = "(P.ENTITY = '{$sEntityType}' AND SUM(CASE WHEN P.ATTR = '" . implode("' or P.ATTR = '", $_arAttr) . "' THEN 1 ELSE 0 END) = " . ($_icnt - $_idcnt) . ')';
             }
         }
         $arPermission = array();
         if (!empty($arInEntity)) {
             $arPermission[] = " CER.ENTITY_TYPE IN ('" . implode("','", $arInEntity) . "')";
         }
         if (!empty($arUserPerm)) {
             $arPermission[] = "\n\t\t\t\t\t\tEXISTS(\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM b_crm_entity_perms P\n\t\t\t\t\t\t\tWHERE P.ENTITY = CER.ENTITY_TYPE AND CER.ENTITY_ID = P.ENTITY_ID\n\t\t\t\t\t\t\tGROUP BY P.ENTITY, P.ENTITY_ID\n\t\t\t\t\t\t\tHAVING " . implode(" \n\t\t\t\t\t\t\t\tOR ", $arUserPerm) . "\n\t\t\t\t\t\t)";
         }
         if (!empty($arPermission)) {
             $strPermission = 'AND (' . implode(' OR ', $arPermission) . ')';
         }
     }
     $sOrder = '';
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != 'ASC' ? 'DESC' : 'ASC';
         switch (strtoupper($key)) {
             case 'ID':
                 $sOrder .= ', CER.ID ' . $ord;
                 break;
             case 'CREATED_BY_ID':
                 $sOrder .= ', CE.CREATED_BY_ID ' . $ord;
                 break;
             case 'EVENT_TYPE':
                 $sOrder .= ', CE.EVENT_TYPE ' . $ord;
                 break;
             case 'ENTITY_TYPE':
                 $sOrder .= ', CER.ENTITY_TYPE ' . $ord;
                 break;
             case 'ENTITY_ID':
                 $sOrder .= ', CER.ENTITY_ID ' . $ord;
                 break;
             case 'EVENT_ID':
                 $sOrder .= ', CE.EVENT_ID ' . $ord;
                 break;
             case 'DATE_CREATE':
                 $sOrder .= ', CE.DATE_CREATE ' . $ord;
                 break;
             case 'EVENT_NAME':
                 $sOrder .= ', CE.EVENT_NAME 	 ' . $ord;
                 break;
             case 'ENTITY_FIELD':
                 $sOrder .= ', CER.ENTITY_FIELD 	 ' . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = 'CER.ID DESC';
     }
     $strSqlOrder = ' ORDER BY ' . TrimEx($sOrder, ',');
     // where
     $arWhereFields = array('ID' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.ID', 'FIELD_TYPE' => 'int', 'JOIN' => false), 'ENTITY_TYPE' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.ENTITY_TYPE', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'EVENT_REL_ID' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.EVENT_ID', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'EVENT_ID' => array('TABLE_ALIAS' => 'CE', 'FIELD_NAME' => 'CE.EVENT_ID', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'CREATED_BY_ID' => array('TABLE_ALIAS' => 'CE', 'FIELD_NAME' => 'CE.CREATED_BY_ID', 'FIELD_TYPE' => 'int', 'JOIN' => false), 'ASSIGNED_BY_ID' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.ASSIGNED_BY_ID', 'FIELD_TYPE' => 'int', 'JOIN' => false), 'EVENT_TYPE' => array('TABLE_ALIAS' => 'CE', 'FIELD_NAME' => 'CE.EVENT_TYPE', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'EVENT_DESC' => array('TABLE_ALIAS' => 'CE', 'FIELD_NAME' => 'CE.EVENT_TEXT_1', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'ENTITY_ID' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.ENTITY_ID', 'FIELD_TYPE' => 'int', 'JOIN' => false), 'ENTITY_FIELD' => array('TABLE_ALIAS' => 'CER', 'FIELD_NAME' => 'CER.ENTITY_FIELD', 'FIELD_TYPE' => 'string', 'JOIN' => false), 'DATE_CREATE' => array('TABLE_ALIAS' => 'CE', 'FIELD_NAME' => 'CE.DATE_CREATE', 'FIELD_TYPE' => 'datetime', 'JOIN' => false));
     $obQueryWhere = new CSQLWhere();
     $obQueryWhere->SetFields($arWhereFields);
     if (!is_array($arFilter)) {
         $arFilter = array();
     }
     $sQueryWhereFields = $obQueryWhere->GetQuery($arFilter);
     if (!empty($sQueryWhereFields)) {
         $strSqlSearch .= "\n\t\t\t\tAND ({$sQueryWhereFields}) ";
     }
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tCER.ID,\n\t\t\t\tCER.ENTITY_TYPE,\n\t\t\t\tCER.ENTITY_ID,\n\t\t\t\tCER.ENTITY_FIELD,\n\t\t\t\t" . $DB->DateToCharFunction('CE.DATE_CREATE') . " DATE_CREATE,\n\t\t\t\tCER.EVENT_ID,\n\t\t\t\tCE.EVENT_NAME,\n\t\t\t\tCE.EVENT_TYPE,\n\t\t\t\tCE.EVENT_TEXT_1,\n\t\t\t\tCE.EVENT_TEXT_2,\n\t\t\t\tCE.FILES,\n\t\t\t\tCE.CREATED_BY_ID,\n\t\t\t\tU.LOGIN as CREATED_BY_LOGIN,\n\t\t\t\tU.NAME as CREATED_BY_NAME,\n\t\t\t\tU.LAST_NAME as CREATED_BY_LAST_NAME,\n\t\t\t\tU.SECOND_NAME as CREATED_BY_SECOND_NAME\n\t\t\tFROM\n\t\t\t\tb_crm_event_relations CER,\n\t\t\t\tb_crm_event CE LEFT JOIN b_user U ON CE.CREATED_BY_ID = U.ID\n\t\t\tWHERE\n\t\t\t\tCER.EVENT_ID = CE.ID\n\t\t\t\t{$strSqlSearch}\n\t\t\t\t{$strPermission}\n\t\t\t\t{$strSqlOrder}";
     if ($nPageTop !== false) {
         $nPageTop = (int) $nPageTop;
         $strSql = $DB->TopSql($strSql, $nPageTop);
     }
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     $res->SetUserFields(array('FILES' => array('MULTIPLE' => 'Y')));
     return $res;
 }
Ejemplo n.º 14
0
 function GetList($aSort = array(), $arFilter = array())
 {
     global $DB;
     $this->LAST_ERROR = "";
     $arSqlSearch = array();
     $arSqlSearch_h = array();
     $strSqlSearch = "";
     if (is_array($arFilter)) {
         foreach ($arFilter as $key => $val) {
             if (strlen($val) <= 0 || $val == "NOT_REF") {
                 continue;
             }
             switch (strtoupper($key)) {
                 case "ID":
                     $arSqlSearch[] = GetFilterQuery("P.ID", $val, "N");
                     break;
                 case "TIMESTAMP_1":
                     if ($DB->IsDate($val)) {
                         $arSqlSearch[] = "P.TIMESTAMP_X>=" . $DB->CharToDateFunction($val, "SHORT");
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_TIMESTAMP_FROM") . "<br>";
                     }
                     break;
                 case "TIMESTAMP_2":
                     if ($DB->IsDate($val)) {
                         $arSqlSearch[] = "P.TIMESTAMP_X<DATEADD(DAY, +1, " . $DB->CharToDateFunction($val, "SHORT") . ")";
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_TIMESTAMP_TILL") . "<br>";
                     }
                     break;
                 case "DATE_SENT_1":
                     if ($DB->IsDate($val)) {
                         $arSqlSearch[] = "P.DATE_SENT>=" . $DB->CharToDateFunction($val, "SHORT");
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_DATE_SENT_FROM") . "<br>";
                     }
                     break;
                 case "DATE_SENT_2":
                     if ($DB->IsDate($val)) {
                         $arSqlSearch[] = "P.DATE_SENT<DATEADD(DAY, +1, " . $DB->CharToDateFunction($val, "SHORT") . ")";
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_DATE_SENT_TILL") . "<br>";
                     }
                     break;
                 case "STATUS":
                     $arSqlSearch_h[] = GetFilterQuery("STATUS_TITLE, P.STATUS", $val);
                     break;
                 case "STATUS_ID":
                     $arSqlSearch[] = GetFilterQuery("P.STATUS", $val, "N");
                     break;
                 case "SUBJECT":
                     $arSqlSearch[] = GetFilterQuery("P.SUBJECT", $val);
                     break;
                 case "FROM":
                     $arSqlSearch[] = GetFilterQuery("P.FROM_FIELD", $val, "Y", array("@", "_", "."));
                     break;
                 case "TO":
                     $arSqlSearch[] = GetFilterQuery("P.SENT_BCC", $val, "Y", array("@", "_", "."));
                     break;
                 case "BODY_TYPE":
                     $arSqlSearch[] = $val == "html" ? "P.BODY_TYPE='html'" : "P.BODY_TYPE='text'";
                     break;
                 case "BODY":
                     $arSqlSearch[] = GetFilterQuery("P.BODY", $val);
                     break;
                 case "AUTO_SEND_TIME_1":
                     if ($DB->IsDate($val, false, false, "FULL")) {
                         $arSqlSearch[] = "(P.AUTO_SEND_TIME is not null and P.AUTO_SEND_TIME>=" . $DB->CharToDateFunction($val, "FULL") . " )";
                     } elseif ($DB->IsDate($val, false, false, "SHORT")) {
                         $arSqlSearch[] = "(P.AUTO_SEND_TIME is not null and P.AUTO_SEND_TIME>=" . $DB->CharToDateFunction($val, "SHORT") . " )";
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_AUTO_FROM") . "<br>";
                     }
                     break;
                 case "AUTO_SEND_TIME_2":
                     if ($DB->IsDate($val, false, false, "FULL")) {
                         $arSqlSearch[] = "(P.AUTO_SEND_TIME is not null and P.AUTO_SEND_TIME<=" . $DB->CharToDateFunction($val, "FULL") . " )";
                     } elseif ($DB->IsDate($val, false, false, "SHORT")) {
                         $arSqlSearch[] = "(P.AUTO_SEND_TIME is not null and P.AUTO_SEND_TIME<=" . $DB->CharToDateFunction($val, "SHORT") . " )";
                     } else {
                         $this->LAST_ERROR .= GetMessage("POST_WRONG_AUTO_TILL") . "<br>";
                     }
                     break;
             }
         }
     }
     $sOrder = "";
     $sort_keys = array_keys($aSort);
     for ($i = 0; $i < count($sort_keys); $i++) {
         $ord = strtoupper($aSort[$sort_keys[$i]]) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($sort_keys[$i])) {
             case "ID":
                 $sOrder .= ", P.ID " . $ord;
                 break;
             case "TIMESTAMP":
                 $sOrder .= ", P.TIMESTAMP_X " . $ord;
                 break;
             case "SUBJECT":
                 $sOrder .= ", P.SUBJECT " . $ord;
                 break;
             case "BODY_TYPE":
                 $sOrder .= ", P.BODY_TYPE " . $ord;
                 break;
             case "STATUS":
                 $sOrder .= ", P.STATUS " . $ord;
                 break;
             case "DATE_SENT":
                 $sOrder .= ", P.DATE_SENT " . $ord;
                 break;
             case "AUTO_SEND_TIME":
                 $sOrder .= ", P.AUTO_SEND_TIME " . $ord;
                 break;
             case "FROM_FIELD":
                 $sOrder .= ", P.FROM_FIELD " . $ord;
                 break;
             case "TO_FIELD":
                 $sOrder .= ", P.TO_FIELD " . $ord;
                 break;
         }
     }
     if ($sOrder == "") {
         $sOrder = "P.ID DESC";
     }
     $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tCASE\n\t\t\t\tWHEN P.STATUS='S' THEN '" . $DB->ForSql(GetMessage("POST_STATUS_SENT")) . "'\n\t\t\t\tWHEN P.STATUS='P' THEN '" . $DB->ForSql(GetMessage("POST_STATUS_PART")) . "'\n\t\t\t\tWHEN P.STATUS='E' THEN '" . $DB->ForSql(GetMessage("POST_STATUS_ERROR")) . "'\n\t\t\t\tWHEN P.STATUS='W' THEN '" . $DB->ForSql(GetMessage("POST_STATUS_WAIT")) . "'\n\t\t\t\tELSE '" . $DB->ForSql(GetMessage("POST_STATUS_DRAFT")) . "'\n\t\t\t\tEND as STATUS_TITLE\n\t\t\t\t,P.ID\n\t\t\t\t,P.STATUS\n\t\t\t\t,P.FROM_FIELD\n\t\t\t\t,P.TO_FIELD\n\t\t\t\t,P.EMAIL_FILTER\n\t\t\t\t,P.SUBJECT\n\t\t\t\t,P.BODY_TYPE\n\t\t\t\t,P.DIRECT_SEND\n\t\t\t\t,P.CHARSET\n\t\t\t\t,P.SUBSCR_FORMAT\n\t\t\t\t," . $DB->DateToCharFunction("P.TIMESTAMP_X") . "\tTIMESTAMP_X\n\t\t\t\t," . $DB->DateToCharFunction("P.DATE_SENT") . "\tDATE_SENT\n\t\t\tFROM b_posting P\n\t\t\tWHERE\n\t\t\t" . $strSqlSearch . "\n\t\t";
     if (count($arSqlSearch_h) > 0) {
         $strSqlSearch_h = GetFilterSqlSearch($arSqlSearch_h);
         $strSql = "SELECT * FROM (" . $strSql . ") AS P WHERE " . $strSqlSearch_h;
     }
     $strSql .= $strSqlOrder;
     //		echo htmlspecialchars($strSql);
     $res = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     $res->is_filtered = IsFiltered($strSqlSearch);
     return $res;
 }
Ejemplo n.º 15
0
 public static function GetVetting($arFilter, $arSort)
 {
     global $DB;
     $err_mess = CRatingRule::err_mess() . "<br>Function: GetVetting<br>Line: ";
     $arSqlSearch = array();
     if (is_array($arFilter)) {
         $filter_keys = array_keys($arFilter);
         for ($i = 0; $i < count($filter_keys); $i++) {
             $val = $arFilter[$filter_keys[$i]];
             if (strlen($val) <= 0 || $val == "NOT_REF") {
                 continue;
             }
             switch (strtoupper($filter_keys[$i])) {
                 case "RULE_ID":
                     $arSqlSearch[] = GetFilterQuery("RULE_ID", $val, "N");
                     break;
                 case "ENTITY_TYPE_ID":
                     $arSqlSearch[] = GetFilterQuery("ENTITY_TYPE_ID", $val, "N");
                     break;
                 case "ENTITY_ID":
                     $arSqlSearch[] = GetFilterQuery("ENTITY_ID", $val, "N");
                     break;
                 case "APPLIED":
                     if (in_array($val, array('Y', 'N'))) {
                         $arSqlSearch[] = "APPLIED = '" . $val . "'";
                     }
                     break;
             }
         }
     }
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $sOrder = "";
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($key)) {
             case "ID":
                 $sOrder .= ", ID " . $ord;
                 break;
             case "RULE_ID":
                 $sOrder .= ", RULE_ID " . $ord;
                 break;
             case "ENTITY_TYPE_ID":
                 $sOrder .= ", ENTITY_TYPE_ID " . $ord;
                 break;
             case "ENTITY_ID":
                 $sOrder .= ", ENTITY_ID " . $ord;
                 break;
             case "APPLIED":
                 $sOrder .= ", APPLIED " . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = "ID ASC";
     }
     $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     $strSql = "SELECT * FROM b_rating_rule_vetting WHERE {$strSqlSearch} {$strSqlOrder}";
     return $DB->Query($strSql, false, $err_mess . __LINE__);
 }
Ejemplo n.º 16
0
 public function GetList($aSort = array(), $arFilter = array())
 {
     global $DB;
     $arSqlSearch = array();
     if (is_array($arFilter)) {
         foreach ($arFilter as $key => $val) {
             if (strlen($val) <= 0 || $val == "NOT_REF") {
                 continue;
             }
             $key = strtoupper($key);
             switch ($key) {
                 case "ID":
                 case "CODE_ID":
                 case "USER_ID":
                     $arSqlSearch[] = $key . "=" . intval($val);
                     break;
                 case "KEYS_STRING":
                     $arSqlSearch[] = GetFilterQuery("KEYS_STRING", $val);
                     break;
             }
         }
     }
     $sOrder = "";
     foreach ($aSort as $key => $val) {
         $ord = strtoupper($val) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($key)) {
             case "ID":
                 $sOrder .= ", ID " . $ord;
                 break;
             case "KEYS_STRING":
                 $sOrder .= ", KEYS_STRING " . $ord;
                 break;
             case "CODE_ID":
                 $sOrder .= ", CODE_ID " . $ord;
                 break;
             case "USER_ID":
                 $sOrder .= ", USER_ID " . $ord;
                 break;
         }
     }
     if (strlen($sOrder) > 0) {
         $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     } else {
         $strSqlOrder = "";
     }
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\tb_hot_keys\n\t\t\tWHERE\n\t\t\t" . $strSqlSearch . "\n\t\t\t" . $strSqlOrder;
     $res = $DB->Query($strSql, false, $this->ErrOrig() . " Line: " . __LINE__);
     return $res;
 }
Ejemplo n.º 17
0
	/**
	 * <p>Возвращает массив, описывающий значения <a href="http://dev.1c-bitrix.ru/api_help/form/terms.php#answer">ответов</a> на <a href="http://dev.1c-bitrix.ru/api_help/form/terms.php#question">вопросы</a> или значения <a href="http://dev.1c-bitrix.ru/api_help/form/terms.php#field">полей</a> веб-формы для указанного <a href="http://dev.1c-bitrix.ru/api_help/form/terms.php#result">результата</a>. Помимо этого, функция возвращает массив, содержащий <a href="http://dev.1c-bitrix.ru/api_help/form/classes/cformresult/index.php">поля результата</a>.</p> <p> Формат массива возвращаемый функцией: </p> <pre class="syntax">Array ( [<i>символьный идентификатор вопроса 1</i>] =&gt; массив описывающий ответы на вопрос 1 Array ( [0] =&gt; массив описывающий ответ 1 Array ( [RESULT_ID] =&gt; ID результата [FIELD_ID] =&gt; ID вопроса [SID] =&gt; символьный идентификатор вопроса [TITLE] =&gt; текст вопроса [TITLE_TYPE] =&gt; тип текста вопроса [text|html] [FILTER_TITLE] =&gt; заголовок поля фильтра [RESULTS_TABLE_TITLE] =&gt; заголовок столбца таблицы результатов [ANSWER_ID] =&gt; ID ответа [ANSWER_TEXT] =&gt; параметр ответа <font color="green">ANSWER_TEXT</font> [ANSWER_VALUE] =&gt; параметр ответа <font color="red">ANSWER_VALUE</font> [USER_TEXT] =&gt; текст введенный с клавиатуры [USER_DATE] =&gt; введенная дата (если FIELD_TYPE=date) [USER_FILE_ID] =&gt; ID файла (если FIELD_TYPE=[file|image]) [USER_FILE_NAME] =&gt; имя файла [USER_FILE_IS_IMAGE] =&gt; "Y" - FIELD_TYPE=image; "N" - FIELD_TYPE=file [USER_FILE_HASH] =&gt; хэш файла (если FIELD_TYPE=file) [USER_FILE_SUFFIX] =&gt; суффикс к расширению файла (если FIELD_TYPE=file) [USER_FILE_SIZE] =&gt; размер файла (если FIELD_TYPE=[file|image]) [FIELD_TYPE] =&gt; тип ответа [FIELD_WIDTH] =&gt; ширина поля ответа [FIELD_HEIGHT] =&gt; высота поля ответа [FIELD_PARAM] =&gt; параметр поля ответа ) [1] =&gt; массив описывающий ответ 2 [2] =&gt; массив описывающий ответ 3 ... [N-1] =&gt; массив описывающий ответ N ) [<i>символьный идентификатор вопроса 2</i>] =&gt; массив описывающий ответы на вопрос 2 [<i>символьный идентификатор вопроса 3</i>] =&gt; массив описывающий ответы на вопрос 3 ... [<i>символьный идентификатор вопроса N</i>] =&gt; массив описывающий ответы на вопрос N )</pre>
	 *
	 *
	 *
	 *
	 * @param int $result_id  ID результата.
	 *
	 *
	 *
	 * @param array $field  Массив символьных идентификаторов вопросов или полей веб-формы,
	 * значения которых необходимо получить.
	 *
	 *
	 *
	 * @param array &$result  Ссылка на массив <a href="http://dev.1c-bitrix.ru/api_help/form/classes/cformresult/index.php">полей
	 * результата</a>, а также некоторых <a
	 * href="http://dev.1c-bitrix.ru/api_help/form/classes/cform/index.php">полей веб-формы</a> и <a
	 * href="http://dev.1c-bitrix.ru/api_help/form/classes/cformstatus/index.php">полей статуса</a>.
	 * Структура данного массива: <pre>Array ( [ID] =&gt; ID результата [TIMESTAMP_X] =&gt;
	 * время изменения результата [DATE_CREATE] =&gt; дата создания результата
	 * [FORM_ID] =&gt; ID веб-формы [USER_ID] =&gt; ID пользователя создавшего результат
	 * (автор) [USER_AUTH] =&gt; флаг авторизованности автора при создании
	 * результата [Y|N] [STAT_GUEST_ID] =&gt; ID посетителя создавшего результат
	 * [STAT_SESSION_ID] =&gt; ID сессии в которой был создан результат [STATUS_ID] =&gt; ID
	 * статуса в котором находится результат [STATUS_TITLE] =&gt; заголовок
	 * статуса в котором находится результат [STATUS_DESCRIPTION] =&gt; описание
	 * статуса в котором находится результат [STATUS_CSS] =&gt; имя CSS класса в
	 * котором находится результат [SID] =&gt; символьный идентификатор
	 * веб-формы [NAME] =&gt; заголовок веб-формы [IMAGE_ID] =&gt; ID изображения
	 * веб-формы [DESCRIPTION] =&gt; описание веб-формы [DESCRIPTION_TYPE] =&gt; тип
	 * описания веб-формы [text|html] )</pre>
	 *
	 *
	 *
	 * @param array &$answer  Ссылка на массив, описывающий значения ответов на вопросы или
	 * значения полей веб-формы для указанного результата <i>result_id</i>.
	 * Структура данного массива: <pre>Array ( [<i>символьный идентификатор
	 * вопроса 1</i>] =&gt; массив описывающий ответы на вопрос 1 Array ( [<i>ID
	 * ответа 1</i>] =&gt; массив описывающий ответ 1 Array ( [RESULT_ID] =&gt; ID
	 * результата [FIELD_ID] =&gt; ID вопроса [SID] =&gt; символьный идентификатор
	 * вопроса [TITLE] =&gt; текст вопроса [TITLE_TYPE] =&gt; тип текста вопроса [text|html]
	 * [FILTER_TITLE] =&gt; заголовок поля фильтра [RESULTS_TABLE_TITLE] =&gt; заголовок
	 * столбца таблицы результатов [ANSWER_ID] =&gt; ID ответа [ANSWER_TEXT] =&gt;
	 * параметр ответа <font color="green">ANSWER_TEXT</font> [ANSWER_VALUE] =&gt; параметр ответа
	 * <font color="red">ANSWER_VALUE</font> [USER_TEXT] =&gt; текст введенный с клавиатуры
	 * [USER_DATE] =&gt; введенная дата (если FIELD_TYPE=date) [USER_FILE_ID] =&gt; ID файла
	 * (FIELD_TYPE=[file|image]) [USER_FILE_NAME] =&gt; имя файла [USER_FILE_IS_IMAGE] =&gt; "Y" - FIELD_TYPE=image;
	 * "N" - FIELD_TYPE=file [USER_FILE_HASH] =&gt; хэш файла (если FIELD_TYPE=file) [USER_FILE_SUFFIX] =&gt;
	 * суффикс к расширению файла (FIELD_TYPE=file) [USER_FILE_SIZE] =&gt; размер файла
	 * (если FIELD_TYPE=[file|image]) [FIELD_TYPE] =&gt; тип ответа [FIELD_WIDTH] =&gt; ширина поля
	 * ответа [FIELD_HEIGHT] =&gt; высота поля ответа [FIELD_PARAM] =&gt; параметр поля
	 * ответа ) [<i>ID ответа 2</i>] =&gt; массив описывающий ответ 2 [<i>ID ответа
	 * 3</i>] =&gt; массив описывающий ответ 3 ... [<i>ID ответа N</i>] =&gt; массив
	 * описывающий ответ N ) [<i>символьный идентификатор вопроса 2</i>] =&gt;
	 * массив описывающий ответы на вопрос 2 [<i>символьный идентификатор
	 * вопроса 3</i>] =&gt; массив описывающий ответы на вопрос 3 ...
	 * [<i>символьный идентификатор вопроса N</i>] =&gt; массив описывающий
	 * ответы на вопрос N )</pre>
	 *
	 *
	 *
	 * @return array 
	 *
	 *
	 * <h4>Example</h4> 
	 * <pre>
	 * &lt;?
	 * $RESULT_ID = 189; // ID результата
	 * 
	 * $arAnswer = <b>CFormResult::GetDataByID</b>(
	 * 	$RESULT_ID, 
	 * 	array("VS_INTEREST"),  // вопрос "Какие области знаний вас интересуют?" 
	 * 	$arResult, 
	 * 	$arAnswer2);
	 * 
	 * // выведем поля результата
	 * echo "&lt;pre&gt;"; print_r($arResult); echo "&lt;/pre&gt;";
	 * 
	 * // выведем значения ответов
	 * echo "&lt;pre&gt;"; print_r($arAnswer); echo "&lt;/pre&gt;";
	 * 
	 * // выведем значения ответов в несколько ином формате
	 * echo "&lt;pre&gt;"; print_r($arAnswer2); echo "&lt;/pre&gt;";
	 * ?&gt;
	 * 
	 * &lt;?
	 * $RESULT_ID = 189; // ID результата
	 * 
	 * // получим данные по всем вопросам
	 * $arAnswer = <b>CFormResult::GetDataByID</b>(
	 * 	$RESULT_ID, 
	 * 	array(), 
	 * 	$arResult, 
	 * 	$arAnswer2);
	 * 
	 * // выведем поля результата
	 * echo "&lt;pre&gt;"; print_r($arResult); echo "&lt;/pre&gt;";
	 * 
	 * // выведем значения ответов
	 * echo "&lt;pre&gt;"; print_r($arAnswer); echo "&lt;/pre&gt;";
	 * 
	 * // выведем значения ответов в несколько ином формате
	 * echo "&lt;pre&gt;"; print_r($arAnswer2); echo "&lt;/pre&gt;";
	 * ?&gt;
	 * </pre>
	 *
	 *
	 *
	 * <h4>See Also</h4> 
	 * <ul> <li> <a href="http://dev.1c-bitrix.ru/api_help/form/classes/cformresult/index.php">Поля CFormResult</a> </li>
	 * <li> <a href="http://dev.1c-bitrix.ru/api_help/form/classes/cform/index.php">Поля CForm</a> </li> <li> <a
	 * href="http://dev.1c-bitrix.ru/api_help/form/classes/cform/getresultanswerarray.php">CForm::GetResultAnswerArray</a>
	 * </li> </ul><a name="examples"></a>
	 *
	 *
	 * @static
	 * @link http://dev.1c-bitrix.ru/api_help/form/classes/cformresult/getdatabyid.php
	 * @author Bitrix
	 */
	public static function GetDataByID($RESULT_ID, $arrFIELD_SID, &$arrRES, &$arrANSWER)
	{
		global $DB, $strError;
		$err_mess = (CAllFormResult::err_mess())."<br>Function: GetDataByID<br>Line: ";
		$arrReturn = array();
		$RESULT_ID = intval($RESULT_ID);
		$z = CFormResult::GetByID($RESULT_ID);
		if ($arrRES = $z->Fetch())
		{
			if (is_array($arrFIELD_SID) && count($arrFIELD_SID)>0)
			{
				foreach($arrFIELD_SID as $field) $str .= ",'".$DB->ForSql($field,50)."'";
				$str = TrimEx($str,",");
				if (strlen($str)>0) $s = "and SID in ($str)";
			}
			$strSql = "SELECT ID, SID, SID as VARNAME FROM b_form_field WHERE FORM_ID='".$arrRES["FORM_ID"]."' ".$s;
			$q = $DB->Query($strSql, false, $err_mess.__LINE__);
			while ($qr = $q->Fetch())
			{
				$arrFIELDS[$qr["ID"]] = $qr["SID"];
			}
			if (is_array($arrFIELDS)) $arrKeys = array_keys($arrFIELDS);
			CForm::GetResultAnswerArray($arrRES["FORM_ID"], $arrColumns, $arrAnswers, $arrAnswersSID, array("RESULT_ID"=>$RESULT_ID));

			foreach ($arrAnswers[$RESULT_ID] as $fid => $arrAns)
			{
				if (is_array($arrKeys))
				{
					if (in_array($fid,$arrKeys))
					{
						$sid = $arrFIELDS[$fid];
						$arrANSWER[$sid] = $arrAns;
						$arrA = array_values($arrAns);
						foreach($arrA as $arr) $arrReturn[$sid][] = $arr;
					}
				}
			}
		}
		else return false;

		if (is_array($arrANSWER)) reset($arrANSWER);
		if (is_array($arrReturn)) reset($arrReturn);
		if (is_array($arrRES)) reset($arrRES);

		/*
		echo "<pre>arrRES\n";
		print_r($arrRES);
		echo "arrANSWER\n";
		print_r($arrANSWER);
		echo "arrReturn\n";
		print_r($arrReturn);
		echo "</pre>";
		*/

		return $arrReturn;
	}
Ejemplo n.º 18
0
 public static function GetWeightList($arSort = array(), $arFilter = array())
 {
     global $DB;
     $arSqlSearch = array();
     $strSqlSearch = "";
     $err_mess = CRatings::err_mess() . "<br>Function: GetWeightList<br>Line: ";
     if (is_array($arFilter)) {
         foreach ($arFilter as $key => $val) {
             if (strlen($val) <= 0 || $val == "NOT_REF") {
                 continue;
             }
             switch (strtoupper($key)) {
                 case "ID":
                     $arSqlSearch[] = GetFilterQuery("RW.ID", $val, "N");
                     break;
                 case "RATING_FROM":
                     $arSqlSearch[] = GetFilterQuery("RW.RATING_FROM", $val, "N");
                     break;
                 case "RATING_TO":
                     $arSqlSearch[] = GetFilterQuery("RW.RATING_TO", $val, "N");
                     break;
                 case "WEIGHT":
                     $arSqlSearch[] = GetFilterQuery("RW.WEIGHT", $val, "N");
                     break;
                 case "COUNT":
                     $arSqlSearch[] = GetFilterQuery("RW.COUNT", $val, "N");
                     break;
                 case "MAX":
                     if (in_array($val, array('Y', 'N'))) {
                         $arSqlSearch[] = "R.MAX = '" . $val . "'";
                     }
                     break;
             }
         }
     }
     $sOrder = "";
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($key)) {
             case "ID":
                 $sOrder .= ", RW.ID " . $ord;
                 break;
             case "RATING_FROM":
                 $sOrder .= ", RW.RATING_FROM " . $ord;
                 break;
             case "RATING_TO":
                 $sOrder .= ", RW.RATING_TO " . $ord;
                 break;
             case "WEIGHT":
                 $sOrder .= ", RW.WEIGHT " . $ord;
                 break;
             case "COUNT":
                 $sOrder .= ", RW.COUNT " . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = "RW.ID DESC";
     }
     $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\n\t\t\tSELECT\n\t\t\t\tRW.ID, RW.RATING_FROM, RW.RATING_TO, RW.WEIGHT, RW.COUNT\n\t\t\tFROM\n\t\t\t\tb_rating_weight RW\n\t\t\tWHERE\n\t\t\t" . $strSqlSearch . "\n\t\t\t" . $strSqlOrder;
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     return $res;
 }
Ejemplo n.º 19
0
<?php

require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/img.php";
global $arrSaveColor;
if (CModule::IncludeModule("vote")) {
    $diameter = intval($_REQUEST["dm"]) > 0 ? intval($_REQUEST["dm"]) : 150;
    $res = CVoteAnswer::GetList($qid, $by = "s_counter", $order = "desc");
    $res->NavStart(1000);
    $totalRecords = $res->SelectedRowsCount();
    $arChart = array();
    $color = "";
    $sum = 0;
    while ($arAnswer = $res->Fetch()) {
        $arChart[] = array("COLOR" => strlen($arAnswer["COLOR"]) > 0 ? TrimEx($arAnswer["COLOR"], "#") : ($color = GetNextRGB($color, $totalRecords)), "COUNTER" => $arAnswer["COUNTER"]);
        $sum += $arAnswer["COUNTER"];
    }
    // create an image
    $ImageHandle = CreateImageHandle($diameter, $diameter);
    imagefill($ImageHandle, 0, 0, imagecolorallocate($ImageHandle, 255, 255, 255));
    // drawing pie chart
    if ($sum > 0) {
        Circular_Diagram($ImageHandle, $arChart, "FFFFFF", $diameter, $diameter / 2, $diameter / 2);
    }
    // displaying of the resulting image
    ShowImageHeader($ImageHandle);
}
Ejemplo n.º 20
0
function TrimExAll($str,$symbol)
{
	while (substr($str,0,1)==$symbol or substr($str,strlen($str)-1,1)==$symbol)
		$str = TrimEx($str,$symbol);

	return $str;
}
Ejemplo n.º 21
0
	public function GetList($aSort=array(), $arFilter=Array())
	{
		global $DB;
		$arSqlSearch = Array();
		$strSqlSearch = "";
		if (is_array($arFilter))
		{
			$filter_keys = array_keys($arFilter);
			for ($i=0; $i<count($filter_keys); $i++)
			{
				$val = $arFilter[$filter_keys[$i]];
				if (strlen($val)<=0 || $val=="NOT_REF") continue;
				switch(strtoupper($filter_keys[$i]))
				{
				case "ID":
					$arSqlSearch[] = "ID=".intval($val);
					break;
				case "KEYS_STRING":
					$arSqlSearch[] = GetFilterQuery("KEYS_STRING", $val);
					break;
				case "CODE_ID":
					$arSqlSearch[] = "CODE_ID=".intval($val);
					break;
				case "USER_ID":
					$arSqlSearch[] = "USER_ID=".intval($val);
					break;
				}
			}
		}

		$sOrder = "";
		foreach($aSort as $key=>$val)
		{
			$ord = (strtoupper($val) <> "ASC"? "DESC":"ASC");
			switch (strtoupper($key))
			{
				case "ID":	$sOrder .= ", ID ".$ord; break;
				case "KEYS_STRING":	$sOrder .= ", KEYS_STRING ".$ord; break;
				case "CODE_ID":	$sOrder .= ", CODE_ID ".$ord; break;
				case "USER_ID":	$sOrder .= ", USER_ID ".$ord; break;
			}
		}

		if (strlen($sOrder)>0)
			$strSqlOrder = " ORDER BY ".TrimEx($sOrder,",");
		else
			$strSqlOrder="";

		$strSqlSearch = GetFilterSqlSearch($arSqlSearch);
		$strSql = "
			SELECT
				*
			FROM
				b_hot_keys
			WHERE
			".$strSqlSearch."
			".$strSqlOrder;
		$res = $DB->Query($strSql, false, $this->ErrOrig()." Line: ".__LINE__);
		return $res;
	}
Ejemplo n.º 22
0
 function SetMailTemplate($WEB_FORM_ID, $ADD_NEW_TEMPLATE = "Y", $old_SID = "", $bReturnFullInfo = false)
 {
     global $DB, $MESS, $strError;
     $err_mess = CAllForm::err_mess() . "<br>Function: SetMailTemplates<br>Line: ";
     $arrReturn = array();
     $WEB_FORM_ID = intval($WEB_FORM_ID);
     $q = CForm::GetByID($WEB_FORM_ID);
     if ($arrForm = $q->Fetch()) {
         $MAIL_EVENT_TYPE = "FORM_FILLING_" . $arrForm["SID"];
         if (strlen($old_SID) > 0) {
             $old_MAIL_EVENT_TYPE = "FORM_FILLING_" . $old_SID;
         }
         $et = new CEventType();
         $em = new CEventMessage();
         if (strlen($MAIL_EVENT_TYPE) > 0) {
             $et->Delete($MAIL_EVENT_TYPE);
         }
         $z = CLanguage::GetList($v1, $v2);
         $OLD_MESS = $MESS;
         while ($arLang = $z->Fetch()) {
             IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/form/admin/form_mail.php", $arLang["LID"]);
             $str = "";
             $str .= "#RS_FORM_ID# - " . GetMessage("FORM_L_FORM_ID") . "\n";
             $str .= "#RS_FORM_NAME# - " . GetMessage("FORM_L_NAME") . "\n";
             $str .= "#RS_FORM_SID# - " . GetMessage("FORM_L_SID") . "\n";
             $str .= "#RS_RESULT_ID# - " . GetMessage("FORM_L_RESULT_ID") . "\n";
             $str .= "#RS_DATE_CREATE# - " . GetMessage("FORM_L_DATE_CREATE") . "\n";
             $str .= "#RS_USER_ID# - " . GetMessage("FORM_L_USER_ID") . "\n";
             $str .= "#RS_USER_EMAIL# - " . GetMessage("FORM_L_USER_EMAIL") . "\n";
             $str .= "#RS_USER_NAME# - " . GetMessage("FORM_L_USER_NAME") . "\n";
             $str .= "#RS_USER_AUTH# - " . GetMessage("FORM_L_USER_AUTH") . "\n";
             $str .= "#RS_STAT_GUEST_ID# - " . GetMessage("FORM_L_STAT_GUEST_ID") . "\n";
             $str .= "#RS_STAT_SESSION_ID# - " . GetMessage("FORM_L_STAT_SESSION_ID") . "\n";
             $strFIELDS = "";
             $w = CFormField::GetList($WEB_FORM_ID, "ALL", $by, $order, array(), $is_filtered);
             while ($wr = $w->Fetch()) {
                 if (strlen($wr["RESULTS_TABLE_TITLE"]) > 0) {
                     $FIELD_TITLE = $wr["RESULTS_TABLE_TITLE"];
                 } elseif (strlen($wr["TITLE"]) > 0) {
                     $FIELD_TITLE = $wr["TITLE_TYPE"] == "html" ? htmlspecialcharsback(strip_tags($wr["TITLE"])) : $wr["TITLE"];
                 } else {
                     $FIELD_TITLE = TrimEx($wr["FILTER_TITLE"], ":");
                 }
                 $str .= "#" . $wr["SID"] . "# - " . $FIELD_TITLE . "\n";
                 $str .= "#" . $wr["SID"] . "_RAW# - " . $FIELD_TITLE . " (" . GetMessage('FORM_L_RAW') . ")\n";
                 $strFIELDS .= $FIELD_TITLE . "\n*******************************\n#" . $wr["SID"] . "#\n\n";
             }
             $et->Add(array("LID" => $arLang["LID"], "EVENT_NAME" => $MAIL_EVENT_TYPE, "NAME" => GetMessage("FORM_FILLING") . " \"" . $arrForm["SID"] . "\"", "DESCRIPTION" => $str));
         }
         // задаем новый тип событи¤ дл¤ старых шаблонов
         if (strlen($old_MAIL_EVENT_TYPE) > 0 && $old_MAIL_EVENT_TYPE != $MAIL_EVENT_TYPE) {
             $e = $em->GetList($by = "id", $order = "desc", array("EVENT_NAME" => $old_MAIL_EVENT_TYPE));
             while ($er = $e->Fetch()) {
                 $em->Update($er["ID"], array("EVENT_NAME" => $MAIL_EVENT_TYPE));
             }
             if (strlen($old_MAIL_EVENT_TYPE) > 0) {
                 $et->Delete($old_MAIL_EVENT_TYPE);
             }
         }
         if ($ADD_NEW_TEMPLATE == "Y") {
             $z = CSite::GetList($v1, $v2);
             while ($arSite = $z->Fetch()) {
                 $arrSiteLang[$arSite["ID"]] = $arSite["LANGUAGE_ID"];
             }
             $arrFormSite = CForm::GetSiteArray($WEB_FORM_ID);
             if (is_array($arrFormSite) && count($arrFormSite) > 0) {
                 foreach ($arrFormSite as $sid) {
                     IncludeModuleLangFile($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/form/admin/form_mail.php", $arrSiteLang[$sid]);
                     $SUBJECT = "#SERVER_NAME#: " . GetMessage("FORM_FILLING_S") . " [#RS_FORM_ID#] #RS_FORM_NAME#";
                     $MESSAGE = "#SERVER_NAME#\n\n" . GetMessage("FORM_FILLING") . ": [#RS_FORM_ID#] #RS_FORM_NAME#\n-------------------------------------------------------\n\n" . GetMessage("FORM_DATE_CREATE") . "#RS_DATE_CREATE#\n" . GetMessage("FORM_RESULT_ID") . "#RS_RESULT_ID#\n" . GetMessage("FORM_USER") . "[#RS_USER_ID#] #RS_USER_NAME# #RS_USER_AUTH#\n" . GetMessage("FORM_STAT_GUEST_ID") . "#RS_STAT_GUEST_ID#\n" . GetMessage("FORM_STAT_SESSION_ID") . "#RS_STAT_SESSION_ID#\n\n\n{$strFIELDS}\n" . GetMessage("FORM_VIEW") . "\nhttp://#SERVER_NAME#/bitrix/admin/form_result_view.php?lang=" . $arrSiteLang[$sid] . "&WEB_FORM_ID=#RS_FORM_ID#&RESULT_ID=#RS_RESULT_ID#\n\n-------------------------------------------------------\n" . GetMessage("FORM_GENERATED_AUTOMATICALLY") . "\n\t\t\t\t\t\t";
                     // добавл¤ем новый шаблон
                     $arFields = array("ACTIVE" => "Y", "EVENT_NAME" => $MAIL_EVENT_TYPE, "LID" => $sid, "EMAIL_FROM" => "#DEFAULT_EMAIL_FROM#", "EMAIL_TO" => "#DEFAULT_EMAIL_FROM#", "SUBJECT" => $SUBJECT, "MESSAGE" => $MESSAGE, "BODY_TYPE" => "text");
                     $TEMPLATE_ID = $em->Add($arFields);
                     if ($bReturnFullInfo) {
                         $arrReturn[] = array('ID' => $TEMPLATE_ID, 'FIELDS' => $arFields);
                     } else {
                         $arrReturn[] = $TEMPLATE_ID;
                     }
                 }
             }
         }
         $MESS = $OLD_MESS;
     }
     return $arrReturn;
 }
Ejemplo n.º 23
0
 function GetList($arOrder = array('CSORT' => 'ASC'), $arFilter = array(), $arFields = array())
 {
     global $DB;
     $arSqlSearch = array();
     $strSqlSearch = "";
     if (is_array($arFilter)) {
         $filter_keys = array_keys($arFilter);
         for ($i = 0, $cnt = count($filter_keys); $i < $cnt; $i++) {
             $val = $arFilter[$filter_keys[$i]];
             $key = $filter_keys[$i];
             switch (strtoupper($filter_keys[$i])) {
                 case "ID":
                     $arSqlSearch[] = 'ID=' . intval($val);
                     break;
                 case "ACTIVE":
                     $arSqlSearch[] = GetFilterQuery("ACTIVE", $val);
                     break;
                 case "NAME":
                     $match = $arFilter[$key . "_EXACT_MATCH"] == "Y" && $match_value_set ? "N" : "Y";
                     $arSqlSearch[] = GetFilterQuery("NAME", $val, $match);
                     break;
                 case "RATE":
                     $arSqlSearch[] = 'RATE=\'' . doubleval($val) . '\'';
                     //GetFilterQuery('RATE', $val);
                     break;
             }
         }
     }
     $sOrder = "";
     $sort_keys = array_keys($arOrder);
     for ($i = 0, $intCount = count($sort_keys); $i < $intCount; $i++) {
         $ord = strtoupper($arOrder[$sort_keys[$i]]) != "ASC" ? "DESC" : "ASC";
         switch (strtoupper($sort_keys[$i])) {
             case "ID":
                 $sOrder .= ", ID " . $ord;
                 break;
             case "C_SORT":
                 $sOrder .= ", C_SORT " . $ord;
                 break;
             case "ACTIVE":
                 $sOrder .= ", ACTIVE " . $ord;
                 break;
             case "NAME":
                 $sOrder .= ", NAME " . $ord;
                 break;
             case "RATE":
                 $sOrder .= ", RATE " . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = "C_SORT ASC";
     }
     $strSqlOrder = " ORDER BY " . TrimEx($sOrder, ",");
     $arDefaultFields = array('ID', 'TIMESTAMP_X', 'ACTIVE', 'C_SORT', 'NAME', 'RATE');
     if (!is_array($arFields) || count($arFields) <= 0) {
         $arQueryFields = $arDefaultFields;
     } else {
         $arQueryFields = array();
         foreach ($arFields as $fld) {
             if (in_array($fld, $arDefaultFields)) {
                 $arQueryFields[] = $fld;
             }
         }
         if (count($arQueryFields) <= 0) {
             $arQueryFields = $arDefaultFields;
         }
     }
     $strSqlFields = implode(', ', $arQueryFields);
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "\nSELECT\n" . $strSqlFields . "\nFROM b_catalog_vat\nWHERE\n" . $strSqlSearch . "\n" . $strSqlOrder . "\n";
     //echo $strSql;
     $res = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     $res->is_filtered = IsFiltered($strSqlSearch);
     return $res;
 }
Ejemplo n.º 24
0
 /**
  * <p>Метод производит выборку уведомлений с сортировкой и фильтрацией. Статичный метод.</p>
  *
  *
  * @param array $arSort = array() Сортировка осуществляется по: <ul> <li> <b>ID</b> - идентификатору
  * сообщения;</li> <li> <b>MODULE_ID</b> - идентификатору модуля, к которому
  * относится сообщение.</li> </ul>
  *
  * @param array $arFilter = array() Фильтрация осуществляется по: <ul> <li> <b>ID</b> - идентификатору
  * сообщения;</li> <li> <b>MODULE_ID</b> - идентификатору модуля, к которому
  * относится сообщение;</li> <li> <b>TAG</b> - тегу;</li> <li> <b>ENABLE_CLOSE</b>-
  * разрешению на ручное закрытие.</li> </ul>
  *
  * @return mixed <p>Возвращается экземляр класса <a
  * href="http://dev.1c-bitrix.ru/api_help/main/reference/cdbresult/index.php">CDBResult</a> для дальней
  * обработки.</p>
  *
  * <h4>Example</h4> 
  * <pre>
  * CAdminNotify::GetList(array('ID' =&gt; 'DESC'), array('MODULE_ID'=&gt;'main'));
  * </pre>
  *
  *
  * <h4>See Also</h4> 
  * <ul> <li> <a href="http://dev.1c-bitrix.ru/api_help/main/reference/cdbresult/index.php">CDBResult</a> </li> </ul><a
  * name="examples"></a>
  *
  *
  * @static
  * @link http://dev.1c-bitrix.ru/api_help/main/reference/cadminnotify/getlist.php
  * @author Bitrix
  */
 public static function GetList($arSort = array(), $arFilter = array())
 {
     global $DB;
     $arSqlSearch = array();
     $strSqlSearch = '';
     $err_mess = self::err_mess() . '<br />Function: GetList<br />Line: ';
     if (!is_array($arFilter)) {
         $arFilter = array();
     }
     if (!isset($arFilter['LID'])) {
         $arFilter['LID'] = LANGUAGE_ID;
     }
     if (!isset($arFilter['PUBLIC_SECTION'])) {
         $arFilter['PUBLIC_SECTION'] = 'N';
     }
     $strFrom = '';
     $strSelect = "AN.ID, AN.MODULE_ID, AN.TAG, AN.MESSAGE, AN.ENABLE_CLOSE, AN.PUBLIC_SECTION";
     if (is_array($arFilter)) {
         $filter_keys = array_keys($arFilter);
         for ($i = 0, $ic = count($filter_keys); $i < $ic; $i++) {
             $val = $arFilter[$filter_keys[$i]];
             if (strlen($val) <= 0 || $val == 'NOT_REF') {
                 continue;
             }
             switch (strtoupper($filter_keys[$i])) {
                 case 'ID':
                     $arSqlSearch[] = GetFilterQuery('AN.ID', $val, 'N');
                     break;
                 case 'MODULE_ID':
                     $arSqlSearch[] = GetFilterQuery('AN.MODULE_ID', $val);
                     break;
                 case 'TAG':
                     $arSqlSearch[] = GetFilterQuery('AN.TAG', $val);
                     break;
                 case 'MESSAGE':
                     $arSqlSearch[] = GetFilterQuery('AN.MESSAGE', $val);
                     break;
                 case 'ENABLE_CLOSE':
                     $arSqlSearch[] = $val == 'Y' ? "AN.ENABLE_CLOSE='Y'" : "AN.ENABLE_CLOSE='N'";
                     break;
                 case 'LID':
                     $strSelect .= ", ANL.MESSAGE as MESSAGE_LANG";
                     $strFrom = 'LEFT JOIN b_admin_notify_lang ANL ON (AN.ID = ANL.NOTIFY_ID AND ANL.LID = \'' . $DB->ForSQL($val) . '\')';
                     break;
                 case 'PUBLIC_SECTION':
                     $arSqlSearch[] = $val == 'Y' ? "AN.PUBLIC_SECTION='Y'" : "AN.PUBLIC_SECTION='N'";
             }
         }
     }
     $sOrder = '';
     foreach ($arSort as $key => $val) {
         $ord = strtoupper($val) != 'ASC' ? 'DESC' : 'ASC';
         switch (strtoupper($key)) {
             case 'ID':
                 $sOrder .= ', AN.ID ' . $ord;
                 break;
             case 'MODULE_ID':
                 $sOrder .= ', AN.MODULE_ID ' . $ord;
                 break;
             case 'ENABLE_CLOSE':
                 $sOrder .= ', AN.ENABLE_CLOSE ' . $ord;
                 break;
         }
     }
     if (strlen($sOrder) <= 0) {
         $sOrder = 'AN.ID DESC';
     }
     $strSqlOrder = ' ORDER BY ' . TrimEx($sOrder, ',');
     $strSqlSearch = GetFilterSqlSearch($arSqlSearch);
     $strSql = "SELECT " . $strSelect . " FROM b_admin_notify AN " . $strFrom . " WHERE " . $strSqlSearch . " " . $strSqlOrder;
     $res = $DB->Query($strSql, false, $err_mess . __LINE__);
     return $res;
 }
Ejemplo n.º 25
0
function CleanUpCsv(&$item)
{
    $item = TrimEx($item, "\"");
}
Ejemplo n.º 26
0
	public function GetList($aSort=array(), $arFilter=Array(), $getCommon=true)
	{
		global $DB;

		$err_mess = (CAdminFilter::err_mess())."<br>Function: GetList<br>Line: ";
		$arSqlSearch = Array();
		if (is_array($arFilter))
		{
			foreach ($arFilter as $key => $val)
			{
				if (strlen($val)<=0 || $val=="NOT_REF")
					continue;

				switch(strtoupper($key))
				{
				case "ID":
					$arSqlSearch[] = GetFilterQuery("F.ID",$val,"N");
					break;
				case "USER_ID":
					if($getCommon)
						$arSqlSearch[] = "F.USER_ID=".intval($val)." OR F.COMMON='Y'";
					else
						$arSqlSearch[] = "F.USER_ID = ".intval($val);
					break;
				case "FILTER_ID":
					$arSqlSearch[] = GetFilterQuery("F.FILTER_ID", $val);
					break;
				case "NAME":
					$arSqlSearch[] = GetFilterQuery("F.NAME", $val);
					break;
				case "FIELDS":
					$arSqlSearch[] = GetFilterQuery("F.FIELDS", $val);
					break;
				case "COMMON":
					$arSqlSearch[] = "F.COMMON = '".$DB->ForSql($val,1)."'";
					break;
				case "PRESET":
					$arSqlSearch[] = "F.PRESET = '".$DB->ForSql($val,1)."'";
					break;
				case "LANGUAGE_ID":
					$arSqlSearch[] = "F.LANGUAGE_ID = '".$DB->ForSql($val,2)."'";
					break;
				case "PRESET_ID":
					$arSqlSearch[] = GetFilterQuery("F.PRESET_ID", $val);
					break;
				case "SORT":
					$arSqlSearch[] = GetFilterQuery("F.SORT", $val);
					break;
				case "SORT_FIELD":
					$arSqlSearch[] = GetFilterQuery("F.SORT_FIELD", $val);
					break;
				}
			}
		}

		$sOrder = "";
		foreach($aSort as $key=>$val)
		{
			$ord = (strtoupper($val) <> "ASC"? "DESC":"ASC");
			switch (strtoupper($key))
			{
				case "ID":		$sOrder .= ", F.ID ".$ord; break;
				case "USER_ID":	$sOrder .= ", F.USER_ID ".$ord; break;
				case "FILTER_ID":	$sOrder .= ", F.FILTER_ID ".$ord; break;
				case "NAME":	$sOrder .= ", F.NAME ".$ord; break;
				case "FIELDS":	$sOrder .= ", F.FIELDS ".$ord; break;
				case "COMMON":	$sOrder .= ", F.COMMON ".$ord; break;
				case "PRESET":	$sOrder .= ", F.PRESET ".$ord; break;
				case "LANGUAGE_ID":	$sOrder .= ", F.LANGUAGE_ID ".$ord; break;
				case "PRESET_ID":	$sOrder .= ", F.PRESET_ID ".$ord; break;
				case "SORT":	$sOrder .= ", F.SORT ".$ord; break;
				case "SORT_FIELD":	$sOrder .= ", F.SORT_FIELD ".$ord; break;
			}
		}
		if (strlen($sOrder)<=0)
			$sOrder = "F.ID ASC";
		$strSqlOrder = " ORDER BY ".TrimEx($sOrder,",");

		$strSqlSearch = GetFilterSqlSearch($arSqlSearch,"noFilterLogic");
		$strSql = "
			SELECT
				F.ID, F.USER_ID, F.NAME, F.FILTER_ID, F.FIELDS, F.COMMON, F.PRESET, F.LANGUAGE_ID, F.PRESET_ID, F.SORT, F.SORT_FIELD
			FROM
				b_filters F
			WHERE
			".$strSqlSearch."
			".$strSqlOrder;

		$res = $DB->Query($strSql, false, $err_mess.__LINE__);
		return $res;
	}
Ejemplo n.º 27
0
 function Update($table, $arFields, $WHERE = "", $error_position = "", $DEBUG = false, $ignore_errors = false)
 {
     $rows = 0;
     if (is_array($arFields)) {
         while (list($field, $value) = each($arFields)) {
             $str .= strlen($value) <= 0 ? $field . " = '', " : $field . " = " . $value . ", ";
         }
         $str = TrimEx($str, ",");
         $strSql = "UPDATE " . $table . " SET " . $str . " " . $WHERE;
         if ($DEBUG) {
             echo "<br>" . $strSql . "<br>";
         }
         $w = $this->Query($strSql, $ignore_errors, $error_position);
         $rows = $w->AffectedRowsCount();
         if ($DEBUG) {
             echo "affected_rows = " . $rows . "<br>";
         }
     }
     return $rows;
 }