Esempio n. 1
0
 /**
  * Saves file in storage
  *
  * @param string $sFile
  * @param string $sDestination
  *
  * @return bool|ModuleUploader_EntityItem
  */
 public function Store($sFile, $sDestination = null)
 {
     if (!$sDestination) {
         $oUser = E::ModuleUser()->GetUserCurrent();
         if (!$oUser) {
             return false;
         }
         $sDestination = E::ModuleUploader()->GetUserFileDir($oUser->getId());
     }
     if ($sDestination) {
         $sMimeType = ModuleImg::MimeType($sFile);
         $bIsImage = strpos($sMimeType, 'image/') === 0;
         $iUserId = E::UserId();
         $sExtension = F::File_GetExtension($sFile, true);
         if (substr($sDestination, -1) == '/') {
             $sDestinationDir = $sDestination;
         } else {
             $sDestinationDir = dirname($sDestination) . '/';
         }
         $sUuid = ModuleMresource::CreateUuid('file', $sFile, md5_file($sFile), $iUserId);
         $sDestination = $sDestinationDir . $sUuid . '.' . $sExtension;
         if ($sStoredFile = E::ModuleUploader()->Move($sFile, $sDestination, true)) {
             $oStoredItem = E::GetEntity('Uploader_Item', array('storage' => 'file', 'uuid' => $sUuid, 'original_filename' => basename($sFile), 'url' => $this->Dir2Url($sStoredFile), 'file' => $sStoredFile, 'user_id' => $iUserId, 'mime_type' => $sMimeType, 'is_image' => $bIsImage));
             return $oStoredItem;
         }
     }
     return false;
 }
 /**
  * @param null $xSize
  *
  * @return string|null
  */
 public function getImageUrl($xSize = null)
 {
     $sUrl = $this->getPathUrl();
     if ($sUrl) {
         $sUrl = E::ModuleUploader()->CompleteUrl($sUrl);
         if (!$xSize) {
             return $sUrl;
         }
         return E::ModuleUploader()->ResizeTargetImage($sUrl, $xSize);
     }
     return null;
 }
 /**
  * @param null $xSize
  *
  * @return string|null
  */
 public function getImageUrl($xSize = null)
 {
     $sUrl = $this->getPathUrl();
     if ($sUrl) {
         if (strpos($sUrl, '@') === 0) {
             $sUrl = Config::Get('path.root.url') . substr($sUrl, 1);
         }
         if (!$xSize) {
             return $sUrl;
         }
         return E::ModuleUploader()->ResizeTargetImage($sUrl, $xSize);
     }
     return null;
 }
Esempio n. 4
0
 /**
  * Прикрепляет временный ресурс к вновь созданному объекту
  *
  * @param string $sTargetType
  * @param string $sTargetId
  * @param $sTargetTmp
  *
  * @return bool|ModuleMresource_EntityMresource
  */
 public function LinkTempResource($sTargetType, $sTargetId, $sTargetTmp)
 {
     if ($sTargetTmp && E::IsUser()) {
         $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
         $aMresourceRel = $this->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
         if ($aMresourceRel) {
             $oResource = array_shift($aMresourceRel);
             $sOldPath = $oResource->GetFile();
             $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
             /** @var ModuleMresource_EntityMresource $oResource */
             $oResource = $this->GetMresourcesByUuid($oStoredFile->getUuid());
             if ($oResource) {
                 $oResource->setUrl($this->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $sTargetId)));
                 $oResource->setType($sTargetType);
                 $oResource->setUserId(E::UserId());
                 // 4. В свойство поля записать адрес картинки
                 $this->UnlinkFile($sTargetType, 0, E::UserId());
                 $this->AddTargetRel($oResource, $sTargetType, $sTargetId);
                 return $oResource;
             }
         }
     }
     return false;
 }
Esempio n. 5
0
 /**
  * @param int|string $xSize
  * @param string     $sSex
  *
  * @return string
  */
 public function GetDefaultPhotoUrl($xSize, $sSex)
 {
     $sPath = E::ModuleUploader()->GetUserAvatarDir(0) . 'user_photo_' . Config::Get('view.skin', Config::LEVEL_CUSTOM) . '_' . $sSex . '.png';
     if (strpos($xSize, 'x') !== false) {
         list($nW, $nH) = array_map('intval', explode('x', $xSize));
     } else {
         $nW = $nH = (int) $xSize;
     }
     $sPath .= '-' . $nW . 'x' . $nH . '.' . pathinfo($sPath, PATHINFO_EXTENSION);
     if (Config::Get('module.image.autoresize') && !F::File_Exists($sPath)) {
         $sPath = E::ModuleImg()->AutoresizeSkinImage($sPath, 'user_photo', max($nH, $nW));
     }
     return E::ModuleUploader()->Dir2Url($sPath);
 }
Esempio n. 6
0
 /**
  * @param string $sFileExtension
  * @param string $sPreset
  * @param array  $aOptions
  *
  * @return array
  */
 public function GetOptions($sFileExtension = '*', $sPreset = null, $aOptions = array())
 {
     if (is_array($sPreset) && empty($aOptions)) {
         $aOptions = $sPreset;
         $sPreset = null;
     }
     if (!$sPreset && $sPreset !== 'default') {
         $sPreset = 'images.' . $sPreset;
     }
     $aConfigOptions = E::ModuleUploader()->GetConfig($sFileExtension, $sPreset);
     if ($aConfigOptions && $aOptions) {
         /** @var DataArray $aParams */
         $aOptions = F::Array_Merge($aConfigOptions, $aOptions);
     } elseif (!$aOptions) {
         $aOptions = $aConfigOptions;
     }
     return $aOptions;
 }
Esempio n. 7
0
/**
 * Выводит изображение и прикрепляет его ко временному объекту
 *
 * @param $aParams
 * @param Smarty $oSmarty
 * @return string
 */
function smarty_function_img($aParams, &$oSmarty = NULL)
{
    // Пропущен тип объекта
    if (!isset($aParams['attr']['target-type'])) {
        trigger_error("img: missing 'target-type' parameter", E_USER_WARNING);
        return '';
    }
    // Пропущен идентификатор объекта
    if (!isset($aParams['attr']['target-id'])) {
        trigger_error("img: missing 'target-id' parameter", E_USER_WARNING);
        return '';
    }
    // Получим тип объекта
    $sTargetType = $aParams['attr']['target-type'];
    unset($aParams['attr']['target-type']);
    // Получим ид объекта
    $iTargetId = intval($aParams['attr']['target-id']);
    unset($aParams['attr']['target-id']);
    // Получим ид объекта
    $sCrop = isset($aParams['attr']['crop']) ? $aParams['attr']['crop'] : FALSE;
    unset($aParams['attr']['crop']);
    // Получим изображение по временному ключу, или создадим этот ключ
    if (($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && E::IsUser()) {
        // Продлим куку
        E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, $sTargetTmp, 'P1D', FALSE);
        // Получим предыдущее изображение и если оно было, установим в качестве текущего
        // Получим и удалим все ресурсы
        $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
        if ($aMresourceRel) {
            /** @var ModuleMresource_EntityMresource $oResource */
            $oMresource = array_shift($aMresourceRel);
            if ($oMresource) {
                if ($sCrop) {
                    $aParams['attr']['src'] = E::ModuleUploader()->ResizeTargetImage($oMresource->GetUrl(), $sCrop);
                } else {
                    $aParams['attr']['src'] = $oMresource->GetUrl();
                }
                $oSmarty->assign("bImageIsTemporary", TRUE);
            }
        }
    } else {
        // Куки нет, это значит, что пользователь первый раз создает этот тип
        // и старой картинки просто нет
        if ($iTargetId == '0') {
            E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, F::RandomStr(), 'P1D', FALSE);
        } else {
            E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
            $sImage = E::ModuleUploader()->GetTargetImageUrl($sTargetType, $iTargetId, $sCrop);
            if ($sImage) {
                $aParams['attr']['src'] = $sImage;
                $oSmarty->assign("bImageIsTemporary", TRUE);
            }
        }
    }
    // Формируем строку атрибутов изображения
    $sAttr = '';
    if (isset($aParams['attr']) && is_array($aParams['attr'])) {
        foreach ($aParams['attr'] as $sAttrName => $sAttrValue) {
            $sAttr .= ' ' . $sAttrName . '="' . $sAttrValue . '"';
        }
    }
    // Сформируем тег изображения
    $sImageTag = '<img ' . $sAttr . '/>';
    return $sImageTag;
}
Esempio n. 8
0
 /**
  * Удаляет фото пользователя
  *
  * @param ModuleUser_EntityUser $oUser
  *
  * @return bool
  */
 public function DeletePhoto($oUser)
 {
     $bResult = true;
     if ($sPhoto = $oUser->getProfilePhoto()) {
         $sFile = E::ModuleUploader()->Url2Dir($sPhoto);
         $bResult = E::ModuleImg()->Delete($sFile);
         if ($bResult) {
             $oUser->setProfilePhoto(null);
             E::ModuleUser()->Update($oUser);
         }
     }
     return $bResult;
 }
Esempio n. 9
0
 /**
  * Returns URL for default photo of current skin
  *
  * @param int|string $xSize
  *
  * @return string
  */
 public function GetDefaultPhotoUrl($xSize = null)
 {
     $sPath = E::ModuleUploader()->GetUserAvatarDir(0) . 'user_photo_' . Config::Get('view.skin', Config::LEVEL_CUSTOM) . '_' . ($this->getProfileSex() == 'woman' ? 'female' : 'male') . '.png';
     if ($xSize) {
         if (strpos($xSize, 'x') !== false) {
             list($nW, $nH) = array_map('intval', explode('x', $xSize));
         } else {
             $nW = $nH = intval($xSize);
         }
         $sPath .= '-' . $nW . 'x' . $nH . '.' . pathinfo($sPath, PATHINFO_EXTENSION);
     } else {
         $nW = $nH = self::DEFAULT_PHOTO_SIZE;
     }
     if (Config::Get('module.image.autoresize') && !F::File_Exists($sPath)) {
         E::ModuleImg()->AutoresizeSkinImage($sPath, 'user_photo', max($nH, $nW));
     }
     return E::ModuleUploader()->Dir2Url($sPath);
 }
Esempio n. 10
0
 /**
  * Меняет сортировку элементов фотосета
  */
 public function EventSort()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // Проверяем, целевой объект и права на его редактирование
     if (!($oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTargetType = F::GetRequest('target', FALSE), $sTargetId = F::GetRequest('target_id', FALSE)))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!($aOrder = F::GetRequest('order', FALSE))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!is_array($aOrder)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     E::ModuleMresource()->UpdateSort(array_flip($aOrder), $sTargetType, $sTargetId);
     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('uploader_sort_changed'));
 }
Esempio n. 11
0
/**
 * Выводит изображение и прикрепляет его ко временному объекту
 *
 * @param $aParams
 * @param Smarty $oSmarty
 * @return string
 */
function smarty_function_imgs($aParams, &$oSmarty = NULL)
{
    // Пропущен тип объекта
    if (!isset($aParams['target-type'])) {
        trigger_error("img: missing 'target-type' parameter", E_USER_WARNING);
        return '';
    }
    // Пропущен идентификатор объекта
    if (!isset($aParams['target-id'])) {
        trigger_error("img: missing 'target-id' parameter", E_USER_WARNING);
        return '';
    }
    // Получим тип объекта
    $sTargetType = $aParams['target-type'];
    unset($aParams['target-type']);
    // Получим ид объекта
    $iTargetId = intval($aParams['target-id']);
    unset($aParams['target-id']);
    // Получим параметры обрезки объекта
    $sCrop = isset($aParams['crop']) ? $aParams['crop'] : FALSE;
    unset($aParams['crop']);
    // Получим ид объекта
    $sTemplate = isset($aParams['template']) ? $aParams['template'] : FALSE;
    unset($aParams['template']);
    // Получим изображение по временному ключу, или создадим этот ключ
    $aParams['src'] = array();
    if (($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && E::IsUser()) {
        // Продлим куку
        E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, $sTargetTmp, 'P1D', FALSE);
    } else {
        // Куки нет, это значит, что пользователь первый раз создает этот тип
        // и старой картинки просто нет
        if ($iTargetId == '0') {
            E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, F::RandomStr(), 'P1D', FALSE);
        } else {
            E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
        }
    }
    // Получим предыдущее изображение и если оно было, установим в качестве текущего
    // Получим и удалим все ресурсы
    $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
    if ($aMresourceRel && is_array($aMresourceRel)) {
        /** @var ModuleMresource_EntityMresource $oResource */
        foreach ($aMresourceRel as $oMresource) {
            if ($sCrop) {
                $aParams['src'][$oMresource->getMresourceId()] = array('url' => E::ModuleUploader()->ResizeTargetImage($oMresource->GetUrl(), $sCrop), 'cover' => $oMresource->IsCover());
            } else {
                $aParams['src'][$oMresource->getMresourceId()] = array('url' => $oMresource->GetUrl(), 'cover' => $oMresource->IsCover());
            }
            $oSmarty->assign("bHasImage", TRUE);
        }
    }
    // Создадим массив картинок
    $sItems = '';
    if ($aParams['src']) {
        foreach ($aParams['src'] as $sID => $aData) {
            $sItems .= str_replace(array('ID', 'uploader_item_SRC', 'MARK_AS_PREVIEW'), array($sID, $aData['url'], $aData['cover'] ? E::ModuleLang()->Get('topic_photoset_is_preview') : E::ModuleLang()->Get('topic_photoset_mark_as_preview')), $sTemplate);
        }
    }
    return $sItems;
}
Esempio n. 12
0
 /**
  * Возвращает полный URL до фото профиля
  *
  * @param int|string $xSize - рвзмер (240 | '240x320')
  *
  * @return string
  */
 public function GetPhotoUrl($xSize = null)
 {
     $sPropKey = '_photo_url_' . $xSize;
     $sUrl = $this->getProp($sPropKey);
     if (is_null($sUrl)) {
         if (!$xSize) {
             if (Config::Get('module.user.profile_photo_size')) {
                 $xSize = Config::Get('module.user.profile_photo_size');
             } else {
                 $xSize = self::DEFAULT_PHOTO_SIZE;
             }
         }
         if ($sRealSize = C::Get('module.uploader.images.profile_photo.size.' . $xSize)) {
             $xSize = $sRealSize;
         }
         $sUrl = $this->_getProfileImageUrl('profile_photo', $xSize);
         if (!$sUrl) {
             // Old version compatibility
             $sUrl = $this->getProfilePhoto();
             if ($sUrl) {
                 if ($xSize) {
                     $sUrl = E::ModuleUploader()->ResizeTargetImage($sUrl, $xSize);
                 }
             } else {
                 $sUrl = $this->GetDefaultPhotoUrl($xSize);
             }
         }
         $this->setProp($sPropKey, $sUrl);
     }
     return $sUrl;
 }
Esempio n. 13
0
 /**
  * @param string $sFileExtension
  * @param array  $aOptions
  *
  * @return array
  */
 public function GetOptions($sFileExtension = '*', $aOptions = array())
 {
     $aConfigOptions = E::ModuleUploader()->GetConfig($sFileExtension);
     if ($aConfigOptions && $aOptions) {
         /** @var DataArray $aParams */
         $aOptions = F::Array_Merge($aConfigOptions, $aOptions);
     } elseif (!$aOptions) {
         $aOptions = $aConfigOptions;
     }
     return $aOptions;
 }
Esempio n. 14
0
 public function getImgSize($sSize = null)
 {
     $aSize = $this->getProp('_size-' . $sSize . '-imgsize');
     if (!$aSize) {
         $sFile = $this->getProp('_size-' . $sSize . '-file');
         if (!$sFile) {
             $sUrl = $this->getLink($sSize);
             $sFile = E::ModuleUploader()->Url2Dir($sUrl);
             $this->setProp('_size-' . $sSize . '-file', $sFile);
         }
         if ($sFile && F::File_Exists($sFile)) {
             $aSize = getimagesize($sFile);
             $this->setProp('_size-' . $sSize . '-imgsize', $aSize);
         }
     }
     return $aSize;
 }
Esempio n. 15
0
 /**
  * @param bool $xSize
  *
  * @return string
  */
 public function getWebPath($xSize = FALSE)
 {
     $sUrl = E::ModuleUploader()->CompleteUrl($this->getPathUrl());
     if (!$xSize) {
         return $sUrl;
     }
     return E::ModuleUploader()->ResizeTargetImage($sUrl, $xSize);
 }
Esempio n. 16
0
 /**
  * Удаляет фото пользователя
  *
  * @param ModuleUser_EntityUser $oUser
  */
 public function DeletePhoto($oUser)
 {
     E::ModuleImg()->Delete(E::ModuleUploader()->Url2Dir($oUser->getProfilePhoto()));
 }
Esempio n. 17
0
 public function getSingleImage($nId, $sSize)
 {
     if ($this->getField($nId)) {
         return E::ModuleUploader()->GetTargetImageUrl($this->getField($nId)->getFieldType() . '-' . $nId, $this->getField($nId)->getTargetId(), $sSize);
     }
     return null;
 }
Esempio n. 18
0
 /**
  * @param string $sType
  *
  * @return ModuleMresource_EntityMresourceRel[]
  */
 public function getMediaResources($sType = null)
 {
     $iEntityId = intval($this->getId());
     $aResult = array();
     if ($iEntityId) {
         $aMedia = $this->getProp(static::MEDIARESOURCES_KEY);
         if (is_null($aMedia) && ($sType || $this->getMediaTypes())) {
             // Если медиаресурсы не загружены, то загружаем, включая требуемый тип
             $aTargetTypes = $this->getMediaTypes();
             if ($sType && !in_array($sType, $aTargetTypes)) {
                 $aTargetTypes[] = $sType;
             }
             $aImages = E::ModuleUploader()->GetTargetImages($aTargetTypes, $iEntityId);
             $aMedia = array_fill_keys($aTargetTypes, array());
             /** @var ModuleMresource_EntityMresourceRel $oImage */
             foreach ($aImages as $oImage) {
                 $aMedia[$oImage->getTargetType()][$oImage->getId()] = $oImage;
             }
             $this->setProp(static::MEDIARESOURCES_KEY, $aMedia);
             if ($sType) {
                 $aResult = $aMedia[$sType];
             } else {
                 $aResult = $aMedia;
             }
         } elseif ($sType && !array_key_exists($sType, $aMedia)) {
             $aImages = E::ModuleUploader()->GetTargetImages($sType, $iEntityId);
             if (!empty($aImages)) {
                 $aMedia[$sType] = $aImages;
             } else {
                 $aMedia[$sType] = array();
             }
             $this->setProp(static::MEDIARESOURCES_KEY, $aMedia);
             $aResult = $aMedia[$sType];
         } else {
             if ($sType) {
                 $aResult = $aMedia[$sType];
             } else {
                 $aResult = $aMedia;
             }
         }
     }
     return $aResult;
 }
Esempio n. 19
0
 /**
  * Парсинг текста на предмет видео
  * Находит теги <pre><video></video></pre> и реобразовываетих в видео
  *
  * @param string $sText    Исходный текст
  *
  * @return string
  */
 public function VideoParser($sText)
 {
     $aConfig = E::ModuleUploader()->GetConfig('*', 'images.video');
     if (!empty($aConfig['transform']['max_width'])) {
         $iWidth = intval($aConfig['transform']['max_width']);
     } else {
         $iWidth = 640;
     }
     $nRatio = E::ModuleUploader()->GetConfigAspectRatio('*', 'video');
     if ($nRatio) {
         $iHeight = $iWidth / $nRatio;
     } else {
         $iHeight = intval($aConfig['transform']['max_width']);
     }
     if (!empty($aConfig['transform']['max_height'])) {
         if ($iHeight > intval($aConfig['transform']['max_width'])) {
             $iHeight = intval($aConfig['transform']['max_width']);
         }
     }
     if (!$iHeight) {
         $iHeight = 380;
     }
     $sIframeAttr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen="allowfullscreen"';
     /**
      * youtube.com
      */
     $sText = preg_replace('/<video>http(?:s|):\\/\\/(?:www\\.|m.|)youtube\\.com\\/watch\\?v=([a-zA-Z0-9_\\-]+)(&.+)?<\\/video>/Ui', '<iframe src="//www.youtube.com/embed/$1" width="' . $iWidth . '" height="' . $iHeight . '" ' . $sIframeAttr . '></iframe>', $sText);
     /**
      * youtu.be
      */
     $sText = preg_replace('/<video>http(?:s|):\\/\\/(?:www\\.|m.|)youtu\\.be\\/([a-zA-Z0-9_\\-]+)(&.+)?<\\/video>/Ui', '<iframe src="//www.youtube.com/embed/$1" width="' . $iWidth . '" height="' . $iHeight . '" ' . $sIframeAttr . '></iframe>', $sText);
     /**
      * vimeo.com
      */
     $sText = preg_replace('/<video>http(?:s|):\\/\\/(?:www\\.|)vimeo\\.com\\/(\\d+).*<\\/video>/i', '<iframe src="//player.vimeo.com/video/$1" width="' . $iWidth . '" height="' . $iHeight . '" ' . $sIframeAttr . '></iframe>', $sText);
     /**
      * rutube.ru
      */
     $sText = preg_replace('/<video>http(?:s|):\\/\\/(?:www\\.|)rutube\\.ru\\/tracks\\/(\\d+)\\.html.*<\\/video>/Ui', '<iframe src="//rutube.ru/play/embed/$1" width="' . $iWidth . '" height="' . $iHeight . '" ' . $sIframeAttr . '></iframe>', $sText);
     $sText = preg_replace('/<video>http(?:s|):\\/\\/(?:www\\.|)rutube\\.ru\\/video\\/(\\w+)\\/?<\\/video>/Ui', '<iframe src="//rutube.ru/play/embed/$1" width="' . $iWidth . '" height="' . $iHeight . '" ' . $sIframeAttr . '></iframe>', $sText);
     /**
      * video.yandex.ru - closed
      */
     return $sText;
 }
Esempio n. 20
0
 /**
  * Удаляет аватар блога с сервера
  *
  * @param ModuleBlog_EntityBlog $oBlog    Блог
  */
 public function DeleteAvatar($oBlog)
 {
     if ($oBlog) {
         // * Если аватар есть, удаляем его и его рейсайзы (старая схема)
         if ($sUrl = $oBlog->getAvatar()) {
             E::ModuleImg()->Delete(E::ModuleUploader()->Url2Dir($sUrl));
         }
         // Deletes blog avatar from media resources
         E::ModuleMresource()->DeleteMresourcesRelByTarget('blog_avatar', $oBlog->getid());
     }
 }
Esempio n. 21
0
 /**
  * @param string $sFile
  *
  * @return string|bool
  */
 public function SaveUpload($sFile)
 {
     if ($oImage = $this->GetImage()) {
         if ($sTmpFile = F::File_GetUploadDir() . F::RandomStr() . '.' . pathinfo($sFile, PATHINFO_EXTENSION)) {
             if (F::File_CheckDir(dirname($sTmpFile))) {
                 $oImage->save($sTmpFile);
                 if (E::ModuleUploader()->Move($sTmpFile, $sFile)) {
                     return $sFile;
                 }
             }
         }
     }
     return false;
 }
Esempio n. 22
0
 /**
  * Stores uploaded image with optional cropping
  *
  * @param  string $sFile - The server path to the temporary image file
  * @param  string $sTarget - Target type
  * @param  string $sTargetId - Target ID
  * @param  array|int|bool $xSize - The size of the area to cut the picture:
  *                               array('x1'=>0,'y1'=>0,'x2'=>100,'y2'=>100)
  *                               100 - crop 100x100 by center
  *                               true - crop square by min side
  *
  * @param bool $bMulti - Target has many images
  * @return bool|ModuleMresource_EntityMresource
  */
 public function StoreImage($sFile, $sTarget, $sTargetId, $xSize = null, $bMulti = FALSE)
 {
     $oImg = E::ModuleImg()->Read($sFile);
     if (!$oImg) {
         // Возникла ошибка, надо обработать
         /** TODO Обработка ошибки */
         $this->nLastError = self::ERR_TRANSFORM_IMAGE;
         return false;
     }
     $sExtension = strtolower(pathinfo($sFile, PATHINFO_EXTENSION));
     $aConfig = $this->GetConfig($sFile, 'images.' . $sTarget);
     // Check whether to save the original
     if (isset($aConfig['original']['save']) && $aConfig['original']['save']) {
         $sSuffix = isset($aConfig['original']['suffix']) ? $aConfig['original']['suffix'] : '-original';
         $sOriginalFile = F::File_Copy($sFile, $sFile . $sSuffix . '.' . $sExtension);
     } else {
         $sOriginalFile = null;
     }
     if (!is_null($xSize)) {
         if ($xSize === true) {
             // crop square by min side
             $oImg = E::ModuleImg()->CropSquare($oImg, TRUE);
         } elseif (is_numeric($xSize)) {
             // crop square in center
             $oImg = E::ModuleImg()->CropCenter($oImg, intval($xSize), intval($xSize));
         } elseif (is_array($xSize) && !empty($xSize)) {
             if (!isset($xSize['w']) && isset($xSize['x1']) && isset($xSize['x2'])) {
                 $xSize['w'] = $xSize['x2'] - $xSize['x1'];
             }
             if (!isset($xSize['h']) && isset($xSize['y1']) && isset($xSize['y2'])) {
                 $xSize['h'] = $xSize['y2'] - $xSize['y1'];
             }
             if (isset($xSize['w']) && !isset($xSize['h'])) {
                 $xSize['h'] = $oImg->getHeight();
             }
             if (!isset($xSize['w']) && isset($xSize['h'])) {
                 $xSize['w'] = $oImg->getWidth();
             }
             if (isset($xSize['w']) && isset($xSize['h']) && !(isset($xSize['x1']) && isset($xSize['y1']))) {
                 $oImg = E::ModuleImg()->CropCenter($oImg, $xSize['w'], $xSize['h']);
             } else {
                 $oImg = E::ModuleImg()->Crop($oImg, $xSize['w'], $xSize['h'], $xSize['x1'], $xSize['y1']);
             }
         }
     }
     if ($aConfig['transform']) {
         E::ModuleImg()->Transform($oImg, $aConfig['transform']);
     }
     // Сохраняем изображение во временный файл
     if ($sTmpFile = $oImg->Save(F::File_UploadUniqname($sExtension))) {
         // Файл, куда будет записано изображение
         $sImageFile = $this->Uniqname(E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false), $sExtension);
         // Окончательная запись файла
         if ($oStoredFile = $this->Store($sTmpFile, $sImageFile)) {
             $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
             $aTmpTarget = array('topic_comment', 'talk_comment', 'talk');
             if (!(in_array($sTarget, $aTmpTarget) && !$sTargetId)) {
                 if (!$this->AddRelationResourceTarget($oResource, $sTarget, $sTargetId, $bMulti)) {
                     // TODO Возможная ошибка
                 }
             }
             return $oStoredFile;
         }
     }
     return false;
 }
Esempio n. 23
0
 /**
  * Returns default avatar of the blog
  *
  * @param int|string $xSize
  *
  * @return string
  */
 public function getDefaultAvatarUrl($xSize = null)
 {
     if (!$xSize) {
         if (Config::Get('module.user.profile_avatar_size')) {
             $xSize = Config::Get('module.user.profile_avatar_size');
         } else {
             $xSize = self::DEFAULT_AVATAR_SIZE;
         }
     }
     $sPath = E::ModuleUploader()->GetUserAvatarDir(0) . 'avatar_blog_' . Config::Get('view.skin', Config::LEVEL_CUSTOM) . '.png';
     $sResizePath = null;
     if ($xSize) {
         if ($sRealSize = C::Get('module.uploader.images.profile_avatar.size.' . $xSize)) {
             $xSize = $sRealSize;
         }
         if (is_string($xSize) && $xSize[0] == 'x') {
             $xSize = substr($xSize, 1);
         }
         if ($iSize = intval($xSize)) {
             $sResizePath = $sPath . '-' . $iSize . 'x' . $iSize . '.' . strtolower(pathinfo($sPath, PATHINFO_EXTENSION));
             if (Config::Get('module.image.autoresize') && !F::File_Exists($sResizePath)) {
                 $sResizePath = E::ModuleImg()->AutoresizeSkinImage($sResizePath, 'avatar_blog', $iSize ? $iSize : null);
             }
         }
     }
     if ($sResizePath) {
         $sPath = $sResizePath;
     } elseif (!F::File_Exists($sPath)) {
         $sPath = E::ModuleImg()->AutoresizeSkinImage($sPath, 'avatar_blog', null);
     }
     return E::ModuleUploader()->Dir2Url($sPath);
 }
Esempio n. 24
0
 /**
  * Загрузка изображения
  *
  */
 protected function EventUploadImage()
 {
     /*
      * Т.к. используется обработка отправки формы, то устанавливаем тип ответа 'jsonIframe'
      * (тот же JSON только обернутый в textarea)
      * Это позволяет избежать ошибок в некоторых браузерах, например, Opera
      */
     E::ModuleViewer()->SetResponseAjax(F::AjaxRequest(true) ? 'json' : 'jsonIframe', false);
     // * Пользователь авторизован?
     if (!$this->oUserCurrent) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     $sFile = null;
     // * Был выбран файл с компьютера и он успешно загрузился?
     if ($aUploadedFile = $this->GetUploadedFile('img_file')) {
         $aOptions = array();
         // Check options of uploaded image
         if ($nWidth = $this->GetPost('img_width')) {
             if ($this->GetPost('img_width_unit') == 'percent') {
                 // Max width according width of text area
                 if ($this->GetPost('img_width_ref') == 'text' && ($nWidthText = intval($this->GetPost('img_width_text')))) {
                     $nWidth = round($nWidthText * $nWidth / 100);
                     $aOptions['size']['width'] = $nWidth;
                 }
             }
         }
         $sFile = E::ModuleTopic()->UploadTopicImageFile($aUploadedFile, $this->oUserCurrent, $aOptions);
         if (!$sFile) {
             $sMessage = E::ModuleLang()->Get('uploadimg_file_error');
             if (E::ModuleUploader()->GetError()) {
                 $sMessage .= ' (' . E::ModuleUploader()->GetErrorMsg() . ')';
             }
             E::ModuleMessage()->AddErrorSingle($sMessage, E::ModuleLang()->Get('error'));
             return;
         }
     } elseif (($sUrl = $this->GetPost('img_url')) && $sUrl != 'http://') {
         // * Загрузка файла по URL
         if (preg_match('~(https?:\\/\\/)(\\w([\\w]+)?\\.[\\w\\.\\-\\/]+.*)$~i', $sUrl, $aM)) {
             // Иногда перед нормальным адресом встречается лишний 'http://' и прочий "мусор"
             $sUrl = $aM[1] . $aM[2];
             $sFile = E::ModuleTopic()->UploadTopicImageUrl($sUrl, $this->oUserCurrent);
         }
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('uploadimg_file_error'));
         return;
     }
     // * Если файл успешно загружен, формируем HTML вставки и возвращаем в ajax ответе
     if ($sFile) {
         $sText = E::ModuleImg()->BuildHTML($sFile, $_REQUEST);
         E::ModuleViewer()->AssignAjax('sText', $sText);
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleUploader()->GetErrorMsg(), E::ModuleLang()->Get('error'));
     }
 }
Esempio n. 25
0
 /**
  * Обработка дополнительных полей топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sType
  *
  * @return bool
  */
 public function processTopicFields($oTopic, $sType = 'add')
 {
     /** @var ModuleTopic_EntityContentValues $aValues */
     $aValues = array();
     if ($sType == 'update') {
         // * Получаем существующие значения
         if ($aData = $this->GetTopicValuesByArrayId(array($oTopic->getId()))) {
             $aValues = $aData[$oTopic->getId()];
         }
         // * Чистим существующие значения
         E::ModuleTopic()->DeleteTopicValuesByTopicId($oTopic->getId());
     }
     if ($oType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType())) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             foreach ($aFields as $oField) {
                 $sData = null;
                 if (isset($_REQUEST['fields'][$oField->getFieldId()]) || isset($_FILES['fields_' . $oField->getFieldId()]) || $oField->getFieldType() == 'single-image-uploader') {
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sData = E::ModuleText()->Parser($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sData = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sData = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     //поле с файлом
                     if ($oField->getFieldType() == 'file') {
                         //если указано удаление файла
                         if (F::GetRequest('topic_delete_file_' . $oField->getFieldId())) {
                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                 @unlink(Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl());
                                 //$oTopic->setValueField($oField->getFieldId(),'');
                                 $sData = null;
                             }
                         } else {
                             //если удаление файла не указано, уже ранее залит файл^ и нового файла не загружалось
                             if ($sType == 'update' && isset($aValues[$oField->getFieldId()])) {
                                 $sData = $aValues[$oField->getFieldId()]->getValueSource();
                             }
                         }
                         if (isset($_FILES['fields_' . $oField->getFieldId()]) && is_uploaded_file($_FILES['fields_' . $oField->getFieldId()]['tmp_name'])) {
                             $iMaxFileSize = F::MemSize2Int(Config::Get('module.uploader.files.default.file_maxsize'));
                             $aFileExtensions = Config::Get('module.uploader.files.default.file_extensions');
                             if (!$iMaxFileSize || filesize($_FILES['fields_' . $oField->getFieldId()]['tmp_name']) <= $iMaxFileSize) {
                                 $aPathInfo = pathinfo($_FILES['fields_' . $oField->getFieldId()]['name']);
                                 if (!$aFileExtensions || in_array(strtolower($aPathInfo['extension']), $aFileExtensions)) {
                                     $sFileTmp = $_FILES['fields_' . $oField->getFieldId()]['tmp_name'];
                                     $sDirSave = Config::Get('path.uploads.root') . '/files/' . E::ModuleUser()->GetUserCurrent()->getId() . '/' . F::RandomStr(16);
                                     mkdir(Config::Get('path.root.dir') . $sDirSave, 0777, true);
                                     if (is_dir(Config::Get('path.root.dir') . $sDirSave)) {
                                         $sFile = $sDirSave . '/' . F::RandomStr(10) . '.' . strtolower($aPathInfo['extension']);
                                         $sFileFullPath = Config::Get('path.root.dir') . $sFile;
                                         if (copy($sFileTmp, $sFileFullPath)) {
                                             //удаляем старый файл
                                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                                 $sOldFile = Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl();
                                                 F::File_Delete($sOldFile);
                                             }
                                             $aFileObj = array();
                                             $aFileObj['file_hash'] = F::RandomStr(32);
                                             $aFileObj['file_name'] = E::ModuleText()->Parser($_FILES['fields_' . $oField->getFieldId()]['name']);
                                             $aFileObj['file_url'] = $sFile;
                                             $aFileObj['file_size'] = $_FILES['fields_' . $oField->getFieldId()]['size'];
                                             $aFileObj['file_extension'] = $aPathInfo['extension'];
                                             $aFileObj['file_downloads'] = 0;
                                             $sData = serialize($aFileObj);
                                             F::File_Delete($sFileTmp);
                                         }
                                     }
                                 } else {
                                     $sTypes = implode(', ', $aFileExtensions);
                                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_type', array('types' => $sTypes)), null, true);
                                 }
                             } else {
                                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_size', array('size' => $iMaxFileSize)), null, true);
                             }
                             F::File_Delete($_FILES['fields_' . $oField->getFieldId()]['tmp_name']);
                         }
                     }
                     // Поле с изображением
                     if ($oField->getFieldType() == 'single-image-uploader') {
                         $sTargetType = $oField->getFieldType() . '-' . $oField->getFieldId();
                         $iTargetId = $oTopic->getId();
                         // 1. Удалить значение target_tmp
                         // Нужно затереть временный ключ в ресурсах, что бы в дальнейшем картнка не
                         // воспринималась как временная.
                         if ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) {
                             // 2. Удалить куку.
                             // Если прозошло сохранение вновь созданного топика, то нужно
                             // удалить куку временной картинки. Если же сохранялся уже существующий топик,
                             // то удаление куки ни на что влиять не будет.
                             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
                             // 3. Переместить фото
                             $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sOldPath = $oResource->GetFile();
                                 $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
                                 /** @var ModuleMresource_EntityMresource $oResource */
                                 $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
                                 if ($oResource) {
                                     $oResource->setUrl(E::ModuleMresource()->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $iTargetId)));
                                     $oResource->setType($sTargetType);
                                     $oResource->setUserId(E::UserId());
                                     // 4. В свойство поля записать адрес картинки
                                     $sData = $oResource->getMresourceId();
                                     $oResource = array($oResource);
                                     E::ModuleMresource()->UnlinkFile($sTargetType, 0, $oTopic->getUserId());
                                     E::ModuleMresource()->AddTargetRel($oResource, $sTargetType, $iTargetId);
                                 }
                             }
                         } else {
                             // Топик редактируется, просто обновим поле
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sData = $oResource->getMresourceId();
                             } else {
                                 $sData = false;
                                 //                                    $this->DeleteField($oField);
                             }
                         }
                     }
                     E::ModuleHook()->Run('content_field_proccess', array('sData' => &$sData, 'oField' => $oField, 'oTopic' => $oTopic, 'aValues' => $aValues, 'sType' => &$sType));
                     //Добавляем поле к топику.
                     if ($sData) {
                         /** @var ModuleTopic_EntityContentValues $oValue */
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setTargetId($oTopic->getId());
                         $oValue->setTargetType('topic');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sData);
                         $oValue->setValueSource(in_array($oField->getFieldType(), array('file', 'single-image-uploader')) ? $sData : $_REQUEST['fields'][$oField->getFieldId()]);
                         $this->AddTopicValue($oValue);
                     }
                 }
             }
         }
     }
     return true;
 }
Esempio n. 26
0
 public function getWebPath($xSize = FALSE)
 {
     $sUrl = str_replace('@', Config::Get('path.root.web'), $this->getPathUrl());
     if (!$xSize) {
         return $sUrl;
     }
     return E::ModuleUploader()->ResizeTargetImage($sUrl, $xSize);
 }