public function changeLogo(CUploadedFile $uploadedFile) { $basePath = Yii::app()->getModule('cabinet')->getUploadPath(); //создаем каталог для аватарок, если не существует if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) { throw new CException(Yii::t('default', 'It is not possible to create directory for logos!')); } $filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName; // обновить файл //$this->removeOldLogo(); if (!$uploadedFile->saveAs($basePath . $filename)) { throw new CException(Yii::t('default', 'It is not possible to save logos!')); } // получить запись лого $photo = $this->with('photo')->find('photo.id=:id', [':id' => $this->logo_id]); $webroot = Yii::getpathOfAlias('webroot'); $trimPath = str_replace($webroot, '', $basePath); $logoFileOld = null; $File = new File(); $File->model = 'Company'; $File->type = 'image'; $File->size = filesize($basePath . $filename); $File->name = $filename; $File->path = $trimPath . $filename; $File->record_id = 0; if (!is_null($photo['photo'])) { $File->id = $photo['photo']['id']; $File->isNewRecord = false; $logoFileOld = $photo['photo']['path']; } if ($File->save()) { if (0 != strcmp($logoFileOld, $File->path)) { @unlink($webroot . $logoFileOld); } } else { yii::log("changeLogo save FAILED id=[" . $File->id . "]", "info"); } if ($this->logo_id != $File->id) { // поменять logo_id $this->logo_id = $File->id; if ($this->validate(['logo_id'])) { if (true === $this->update(['logo_id'])) { } else { Yii::log("changeLogo update logo_id FAILED", 'info'); } } else { Yii::log("changeLogo validate logo_id FAILED", 'info'); } } //$this->logo = $filename; return true; }
/** * You can check image exists by url (full or relative url) * @param $url * @return bool */ public static function checkImageByUrl($url) { $exists = false; $preg = preg_match('/^http(s)?:\\/\\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\\/.*)?$/i', $url); if ($preg) { $file_headers = @get_headers($url); if ($file_headers[0] == 'HTTP/1.1 404 Not Found') { $exists = false; } else { $exists = true; } } else { if (strpos($url, '/') !== false) { $path = $_SERVER['DOCUMENT_ROOT'] ? $_SERVER['DOCUMENT_ROOT'] : Yii::getpathOfAlias('webroot'); $exists = @file_exists($path . $url); } } return $exists; }
/** * Изменение размера изображения, сохранение его в папку /{width}x{height}/ * @param string $path Путь к оригинальному изображению * @param number $width Новая ширина * @param number $height Новая высота * @param boolean $keep_ratio true - сохранить пропорции, false - не сохранять * @return string Новый путь к уже модифицированному файлу */ public static function getImageResize($path, $width, $height, $keep_ratio = true) { $ret = $path; if ($path) { // проверить что кешированное уже есть $webroot = Yii::getpathOfAlias('webroot'); $pos = strrpos($path, '/'); $path_cache = substr($path, 0, $pos + 1) . "{$width}x{$height}" . substr($path, $pos, strlen($path)); if (file_exists($webroot . $path_cache)) { $ret = $path_cache; } else { // кеша файла нет, надо создавать $real_path = $webroot . $path; if (file_exists($real_path)) { $image_info = getimagesize($real_path); //Yii::log("getImageResize real_path=[$real_path],image_info=[".print_r( $image_info , true )."]" , 'info'); if (false !== $image_info) { $w = $image_info[0]; $h = $image_info[1]; $type = $image_info[2]; $dst = null; do { switch ($type) { case 1: $img = imagecreatefromgif($real_path); break; case 2: $img = imagecreatefromjpeg($real_path); break; case 3: $img = imagecreatefrompng($real_path); break; default: break 2; // выход через do while } $sizes = static::getDataForResize($width, $height, $w, $h, $keep_ratio); if (is_null($sizes)) { break; } // выход через do while $new = imagecreatetruecolor($sizes['width'], $sizes['height']); // preserve transparency if ($type == 1 or $type == 3) { imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)); imagealphablending($new, false); imagesavealpha($new, true); } imagecopyresampled($new, $img, 0, 0, 0, 0, $sizes['width'], $sizes['height'], $w, $h); $dst = $webroot . $path_cache; // проверить что папки до файла с картинкой существуют $dir_path = pathinfo($dst, PATHINFO_DIRNAME); if (!file_exists($dir_path)) { mkdir($dir_path, 0755, true); } switch ($type) { case 1: imagegif($new, $dst); break; case 2: imagejpeg($new, $dst); break; case 3: imagepng($new, $dst); break; } } while (false); // при ошибках быстро выйти //Yii::log("getImageResize dst=[$dst]" , 'info'); if (!is_null($dst)) { $ret = $path_cache; } } } else { Yii::log("getImageResize getimagesize return false", 'info'); } } } return $ret; }
/** * @param $watermark * @param null $offset_x * @param null $offset_y * @param int $opacity * * @return $this */ public function watermark($watermark, $offset_x = null, $offset_y = null, $opacity = 100) { if ($watermark instanceof EasyImage) { $watermark = $watermark->image(); } elseif (is_string($watermark)) { $watermark = Image::factory(Yii::getpathOfAlias('webroot') . $watermark); } return $this->image()->watermark($watermark, $offset_x, $offset_y, $opacity); }
public function actionDeleteavatar() { $id=Yii::app()->user->id; $model=StudentReg::model()->findByPk(Yii::app()->user->id); if($model->avatar!=='noname.png'){ unlink(Yii::getpathOfAlias('webroot').'/images/avatars/'.$model->avatar); $model->updateByPk($id, array('avatar' => 'noname.png')); $this->redirect(Yii::app()->createUrl('studentreg/edit')); } else { $this->redirect(Yii::app()->createUrl('studentreg/edit')); } }
public function actionUploadImage(){ $path = StaticFilesHelper::createLectureImagePath(); // files storage folder $dir = Yii::getpathOfAlias('webroot').$path; $_FILES['file']['type'] = strtolower($_FILES['file']['type']); if ($_FILES['file']['type'] == 'image/png' || $_FILES['file']['type'] == 'image/jpg' || $_FILES['file']['type'] == 'image/gif' || $_FILES['file']['type'] == 'image/jpeg' || $_FILES['file']['type'] == 'image/pjpeg') { // setting file's mysterious name $filename = md5(date('YmdHis')).'.jpg'; $file = $dir.$filename; // copying copy($_FILES['file']['tmp_name'], $file); // displaying file $array = array( 'filelink' => '/images/lecture/'.$filename ); echo stripslashes(json_encode($array)); } }
public function actionSavecompany_ch() { $Company = Yii::app()->getUser()->getProfile()->company; $Company->CRN = $_SESSION['validate_ch']['crn']; $Company->name = $_SESSION['validate_ch']['name']; //$Company->adr = $_SESSION['validate_usa']['adr']; $Company->open = $_SESSION['validate_ch']['dateopen']; $Company->validate = true; $Company->save(); // Сохранения файла компании $upload_dir = Yii::getpathOfAlias('webroot') . '/uploads/Company/'; $filename = $Company->id . '.html'; $dir = '/' . substr(md5($filename . $Company->id), 0, 2) . '/'; $data = $this->renderPartial('html_ch', ['data' => $_SESSION['validate_ch']], true); $destination = $upload_dir . $dir . $filename; mkdir($upload_dir . $dir); $file = fopen($destination, "w+"); fputs($file, $data); fclose($file); $File = new File(); $File->model = 'Company'; $File->size = filesize($destination); $File->type = 'html'; $File->name = $filename; $File->path = '/uploads/Company' . $dir . $filename; $File->record_id = $Company->id; $File->save(); $this->redirect('/site/validatesuccess'); }
public function actionSocialLogin() { $model = new StudentReg(); $s = file_get_contents('http://ulogin.ru/token.php?token=' .$_POST['token'] . '&host=' . $_SERVER['HTTP_HOST']); $user = json_decode($s, true); $model->email=$user['email']; if($model->socialLogin()) $this->redirect(Yii::app()->request->baseUrl.'/site'); else { if(isset($user['first_name'])) $model->firstName=$user['first_name']; if(isset($user['last_name'])) $model->secondName=$user['last_name']; if(isset($user['nickname'])) $model->nickname=$user['nickname']; if(isset($user['bdate'])) $model->birthday=$user['bdate']; if(isset($user['phone'])) $model->phone=$user['phone']; if(isset($user['photo_big'])) { $arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $filesName=uniqid().'.jpg'; file_put_contents(Yii::getpathOfAlias('webroot')."/avatars/".$filesName, file_get_contents($user['photo_big'], false, stream_context_create($arrContextOptions))); $model->avatar="/avatars/".$filesName; } if(isset($user['city'])) $model->address=$user['city']; if(isset($user['network'])){ switch ($user['network']){ case 'facebook': $model->facebook=$user['profile']; break; case 'googleplus': $model->googleplus=$user['profile']; break; case 'linkedin': $model->linkedin=$user['profile']; break; case 'vkontakte': $model->vkontakte=$user['profile']; break; case 'twitter': $model->twitter=$user['profile']; break; default: break; } } $model->status = 1; if($model->validate()) { $model->save(); $model = new StudentReg(); $model->email=$user['email']; if($model->socialLogin()) $this->redirect(Yii::app()->request->baseUrl.'/site'); } } }