Example #1
0
function deleteFiles($order_id, $types)
{
    $types = !is_array($types) ? array($types) : $types;
    $rows = CFile::selectFilesBySrc('file_reserves_order', $order_id);
    if (!$rows) {
        return 0;
    }
    foreach ($rows as $row) {
        if (!in_array($row['doc_type'], $types)) {
            continue;
        }
        $file = new CFile();
        $file->Delete($row['id']);
    }
}
Example #2
0
 /**
  * Удаление файлов указанных типов
  * @todo Удалять из очереди тоже нужно наверно
  * 
  * @param type $srcId
  * @param type $types
  * @return boolean
  */
 public function deleteFiles($srcId, $types)
 {
     $types = !is_array($types) ? array($types) : $types;
     $this->clearQueue($srcId, $types);
     $rows = CFile::selectFilesBySrc($this->file_table, $srcId);
     if (!$rows) {
         return false;
     }
     foreach ($rows as $row) {
         if (!in_array($row['doc_type'], $types)) {
             continue;
         }
         $file = new CFile();
         $file->Delete($row['id']);
     }
     return true;
 }
Example #3
0
 /**
  * Получить список файлов сообщения.
  *  
  * @param type $msg_id
  *
  * @return type
  */
 public function getAttached($msg_id)
 {
     return CFile::selectFilesBySrc($this->TABLE_FILES, $msg_id, 'id');
     //return $this->db()->rows("SELECT * FROM {$this->TABLE_FILES} WHERE src_id = ?i", $msg_id);
 }
Example #4
0
 /**
  * Вспомогательная функция для получения аттачей и опросов для сообществ
  * 
  * @param type $aReturn 
  */
 function _getCommunityAttachPoll(&$aReturn = array())
 {
     // ответы на опросы -----
     $ids = '';
     $lnk = array();
     for ($i = 0, $c = count($aReturn); $i < $c; $i++) {
         if (!$aReturn[$i]['parent_id']) {
             $ids .= ",{$aReturn[$i]['theme_id']}";
             $lnk[$aReturn[$i]['theme_id']] =& $aReturn[$i];
         }
     }
     if ($ids) {
         $res = $GLOBALS['DB']->rows("SELECT * FROM commune_poll_answers WHERE theme_id IN (" . substr($ids, 1) . ") ORDER BY id");
         if ($res) {
             foreach ($res as $row) {
                 $lnk[$row['theme_id']]['answers'][] = $row;
             }
         }
     }
     //-----------------------
     // аттачи ---------------
     $id_attach = $x = array();
     foreach ($aReturn as $k => $v) {
         $x[$v['id']] = $v;
         if ($v['file_exists']) {
             $id_attach[$v['id']] = $v['id'];
         }
     }
     if ($id_attach) {
         //$ret = $GLOBALS['DB']->rows("SELECT file.*, commune_attach.cid, commune_attach.small FROM commune_attach JOIN file_commune as file ON file.id = commune_attach.fid WHERE commune_attach.cid IN (".implode(", ", $id_attach).")");
         $ret = CFile::selectFilesBySrc(commune::FILE_TABLE, $id_attach);
         if ($ret) {
             foreach ($ret as $k => $val) {
                 $x[$val['src_id']]['attach'][] = $val;
             }
             foreach ($x as $k => $val) {
                 $r[] = $val;
             }
             $aReturn = $r;
         }
     }
     //-----------------------
 }
Example #5
0
 /**
  * Получаем услугу, принадлежащую текущему пользователю, по ID и
  * заполняем свойства обьекта.
  * 
  * @param type $id
  *
  * @return bool
  */
 public function getByID($id)
 {
     $row = $this->db()->row("\n            SELECT \n                s.*,\n                COALESCE((sc.sbr_minus + sc.order_minus),0) AS minus_feedbacks\n            FROM {$this->TABLE} AS s \n            LEFT JOIN {$this->TABLE_COUNTERS} AS sc ON sc.service_id = s.id\n            WHERE \n                s.deleted = FALSE \n                AND s.user_id = ?i \n                AND s.id = ?i", $this->uid, $id);
     if ($this->arrayToFieldsProps($row)) {
         $tservices_tags = new tservices_tags();
         $this->tags = $tservices_tags->getsByTServiceId($id);
         $this->images = CFile::selectFilesBySrc($this->TABLE_FILES, $id, 'id', 'small = 1 AND preview=\'f\'');
         $this->preview = CFile::selectFilesBySrc($this->TABLE_FILES, $id, 'id', 'small = 1 AND preview=\'t\'');
         $this->is_angry = $row['minus_feedbacks'] > 0;
         return true;
     }
     return false;
 }
Example #6
0
 /**
  * Связывает файлы загруженные ассинхронно с сообщением
  *
  * @param   array     $files              Список загруженных файлов
  * @param   string    $login              Логин пользователя
  * @param   integer   $msg_id             ID сообщения
  * @param   boolean   $from_draft         Файлы из черновика
  */
 function addAttachedFiles($files, $msg_id, $login = NULL, $from_draft = false)
 {
     global $DB;
     if (!$login) {
         $login = $_SESSION['login'];
     }
     $bModeration = false;
     $old_files = $this->getAttachedFiles($msg_id);
     if ($from_draft) {
         $notdeleted_files = array();
         if ($files) {
             foreach ($files as $f) {
                 if ($f['status'] == 3 || in_array($f['id'], $old_files)) {
                     array_push($notdeleted_files, $f['id']);
                 }
             }
         }
         $attaches = CFile::selectFilesBySrc(self::FILE_TABLE, $msg_id);
         if ($attaches) {
             foreach ($attaches as $attach) {
                 if (in_array($attach['id'], $notdeleted_files)) {
                     continue;
                 }
                 $cFile = new CFile($attach['id']);
                 $cFile->table = self::FILE_TABLE;
                 if ($cFile->id) {
                     $cFile->Delete($cFile->id);
                 }
             }
         }
     }
     $max_image_size = array('width' => blogs::MAX_IMAGE_WIDTH, 'height' => blogs::MAX_IMAGE_HEIGHT, 'less' => 0);
     if ($files) {
         foreach ($files as $file) {
             switch ($file['status']) {
                 case 4:
                     // Удаляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->table = self::FILE_TABLE;
                     if ($cFile->id) {
                         $cFile->Delete($cFile->id);
                     }
                     break;
                 case 1:
                     if (in_array($file['id'], $old_files)) {
                         $need_copy = false;
                     } else {
                         $bModeration = true;
                         $need_copy = true;
                     }
                     // Добавляем файл
                     $cFile = new CFile($file['id']);
                     $cFile->proportional = 1;
                     $cFile->table = self::FILE_TABLE;
                     $ext = $cFile->getext();
                     if ($need_copy) {
                         $tmp_dir = "users/" . substr($login, 0, 2) . "/" . $login . "/upload/";
                         $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext);
                         $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir));
                         $cFile->_remoteCopy($tmp_dir . $tmp_name, true);
                     }
                     if (in_array($ext, $GLOBALS['graf_array'])) {
                         $is_image = TRUE;
                     } else {
                         $is_image = FALSE;
                     }
                     if ($is_image && $ext != 'swf' && $ext != 'flv') {
                         if ($cFile->image_size['width'] > $max_image_size['width'] || $cFile->image_size['height'] > $max_image_size['height']) {
                             if ($need_copy) {
                                 if ($cFile->resizeImage($cFile->path . 'sm_' . $cFile->name, $max_image_size['width'], $cFile->image_size['height'], 'landscape')) {
                                     $cFile->small = 2;
                                 }
                             } else {
                                 $cFile->small = 2;
                             }
                         } else {
                             $cFile->small = 1;
                         }
                     } else {
                         $cFile->small = $ext == 'flv' ? 2 : 0;
                     }
                     $cFile->updateFileParams(array('src_id' => $msg_id, 'small' => $cFile->small), false);
                     break;
             }
         }
     }
     if ($bModeration && $login == $_SESSION['login'] && !hasPermissions('blogs')) {
         // отравляем сообщение на модерирование сразу по факту создания или редактирования
         // появились новые файлы и это правит автор, и он не админ и не ПРО - отправить на модерирование
         /*require_once( $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php' );
           $DB->query( 'UPDATE blogs_msgs SET moderator_status = 0 WHERE id = ?i', $msg_id );
           $DB->insert( 'moderation', array('rec_id' => $msg_id, 'rec_type' => user_content::MODER_BLOGS) );*/
     }
 }
Example #7
0
 /**
  * Получаем блоки (элементы) ленты по пользователю
  * Получаем единый массив данных, необходимых для вывода элементов ленты. Разделением между топиком сообщества и работой портфолио
  * может служить, например, член массива .portfolio_id, у сообществ он NULL. В запросе pf.post_date может быть NULL, так как
  * поле portfolio.post_date заведено совсем недавно.
  *
  * @param integer $user_id           id пользователя
  * @param integer $my_team_checked   истина, если стоит галка "Моя команда" или "Рекоммендованые мной".
  * @param integer $all_profs_checked истина, если стоит галка "Все разделы".
  * @param mixed $prof_groups         строка идентификаторов групп профессий, разделенных запятыми.
  * @param mixed $communes            строка идентификаторов сообществ, разделенных запятыми.
  * @param integer $offset            SQL OFFSET
  * @param string $limit              SQL LIMIT
  * @param integer &$count=-1         количество работ, если пользователь определил в настройках разделы или стоит галка "Все разделы". Количество тем сообществ, считается отдельно
  * @param mixed $blog_groups         строка идентификаторов разделов блогов, разделенных запятыми.
  *
  * @return array                     массив тем в случае успеха, 0 в случае неудачи
  */
 function GetLentaItems($user_id, $my_team_checked = 0, $all_profs_checked = 0, $prof_groups = NULL, $communes = NULL, $offset = 0, $limit = 'ALL', &$count = -1, $blog_groups = NULL)
 {
     global $DB;
     if ($my_team_checked) {
         $DBProxy = new DB('plproxy');
         $sql = "SELECT uid FROM teams_get(?i);";
         $quids_team = $DBProxy->rows($sql, $user_id);
         $uids_team = array();
         $uids_team[] = 0;
         if ($quids_team) {
             foreach ($quids_team as $uid_team) {
                 $uids_team[] = $uid_team['uid'];
             }
         }
     }
     $sql = "\n        SELECT \n               li.*,\n               u.is_banned::int as user_is_banned,\n               u.is_pro as user_is_pro,\n               u.is_profi AS user_is_profi,\n               u.is_team as user_is_team,\n               u.is_pro_test as user_is_pro_test,\n               u.role as user_role,\n               u.login as user_login,\n               u.photo as user_photo,\n               u.usurname as user_usurname,\n               u.uname as user_uname,\n               u.reg_date, u.is_chuck, u.is_verify\n          FROM\n          (" . (!$all_profs_checked && !$prof_groups ? '' : "\n                SELECT\n                       1 as item_type,\n                       pf.user_id as user_id, \n                       pf.post_date as post_time,\n                       NULL as id,\n                       'PF-' || pf.id as key,\n                       NULL::integer as parent_id,\n                       NULL::integer as theme_id,\n                       NULL as msgtext,\n                       NULL as title,\n                       NULL::integer as deleted_id,\n                       NULL::integer as modified_id,\n                       NULL as created_time,\n                       NULL as deleted_time,\n                       NULL as modified_time,\n                       NULL as file_exists,\n                       NULL::integer as commune_id,\n                       NULL as a_count,\n                       NULL as is_blocked,\n                       NULL as last_activity,\n                       NULL::integer as commune_group_id,\n                       NULL as commune_group_name,\n                       NULL as commune_name,\n                       NULL::integer as commune_author_id,\n                       NULL as member_warn_count,\n                       NULL::integer as member_id,\n                       NULL as member_is_banned,\n                       NULL as member_is_admin,\n                       NULL as last_viewed_time,\n                       NULL as modified_login,\n                       NULL as modified_usurname,\n                       NULL as modified_uname,\n                       NULL as modified_by_commune_admin,\n                       pf.id as portfolio_id,\n                       pf.name as name,\n                       pf.link as link,\n                       pf.descr as descr,\n                       pf.pict as pict,\n                       pf.prev_pict as prev_pict,\n                       pf.prof_id as prof_id,\n                       p.name as prof_name,\n                       p.id as prof_id, \n                       NULL as question,\n                       NULL::boolean as poll_closed,\n\t\t\t\t\t   NULL::boolean as poll_multiple,\n                       NULL::bigint as poll_votes,\n                       NULL::boolean as close_comments,\n                       NULL as is_private,\n                       NULL::smallint as current_count,\nNULL as dfl_title,\nNULL as dfl_description,\nNULL as dfl_type,\n0 as dfl_jury_id,\nNULL as dfl_image,\n0 as dfl_type_id,\nNULL as yt_link,\n0 as count_comments,\n0 as status_comments,\n/*pf.moderator_status,*/\npfb.admin AS work_is_blocked\n                  FROM\n                  (\n                    SELECT DISTINCT COALESCE(m.main_prof, p.id) as id\n                      FROM prof_group pg\n                    INNER JOIN\n                      professions p\n                        ON p.prof_group = pg.id\n                    LEFT JOIN\n                      mirrored_professions m\n                        ON m.mirror_prof = p.id\n                    " . (!$prof_groups ? '' : " WHERE pg.id IN ({$prof_groups})") . "\n                  ) as px\n                INNER JOIN\n                  portf_choise pc\n                    ON pc.prof_id = px.id\n                   AND pc.user_id <> {$user_id}\n                INNER JOIN\n                  professions p\n                    ON p.id = COALESCE(pc.prof_origin, pc.prof_id)\n                INNER JOIN\n                  portfolio pf\n                    ON pf.prof_id = pc.prof_id\n                   AND pf.user_id = pc.user_id\n                   AND pf.post_date > now()  - '1 month'::interval\n                   /*AND (pf.moderator_status != 0 OR pf.moderator_status IS NULL)*/\n                   " . (!$my_team_checked ? '' : " \n                      AND pf.user_id IN (?l)\n                    ") . "LEFT JOIN\n                    portfolio_blocked AS pfb\n                      ON pfb.src_id = pf.id" . ($communes || $blog_groups ? " UNION ALL" : '') . "\n                ") . (!$communes ? '' : "\n                SELECT \n                       2 as item_type,\n                       ms.user_id as user_id,\n                       ms.created_time as post_time,\n                       ms.id as id,\n                       'CM-' || ms.id as key,\n                       ms.parent_id as parent_id,\n                       ms.theme_id as theme_id,\n                       ms.msgtext as msgtext,\n                       ms.title as title,\n                       ms.deleted_id as deleted_id,\n                       ms.modified_id as modified_id,\n                       ms.created_time as created_time,\n                       ms.deleted_time as deleted_time,\n                       ms.modified_time as modified_time,\n                       ms.cnt_files as file_exists,\n                       t.commune_id as commune_id,\n                       t.a_count as a_count,\n                       (CASE WHEN ctb.blocked_time IS NOT NULL THEN ctb.blocked_time\n                             WHEN t.blocked_time IS NOT NULL THEN t.blocked_time\n                             WHEN ms.deleted_time IS NOT NULL THEN ms.deleted_time\n                             ELSE NULL END) as is_blocked,\n                       t.last_activity as last_activity,\n                       cg.id as commune_group_id,\n                       cg.name as commune_group_name,\n                       cm.name as commune_name,\n                       cm.author_id as commune_author_id,\n                       m.warn_count as member_warn_count,\n                       m.id as member_id,\n                       m.is_banned::int as member_is_banned,\n                       m.is_admin::int as member_is_admin,\n                       um.last_viewed_time as last_viewed_time,\n                       umm.login as modified_login,\n                       umm.usurname as modified_usurname,\n                       umm.uname as modified_uname,\n                       (am.user_id IS NOT NULL)::int as modified_by_commune_admin,\n                       NULL as portfolio_id,\n                       NULL as name,\n                       NULL as link,\n                       NULL as descr,\n                       NULL as pict,\n                       NULL as prev_pict,\n                       NULL as prof_id,\n                       NULL as prof_name,\n                       NULL as prof_id, \n    \t\t\t\t   cp.question as question,\n    \t\t\t\t   cp.closed as poll_closed,\n\t\t\t\t\t   cp.multiple as poll_multiple,\n    \t\t\t\t   cv._cnt as poll_votes,\n                       t.close_comments as closed_comments,\n                       t.is_private as is_private,\n                       um.current_count as current_count,\nNULL as dfl_title,\nNULL as dfl_description,\nNULL as dfl_type,\n0 as dfl_jury_id,\nNULL as dfl_image,\n0 as dfl_type_id,\nms.youtube_link as yt_link,\nt.a_count-1 as count_comments,\num.current_count as status_comments,\n/*ms.moderator_status, */\nNULL AS work_is_blocked\n                 FROM commune_themes t\n               INNER JOIN\n                 commune cm\n                   ON cm.id = t.commune_id\n               INNER JOIN\n                 commune_groups cg\n                   ON cg.id = cm.group_id\n               INNER JOIN\n                 commune_messages ms\n                   ON ms.theme_id = t.id\n                  AND ms.parent_id IS NULL\n                  AND ms.created_time > now()  - '1 month'::interval\n                  /*AND (ms.moderator_status != 0 OR ms.moderator_status IS NULL)*/\n               LEFT JOIN\n                 commune_members m\n                   ON m.user_id = ms.user_id\n                  AND m.commune_id = t.commune_id\n               LEFT JOIN\n                 users umm\n                   ON umm.uid = ms.modified_id\n               LEFT JOIN\n                 commune_members am\n                   ON am.user_id = umm.uid\n                  AND am.commune_id = cm.id\n                  AND am.is_admin = true\n\t\t\tLEFT JOIN\n\t\t\t  commune_poll cp\n\t\t\t    ON cp.theme_id = ms.theme_id\n            LEFT JOIN\n                commune_theme_blocked ctb\n                ON ctb.theme_id = t.id\n\t\t\tLEFT JOIN\n\t\t\t  (SELECT theme_id, COUNT(answer_id) AS _cnt FROM commune_poll_votes WHERE user_id = {$user_id} GROUP BY theme_id) cv\n\t\t\t    ON cv.theme_id = ms.theme_id\n               LEFT JOIN\n                 commune_users_messages um\n                   ON um.message_id = ms.id\n                  AND um.user_id = {$user_id}\n                WHERE t.commune_id IN ({$communes})\n                " . ($blog_groups ? " UNION ALL" : '')) . (!$blog_groups ? '' : "\nSELECT \n                    4 as item_type,\n                    bm.fromuser_id as user_id,\n                    bm.post_time as post_time,\n                    bm.id as id,\n                    'BL-' || bm.id as key,\n                    NULL as parent_id,\n                    b.thread_id as theme_id,\n                    bm.msgtext as msgtext,\n                    bm.title as title,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    bg.id as commune_group_id,\n                    bg.t_name as commune_group_name,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    bp.question as question,\n                    bp.closed as poll_closed,\n\t\t\t\t\tbp.multiple as poll_multiple,\n                    bv._cnt as poll_votes,\n                    b.close_comments as closed_comments,\n                    NULL,\n                    w.status AS current_count,\nNULL,\nNULL,\nNULL,\nNULL,\nNULL,\nNULL,\nbm.yt_link as yt_link,\n(b.messages_cnt-1) as count_comments ,\nw.status as status_comments,\n/*bm.moderator_status, */\nNULL AS work_is_blocked \nFROM blogs_themes b \nINNER JOIN blogs_msgs_" . date('Y') . " bm\n        ON bm.thread_id = b.thread_id\n       AND bm.reply_to IS NULL\n       AND (b.is_private='f' OR bm.fromuser_id={$user_id})\n       AND bm.post_time > now()  - '1 month'::interval\n       /*AND (bm.moderator_status != 0 OR bm.moderator_status IS NULL)*/\nLEFT JOIN blogs_blocked ON blogs_blocked.thread_id = b.thread_id\nINNER JOIN blogs_groups bg\n        ON bg.id = b.id_gr\nLEFT JOIN blogs_poll bp\n        ON bp.thread_id = bm.thread_id\nLEFT JOIN (SELECT thread_id, COUNT(answer_id) AS _cnt FROM blogs_poll_votes WHERE user_id = {$user_id} GROUP BY thread_id) bv\n        ON bv.thread_id = bm.thread_id\nLEFT JOIN (SELECT * FROM blogs_themes_watch WHERE user_id = '{$user_id}') AS w ON (theme_id=b.thread_id)\n\n   \nWHERE b.id_gr IN ({$blog_groups}) AND bm.deleted IS NULL AND blogs_blocked.thread_id IS NULL\n\n                " . (date('n') < 2 ? " \n                \n                UNION ALL\n                \n                SELECT \n                    4 as item_type,\n                    bm.fromuser_id as user_id,\n                    bm.post_time as post_time,\n                    bm.id as id,\n                    'BL-' || bm.id as key,\n                    NULL as parent_id,\n                    b.thread_id as theme_id,\n                    bm.msgtext as msgtext,\n                    bm.title as title,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    bg.id as commune_group_id,\n                    bg.t_name as commune_group_name,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    NULL,\n                    bp.question as question,\n                    bp.closed as poll_closed,\n\t\t\t\t\tbp.multiple as poll_multiple,\n                    bv._cnt as poll_votes,\n                    b.close_comments as closed_comments,\n                    NULL,\n                    w.status AS current_count,\nNULL,\nNULL,\nNULL,\nNULL,\nNULL,\nNULL,\nbm.yt_link as yt_link,\n(b.messages_cnt-1) as count_comments ,\nw.status as status_comments,\n/*bm.moderator_status, */\nNULL AS work_is_blocked \nFROM blogs_themes b \nINNER JOIN blogs_msgs_" . (date('Y') - 1) . " bm\n        ON bm.thread_id = b.thread_id\n       AND bm.reply_to IS NULL\n       AND (b.is_private='f' OR bm.fromuser_id={$user_id})\n       AND bm.post_time > now()  - '1 month'::interval\n       /*AND (bm.moderator_status != 0 OR bm.moderator_status IS NULL)*/\nLEFT JOIN blogs_blocked ON blogs_blocked.thread_id = b.thread_id\nINNER JOIN blogs_groups bg\n        ON bg.id = b.id_gr\nLEFT JOIN blogs_poll bp\n        ON bp.thread_id = bm.thread_id\nLEFT JOIN (SELECT thread_id, COUNT(answer_id) AS _cnt FROM blogs_poll_votes WHERE user_id = {$user_id} GROUP BY thread_id) bv\n        ON bv.thread_id = bm.thread_id\nLEFT JOIN (SELECT * FROM blogs_themes_watch WHERE user_id = '{$user_id}') AS w ON (theme_id=b.thread_id)\n\n   \nWHERE b.id_gr IN ({$blog_groups}) AND bm.deleted IS NULL AND blogs_blocked.thread_id IS NULL\n\n                " : '')) . "\n\n          ) AS li\n        INNER JOIN\n          users u\n            ON u.uid = li.user_id\n           AND u.is_banned = '0'\n            \n\n        ORDER BY li.post_time DESC" . ($all_profs_checked || $prof_groups ? ', li.portfolio_id DESC' : '') . "\n        LIMIT {$limit} OFFSET {$offset}\n      ";
     $res = $DB->rows($sql, $uids_team);
     if ($res) {
         foreach ($res as $row) {
             $ret[$row['key']] = $row;
             if ($row['item_type'] == 2) {
                 $ids2[] = $row['id'];
             }
             if ($row['item_type'] == 4) {
                 $ids4[] = $row['id'];
             }
             //            if($row['id']) $ids[] = $row['id'];
         }
         if ($ids2) {
             //$sql = "SELECT file.*, commune_attach.cid, commune_attach.small FROM commune_attach JOIN file_commune as file ON file.id = commune_attach.fid WHERE commune_attach.cid IN (".implode(", ", $ids2).")";
             //$res2 = $DB->rows($sql);
             $res2 = CFile::selectFilesBySrc(commune::FILE_TABLE, $ids2);
             foreach ($res2 as $row) {
                 $ret['CM-' . $row['src_id']]['attach'][] = $row;
             }
         }
         if ($ids4) {
             $sql = 'SELECT * FROM file_blogs WHERE src_id IN (?l)';
             $res2 = $DB->rows($sql, $ids4);
             foreach ($res2 as $row) {
                 $ret['BL-' . $row['src_id']]['attach'][] = $row;
             }
         }
         $count = 0;
         if ($all_profs_checked || $prof_groups || $communes || $blog_groups) {
             $sql = "SELECT SUM(items.count) as count FROM (" . (!$all_profs_checked && !$prof_groups ? '' : "\n                            SELECT\n                                COUNT(pf.id) as count\n                            FROM (\n                                    SELECT DISTINCT COALESCE(m.main_prof, p.id) as id\n                                    FROM prof_group pg\n                                    INNER JOIN professions p ON p.prof_group = pg.id\n                                    LEFT JOIN mirrored_professions m ON m.mirror_prof = p.id\n                                    " . (!$prof_groups ? '' : " WHERE pg.id IN ({$prof_groups})") . "\n                                 ) as px\n                             INNER JOIN portf_choise pc\n                                     ON pc.prof_id = px.id\n                                    AND pc.user_id <> {$user_id}\n                             INNER JOIN professions p\n                                     ON p.id = COALESCE(pc.prof_origin, pc.prof_id)\n                             INNER JOIN portfolio pf\n                                     ON pf.prof_id = pc.prof_id\n                                    AND pf.user_id = pc.user_id\n                                    AND pf.post_date > now()  - '1 month'::interval" . (!$my_team_checked ? '' : " \n                      AND pf.user_id IN (" . implode(',', $uids_team) . ")\n                    ") . ($communes || $blog_groups ? " UNION ALL" : '')) . (!$communes ? '' : "\n                            SELECT \n                                COUNT(ms.id) as count\n                            FROM commune_themes t\n                            INNER JOIN commune_messages ms \n                                    ON ms.theme_id = t.id\n                                   AND ms.parent_id IS NULL\n                                   AND ms.created_time > now()  - '1 month'::interval\n                            INNER JOIN users u\n                                    ON u.uid = ms.user_id\n                                   AND u.is_banned = '0'\n                            WHERE t.commune_id IN ({$communes})\n                        " . ($blog_groups ? " UNION ALL" : '')) . (!$blog_groups ? '' : "\n                            SELECT COUNT(1) as count\n                              FROM blogs_themes b \n                             WHERE b.id_gr IN ({$blog_groups}) AND b.deleted IS NULL AND b.is_blocked = false\n                               AND (b.is_private='f' OR b.fromuser_id={$user_id})\n                               AND b.post_time > now()  - '1 month'::interval\n                        ") . ") as items";
             /*
                       $sql =
                       "
                         SELECT COUNT(pf.id) as count
                               FROM prof_group pg
                             INNER JOIN
                               professions p
                                 ON p.prof_group = pg.id
                             INNER JOIN
                               portf_choise pc
                                 ON pc.prof_id = p.id
                                AND pc.user_id <> {$user_id}
                             INNER JOIN
                               portfolio pf
                                 ON pf.prof_id = pc.prof_id
                                AND pf.user_id = pc.user_id
                             INNER JOIN
                               freelancer f
                                 ON f.uid = pf.user_id
                                AND f.is_banned = '0'".
                             (
                               !$my_team_checked
                               ? ''
                               : " INNER JOIN
                                     teams tm
                                       ON tm.target_id = f.uid
                                      AND tm.user_id = {$user_id}"
                           ).
                         " WHERE pf.post_date > now() - '1 month'::interval "
                         .
                         ( !$prof_groups ? '' : " AND pg.id IN ({$prof_groups})" );
             */
             $memBuff = new memBuff();
             $count_arr = $memBuff->getSql($error, $sql, 120);
             if (!$error) {
                 $count = $count_arr[0]['count'];
             }
         }
         return $ret;
     }
     return 0;
 }
 /**
  * Создание архива документов 
  * по последней задаче
  * 
  * Рекомендуется запускать 
  * в кроне с интервалом 1-2 минуты
  * 
  * @return boolean
  * @throws Exception
  */
 public function generateArchive()
 {
     //Получаем последнюю задачу на создания архива
     $last = $this->db()->row("\n            SELECT \n                rda.*,\n                u.email\n            FROM " . self::$_TABLE_ARCHIVE . " AS rda\n            LEFT JOIN users AS u ON u.uid = rda.uid\n            WHERE \n                rda.status IN(0,-1) \n                AND rda.try_count < ?i\n            ORDER BY rda.id DESC, rda.status DESC\n            LIMIT 1\n        ", self::TRY_COUNT);
     if (!$last) {
         return false;
     }
     $archObj = new ReservesArchiveItemModel($last);
     //Ставим статус в работе
     $this->updateArchive($archObj->id, array('status' => self::STATUS_INPROGRESS));
     try {
         //Получаем файлы документов
         require_once ABS_PATH . '/classes/reserves/ReservesTServiceOrderModel.php';
         $bs_ids = $archObj->getFields();
         $files = CFile::selectFilesBySrc(ReservesTServiceOrderModel::$_TABLE_RESERVES_FILES, $bs_ids, NULL, $this->db()->parse('doc_type IN(?l)', $this->doc_req));
         if (!$files) {
             throw new Exception('Нет файлов документов');
         }
         $_archive_dir = uniqid();
         $_archive_path = self::TMP_PATH . $_archive_dir . DIRECTORY_SEPARATOR;
         $_dav_temp_path = self::DAV_TMP_PATH . $_archive_dir . DIRECTORY_SEPARATOR;
         $filelist = array();
         $cfile = new CFile();
         if (!$cfile->MakeDir(trim($_dav_temp_path, '/'))) {
             throw new Exception('Не удалось создать временную директорию в хранилище');
         }
         //Формируем массив файлов для архива
         foreach ($files as $file) {
             $cfile->name = $file['fname'];
             $cfile->path = $file['path'];
             $info = new SplFileInfo($file['fname']);
             $_ext = $info->getExtension();
             $name = $info->getBasename(".{$_ext}");
             //Создаем временную директорию для файлов на локальной файловой системе
             $_local_tmp_path = "{$_archive_path}{$file['src_id']}/";
             if (!file_exists($_local_tmp_path)) {
                 if (!mkdir($_local_tmp_path, 0777, true)) {
                     throw new Exception("Нет прав на создание: {$_local_tmp_path}");
                 }
             }
             //Сколько копий документа сделать в зависимости от его типа
             $doc_cnt = isset($this->doc_type_cnt[$file['doc_type']]) && $this->doc_type_cnt[$file['doc_type']] > 1 ? $this->doc_type_cnt[$file['doc_type']] : 1;
             $_prefix = sprintf('%07d-', $file['src_id']);
             while ($doc_cnt > 0) {
                 $_suffix = $doc_cnt > 1 ? "-{$doc_cnt}" : '';
                 $_dav_tmp_filename = "{$_dav_temp_path}{$name}{$_suffix}.{$_ext}";
                 if (!$cfile->copyFileTo($_dav_tmp_filename)) {
                     throw new Exception("Не удалось скопировать: {$_dav_tmp_filename}");
                 }
                 $_tmp_name = empty($file['original_name']) ? $name : $file['original_name'];
                 $_local_tmp_filename = "{$_local_tmp_path}{$_prefix}{$_tmp_name}{$_suffix}.{$_ext}";
                 //Кодировка имен файлов для Windows
                 $_local_tmp_filename = iconv('WINDOWS-1251', 'CP866', $_local_tmp_filename);
                 //$_local_tmp_filename = iconv('WINDOWS-1251', 'UTF-8', $_local_tmp_filename);
                 $filelist[$_dav_tmp_filename] = $_local_tmp_filename;
                 //Перемещаем нужные документы из хранища во временную папку
                 if (!$cfile->copyToLocalPathFromDav($_dav_tmp_filename, $_local_tmp_filename)) {
                     throw new Exception("Не удалось переместить файл из хранища {$_dav_tmp_filename} \n                                             в локальную файловую систему {$_local_tmp_filename}");
                 }
                 $doc_cnt--;
             }
         }
         if (empty($filelist)) {
             throw new Exception("Не удалось сформировать массив документов");
         }
         /*
          * @todo: пока используем CFile::copyToLocalPathFromDav
          *             
         //Перемещаем нужные документы из хранища во временную папку
         $cfile = new CFile();
         $res = $cfile->copyFilesToLocalPath($filelist);
         
         if (!$res) {
             throw new Exception("Не удалось переместить файлы из хранища");
         }
         */
         //Создаем архив документов
         $_zip_filename = self::TMP_PATH . "{$_archive_dir}.zip";
         $zip = new ZipArchive();
         if ($zip->open($_zip_filename, ZipArchive::CREATE)) {
             foreach ($filelist as $filename) {
                 $localname = basename($filename);
                 $zip->addFile($filename, $localname);
             }
             $zip->close();
         }
         if (!file_exists($_zip_filename)) {
             throw new Exception("Не удалось создать архив.");
         }
         //Загружаем архив документов
         $cfile = new CFile(array('tmp_name' => $_zip_filename, 'size' => filesize($_zip_filename), 'name' => basename($_zip_filename)), self::$_TABLE_FILE);
         $cfile->server_root = true;
         $cfile->original_name = $archObj->getName();
         $cfile->src_id = $archObj->id;
         $cfile->max_size = 104857600;
         //100Mb
         $cfile->MoveUploadedFile(self::DAV_PATH);
         if (!$cfile->id) {
             $_error = is_array($cfile->error) ? implode(', ', $cfile->error) : $cfile->error;
             throw new Exception("Не удалось загрузить архив в хранилище: {$_error}");
         }
         $this->updateArchive($archObj->id, array('file_id' => $cfile->id, 'try_count' => $archObj->try_count + 1, 'status' => self::STATUS_SUCCESS));
         //@todo: send mail here!
         //Удаляем
         $cfile->deleteFromTempDir($_dav_temp_path);
         delete_files($_archive_path, true, 1);
         unlink($_zip_filename);
         //------------------------------------------------------------------
         $this->addArchiveToLetters($bs_ids, $cfile);
     } catch (Exception $e) {
         $this->updateArchive($archObj->id, array('status' => self::STATUS_ERROR, 'try_count' => $archObj->try_count + 1, 'techmessage' => $e->getMessage()));
         return false;
     }
     return true;
 }
Example #9
0
 /**
  * Удалить файл, прикрепленный к комментарию
  * 
  * @param  int $cid ID комментария
  * @param  int $id_attach ID файла
  * @param  bool $mark_only опционально. установить в true если нужно только пометить файл как удаленный
  * @return bool true - успех, false - провал
  */
 public static function DeleteAttach($cid, $id_attach, $mark_only = false)
 {
     global $DB;
     //$sql = "SELECT file.*, commune_attach.cid, commune_attach.small, commune_attach.id AS att_id, commune_attach.sort AS att_sort FROM commune_attach JOIN file_commune as file ON file.id = commune_attach.fid WHERE commune_attach.cid = ?i AND commune_attach.fid = ?i";
     //$ret = $DB->row($sql, $cid, $id_attach);
     $ret = CFile::selectFilesBySrc(self::FILE_TABLE, $cid, 'sort', "id = {$id_attach}");
     $login = $_SESSION['login'];
     $dir = "users/" . substr($login, 0, 2) . "/" . $login . "/upload/";
     $file = $ret['fname'];
     $file = str_replace('sm_', '', $file);
     $cfile = new CFile($ret['id']);
     if ($file && $login) {
         if ($mark_only) {
             // только пометить на удаление
             $cfile->updateFileParams(array('deleted' => true), false);
             //$sql = "UPDATE commune_attach SET is_deleted = true WHERE id = {$ret['att_id']}";
             //$DB->squery($sql);
         } else {
             $cfile->Delete(0, $dir, $file);
             $cfile->Delete(0, $dir, 'sm_' . $file);
             //              $sql = "DELETE FROM commune_attach WHERE id = {$ret['att_id']}";
             //              $DB->squery($sql);
         }
         $sql = "UPDATE " . self::FILE_TABLE . " SET sort = sort-1 WHERE sort > {$ret['sort']} AND src_id = {$cid}";
         $DB->squery($sql);
         $sql = "SELECT max(sort) FROM " . self::FILE_TABLE . " WHERE id <> {$ret['id']} AND src_id = {$cid}";
         $max_sort = $DB->val($sql) + 1;
         $sql = "UPDATE " . self::FILE_TABLE . " SET sort = {$max_sort} WHERE id = {$ret['id']} AND src_id = {$cid}";
         $DB->squery($sql);
         return true;
     }
     return false;
 }
Example #10
0
 /**
  * Получение данных сообщений, либо одного сообщения по ID
  * 
  * @param integer $message_id 
  * @return array
  */
 public function getData($message_id = NULL)
 {
     $model = $this->model();
     $resource_id = $this->_resource_id;
     if (isset($model['resource_id'])) {
         $resource_id = $model['resource_id'];
     }
     $fields = array();
     $sql_fields = array();
     foreach ($model as $tid => $table) {
         if ($tid == 'attaches' || !is_array($table['fields'])) {
             continue;
         }
         if ($tid == 'users' && !get_uid(false)) {
             continue;
         }
         $fields[$table['table']] = array();
         foreach ($table['fields'] as $k => $v) {
             if (!$v) {
                 continue;
             }
             $fields[$tid][$k] = str_replace("ONLY ", "", $table['table']) . "." . $v;
             if (isset($model[$tid]['expr'][$k])) {
                 $sql_fields[] = $model[$tid]['expr'][$k] . " AS {$k}";
             } else {
                 $sql_fields[] = str_replace("ONLY ", "", $table['table']) . "." . $v . " AS {$k}";
             }
         }
     }
     $sql_fields_author = array('u_auth.uid AS author_uid', 'u_auth.login AS author_login', 'u_auth.uname AS author_uname', 'u_auth.usurname AS author_usurname', 'u_auth.photo AS author_photo', 'u_auth.is_banned AS author_is_banned', 'u_auth.is_pro AS author_is_pro', 'u_auth.is_profi AS author_is_profi', 'u_auth.is_verify AS author_is_verify', 'u_auth.is_team AS author_is_team', 'u_auth.is_pro_test AS author_is_pro_test', 'u_auth.role AS author_role', 'u_auth.warn AS warn', 'u_auth.reg_date AS author_reg_date');
     $sql_fields_mod = array('u_mod.uid AS mod_uid', 'u_mod.login AS mod_login', 'u_mod.uname AS mod_uname', 'u_mod.usurname AS mod_usurname', 'u_mod.role AS mod_role', 'u_mod2.uid AS mod_uid_del', 'u_mod2.login AS mod_login_del', 'u_mod2.uname AS mod_uname_del', 'u_mod2.usurname AS mod_usurname_del', 'u_mod2.role AS mod_role_del');
     $sql_fields_inner = array();
     if (!empty($model['users']['inner_fields'])) {
         foreach ($model['users']['inner_fields'] as $name_field => $as_name) {
             $sql_fields_inner[] = "{$name_field} as {$as_name}";
         }
     }
     $sql_fields = implode(", ", array_merge($sql_fields, $sql_fields_author, $sql_fields_mod, $sql_fields_inner));
     if ($model['comments']['set']) {
         $sql[] = $model['comments']['set'] . ';';
     }
     $sql[] = "SELECT {$sql_fields} FROM " . $model['comments']['table'];
     if (isset($model['users']) && get_uid(false)) {
         $sql[] = "LEFT JOIN " . $model['users']['table'] . " ON " . $fields['comments']['id'] . " = " . $fields['users']['comment'] . " AND " . $fields['users']['user'] . " = " . get_uid(false);
     }
     // Данные автора комментария
     $sql[] = "LEFT JOIN users as u_auth ON u_auth.uid = " . $fields['comments']['author'];
     // Данные модератора или админа, редактировавшего коммент
     $sql[] = "LEFT JOIN users as u_mod ON u_mod.uid = " . $fields['comments']['modified'];
     // Данные модератора или админа, удалившего коммент
     $sql[] = "LEFT JOIN users as u_mod2 ON u_mod2.uid = " . $fields['comments']['deleted'];
     if (!empty($model['users']['inner'])) {
         $sql[] = implode(" \n ", $model['users']['inner']);
     }
     $sql[] = "WHERE " . $fields['comments'][!$message_id ? 'resource' : 'id'] . " = ? ";
     if (isset($model['comments']['where'])) {
         $sql[] = "AND " . implode(" AND ", $model['comments']['where']);
     }
     $sql[] = "ORDER BY " . $fields['comments']['created_time'];
     $sql = implode(" \n ", $sql);
     $DB = new DB('master');
     $res = $DB->rows($sql, !$message_id ? $resource_id : $message_id);
     $this->msg_num = count($res);
     $comment_ids = array();
     $comment_arr = array();
     if ($this->msg_num) {
         foreach ($res as $row) {
             $comment_ids[] = $row['id'];
             $comments_arr[$row['id']] = $row;
         }
     }
     // Выбираем файлы
     if (count($comment_ids) && isset($model['attaches'])) {
         $tbl = $model['attaches']['table'];
         $fl_tbl = $model['attaches']['file_table'];
         if ($tbl == $fl_tbl) {
             if ($model['attaches']['fields']['inline']) {
                 $where = " {$tbl}." . $model['attaches']['fields']['inline'] . " = FALSE";
             }
             $res = CFile::selectFilesBySrc($tbl, $comment_ids, 'id', $where);
         } else {
             $exclude_inline = '';
             if ($model['attaches']['fields']['inline']) {
                 $exclude_inline = " AND {$tbl}." . $model['attaches']['fields']['inline'] . " = FALSE";
             }
             $sql = array();
             $sql[] = "SELECT * FROM " . $tbl;
             $sql[] = "INNER JOIN {$fl_tbl} file ON file.id = {$tbl}." . $model['attaches']['fields']['file'];
             $sql[] = "WHERE {$tbl}." . $model['attaches']['fields']['comment'] . " IN (" . implode(', ', $comment_ids) . "){$exclude_inline}";
             $sql = implode(" \n ", $sql);
             $res = $DB->rows($sql);
         }
         foreach ($res as $file) {
             $comments_arr[$file[$model['attaches']['fields']['comment']]]['attach'][] = $file;
         }
     }
     $ret = $comments_arr;
     if ($message_id && count($comments_arr)) {
         $ret = array_shift($ret);
     }
     if (!count($ret)) {
         $ret = array();
     }
     return $ret;
 }