示例#1
0
 /**
  * Return waImage class for this image ot null if image is broken
  *
  * @throws waException
  * @return waImage
  */
 public function waImage()
 {
     if ($this->data === null) {
         throw new waException('No file uploaded.');
     }
     return waImage::factory($this->data['tmp_name']);
 }
 public function photoUpload(waImage $photo)
 {
     $settings = $this->getSettings();
     $opacity = $settings['opacity'];
     $result = null;
     if ($opacity && !empty($settings['text'])) {
         $font_path = realpath(dirname(__FILE__) . '/config/data/arial.ttf');
         $photo->watermark(array('watermark' => $settings['text'], 'opacity' => $opacity, 'font_file' => $font_path, 'font_size' => $settings['text_size'] * max($photo->width, $photo->height) / photosPhoto::getBigPhotoSize(), 'font_color' => $settings['text_color'], 'text_orientation' => $this->_orientation($settings['text_orientation']), 'align' => $this->_align($settings['text_align'])));
         $result = true;
     }
     if ($opacity && !empty($settings['image'])) {
         $watermark_path = wa()->getDataPath('data/', true) . $settings['image'];
         $watermark = waImage::factory($watermark_path);
         $photo->watermark(array('watermark' => $watermark, 'opacity' => $opacity, 'align' => $this->_align($settings['image_align'])));
         $result = true;
     }
     return $result;
 }
 public function __construct($file)
 {
     if (!self::$checked) {
         self::check();
     }
     parent::__construct($file);
     $this->im = new Imagick();
     $this->im->readImage($file);
 }
示例#4
0
 public function save($file = null, $quality = null)
 {
     $config = wa('photos')->getConfig();
     if ($quality === null) {
         $quality = $config->getSaveQuality();
     }
     // check save_original option
     if ($config->getOption('save_original')) {
         // get original file name
         $original_file = photosPhoto::getOriginalPhotoPath($this->file);
         // save original file if it not exists
         if (!file_exists($original_file)) {
             copy($this->file, $original_file);
         }
     }
     // save image
     return $this->image->save($file, $quality);
 }
示例#5
0
 public function __construct($file)
 {
     if (!self::$checked) {
         self::check();
     }
     parent::__construct($file);
     if (!is_resource($this->image)) {
         $this->image = $this->createGDImageResourse($this->file, $this->type);
     }
 }
 /**
  * Userpic
  */
 public function photoAction()
 {
     $id = (int) waRequest::get('id');
     if (!$id) {
         $id = $this->getUser()->getId();
     }
     $contact = new waContact($id);
     $rand = $contact['photo'];
     $file = wa()->getDataPath("photo/{$id}/{$rand}.original.jpg", TRUE, 'contacts');
     $size = waRequest::get('size');
     if (!file_exists($file)) {
         $size = (int) $size;
         if (!in_array($size, array(20, 32, 50, 96))) {
             $size = 96;
         }
         waFiles::readFile($this->getConfig()->getRootPath() . '/wa-content/img/userpic' . $size . '.jpg');
     } else {
         // original file
         if ($size == 'original') {
             waFiles::readFile($file);
         } elseif ($size == 'full') {
             $file = str_replace('.original.jpg', '.jpg', $file);
             waFiles::readFile($file);
         } else {
             if (!$size) {
                 $size = '96x96';
             }
             $size_parts = explode('x', $size, 2);
             $size_parts[0] = (int) $size_parts[0];
             if (!isset($size_parts[1])) {
                 $size_parts[1] = $size_parts[0];
             } else {
                 $size_parts[1] = (int) $size_parts[1];
             }
             if (!$size_parts[0] || !$size_parts[1]) {
                 $size_parts = array(96, 96);
             }
             $size = $size_parts[0] . 'x' . $size_parts[1];
             $thumb_file = str_replace('.original.jpg', '.' . $size . '.jpg', $file);
             $file = str_replace('.original.jpg', '.jpg', $file);
             if (!file_exists($thumb_file) || filemtime($thumb_file) < filemtime($file)) {
                 waImage::factory($file)->resize($size_parts[0], $size_parts[1])->save($thumb_file);
                 clearstatcache();
             }
             waFiles::readFile($thumb_file);
         }
     }
 }
 public function execute()
 {
     $this->response = array();
     // Initialize all needed post vars as $vars in current namespace
     foreach (array('x1', 'y1', 'x2', 'y2', 'w', 'h', 'ww', 'orig') as $var) {
         if (null === (${$var} = (int) waRequest::post($var))) {
             // $$ black magic...
             $this->response['error'] = 'wrong parameters';
             return;
         }
     }
     $id = $this->getId();
     $contact = new waContact($id);
     // Path to file we need to crop
     $rand = mt_rand();
     $dir = waContact::getPhotoDir($id, true);
     $filename = wa()->getDataPath("{$dir}{$rand}.original.jpg", true, 'contacts');
     $oldDir = wa()->getDataPath("{$dir}", true, 'contacts');
     $no_old_photo = false;
     if (!$orig) {
         // Delete the old photos if they exist
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
             $no_old_photo = true;
         }
         waFiles::create($oldDir);
         // Is there an uploaded file in session?
         $photoEditors = $this->getStorage()->read('photoEditors');
         if (!isset($photoEditors[$id]) || !file_exists($photoEditors[$id])) {
             $this->response['error'] = 'Photo editor session is not found or already expired.';
             return;
         }
         $newFile = $photoEditors[$id];
         // Save the original image in jpeg for future use
         try {
             $img = waImage::factory($newFile)->save($filename);
         } catch (Exception $e) {
             $this->response['error'] = 'Unable to save new file ' . $filename . ' (' . pathinfo($filename, PATHINFO_EXTENSION) . ') as jpeg: ' . $e->getMessage();
             return;
         }
         // Remove uploaded file
         unset($photoEditors[$id]);
         $this->getStorage()->write('photoEditors', $photoEditors);
         unlink($newFile);
     } else {
         // cropping an old file. Move it temporarily to temp dir to delete all cached thumbnails
         $oldFile = wa()->getDataPath("{$dir}{$contact['photo']}.original.jpg", TRUE, 'contacts');
         $tempOldFile = wa()->getTempPath("{$id}/{$rand}.original.jpg", 'contacts');
         waFiles::move($oldFile, $tempOldFile);
         // Delete thumbnails
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
         }
         waFiles::create($oldDir);
         // return original image to its proper place
         waFiles::move($tempOldFile, $filename);
     }
     if (!file_exists($filename)) {
         $this->response['error'] = 'Image to crop not found (check directory access rights).';
         return;
     }
     // Crop and save selected area
     $croppedFilename = wa()->getDataPath("{$dir}{$rand}.jpg", TRUE, 'contacts');
     try {
         $img = waImage::factory($filename);
         $scale = $img->width / $ww;
         $img->crop(floor($w * $scale), floor($h * $scale), floor($x1 * $scale), floor($y1 * $scale))->save($croppedFilename);
     } catch (Exception $e) {
         $this->response['error'] = 'Unable to crop an image: ' . $e->getMessage();
         return;
     }
     // Update record in DB for this user
     $contact['photo'] = $rand;
     $contact->save();
     if ($no_old_photo) {
         $old_app = null;
         if (wa()->getApp() !== 'contacts') {
             $old_app = wa()->getApp();
             waSystem::setActive('contacts');
         }
         $this->logAction('photo_add', null, $contact->getId());
         if ($old_app) {
             waSystem::setActive($old_app);
         }
     }
     // Update recent history to reload thumbnail correctly (if not called from personal account)
     if (wa()->getUser()->get('is_user')) {
         $history = new contactsHistoryModel();
         $history->save('/contact/' . $id, null, null, '--');
     }
     $this->response = array('url' => $contact->getPhoto());
 }
 private function stepImportImage()
 {
     /**
      * @var shopProductImagesModel $model
      */
     static $model;
     if (!is_array($this->data['map'][self::STAGE_IMAGE]) && $this->data['map'][self::STAGE_IMAGE]) {
         $this->data['map'][self::STAGE_IMAGE] = array($this->data['map'][self::STAGE_IMAGE]);
     }
     if ($file = reset($this->data['map'][self::STAGE_IMAGE])) {
         if (!$model) {
             $model = new shopProductImagesModel();
         }
         //TODO store image id & if repeated - skip it
         $target = 'new';
         $u = @parse_url($file);
         $_is_url = false;
         if (!$u || !(isset($u['scheme']) && isset($u['host']) && isset($u['path']))) {
         } elseif (in_array($u['scheme'], array('http', 'https', 'ftp', 'ftps'))) {
             $_is_url = true;
         } else {
             $target = 'skip';
             $file = null;
             $this->error(sprintf('Unsupported file source protocol', $u['scheme']));
         }
         $search = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'ext' => pathinfo($file, PATHINFO_EXTENSION));
         try {
             $name = preg_replace('@[^a-zA-Zа-яА-Я0-9\\._\\-]+@', '', basename(urldecode($file)));
             if ($_is_url) {
                 $pattern = sprintf('@/(%d)/images/(\\d+)/\\2\\.(\\d+(x\\d+)?)\\.([^\\.]+)$@', $search['product_id']);
                 if (preg_match($pattern, $file, $matches)) {
                     $image = array('product_id' => $matches[1], 'id' => $matches[2], 'ext' => $matches[5]);
                     if (strpos($file, shopImage::getUrl($image, $matches[3])) !== false && $model->getByField($image)) {
                         #skip local file
                         $target = 'skip';
                         $file = null;
                     }
                 }
                 if ($file) {
                     waFiles::upload($file, $file = wa()->getTempPath('csv/upload/images/' . waLocale::transliterate($name, 'en_US')));
                 }
             } elseif ($file) {
                 $file = $this->data['upload_path'] . $file;
             }
             if ($file && file_exists($file)) {
                 if ($image = waImage::factory($file)) {
                     $search['original_filename'] = $name;
                     $data = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => filesize($file), 'original_filename' => $name, 'ext' => pathinfo($file, PATHINFO_EXTENSION));
                     if ($exists = $model->getByField($search)) {
                         $data = array_merge($exists, $data);
                         $thumb_dir = shopImage::getThumbsPath($data);
                         $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1);
                         $paths[] = $back_thumb_dir;
                         waFiles::delete($back_thumb_dir);
                         // old backups
                         if (file_exists($thumb_dir)) {
                             if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) {
                                 throw new waException(_w("Error while rebuild thumbnails"));
                             }
                         }
                     }
                     $image_changed = false;
                     /**
                      * TODO move it code into product core method
                      */
                     /**
                      * Extend add/update product images
                      * Make extra workup
                      * @event image_upload
                      */
                     $event = wa()->event('image_upload', $image);
                     if ($event) {
                         foreach ($event as $result) {
                             if ($result) {
                                 $image_changed = true;
                                 break;
                             }
                         }
                     }
                     if (empty($data['id'])) {
                         $image_id = $data['id'] = $model->add($data);
                     } else {
                         $image_id = $data['id'];
                         $target = 'update';
                         $model->updateById($image_id, $data);
                     }
                     if (!$image_id) {
                         throw new waException("Database error");
                     }
                     $image_path = shopImage::getPath($data);
                     if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) {
                         $model->deleteById($image_id);
                         throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($this->getConfig()->getRootPath()))));
                     }
                     if ($image_changed) {
                         $image->save($image_path);
                         /**
                          * @var shopConfig $config
                          */
                         $config = $this->getConfig();
                         if ($config->getOption('image_save_original') && ($original_file = shopImage::getOriginalPath($data))) {
                             waFiles::copy($file, $original_file);
                         }
                     } else {
                         waFiles::copy($file, $image_path);
                     }
                     $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
                 } else {
                     $this->error(sprintf('Invalid image file', $file));
                 }
             } elseif ($file) {
                 $this->error(sprintf('File %s not found', $file));
                 $target = 'skip';
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             } else {
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             }
         } catch (Exception $e) {
             $this->error($e->getMessage());
             //TODO skip on repeated error
         }
         array_shift($this->data['map'][self::STAGE_IMAGE]);
         ++$this->data['current'][self::STAGE_IMAGE];
         if ($_is_url) {
             waFiles::delete($file);
         }
     }
     return true;
 }
 /**
  * Merge given contacts into master contact, save, send merge event, then delete slaves.
  *
  * !!! Probably should move it into something like contactsHelper
  *
  * @param array $merge_ids list of contact ids
  * @param int $master_id contact id to merge others into
  * @return array
  */
 public static function merge($merge_ids, $master_id)
 {
     $merge_ids[] = $master_id;
     // List of contacts to merge
     $collection = new contactsCollection('id/' . implode(',', $merge_ids));
     $contacts_data = $collection->getContacts('*');
     // Master contact data
     if (!$master_id || !isset($contacts_data[$master_id])) {
         throw new waException('No contact to merge into.');
     }
     $master_data = $contacts_data[$master_id];
     unset($contacts_data[$master_id]);
     $master = new waContact($master_id);
     $result = array('total_requested' => count($contacts_data) + 1, 'total_merged' => 0, 'error' => '', 'users' => 0);
     if ($master_data['photo']) {
         $filename = wa()->getDataPath(waContact::getPhotoDir($master_data['id']) . "{$master_data['photo']}.original.jpg", true, 'contacts');
         if (!file_exists($filename)) {
             $master_data['photo'] = null;
         }
     }
     $data_fields = waContactFields::getAll('enabled');
     $check_duplicates = array();
     // field_id => true
     $update_photo = null;
     // if need to update photo here it is file paths
     // merge loop
     foreach ($contacts_data as $id => $info) {
         if ($info['is_user'] > 0) {
             $result['users']++;
             unset($contacts_data[$id]);
             continue;
         }
         foreach ($data_fields as $f => $field) {
             if (!empty($info[$f])) {
                 if ($field->isMulti()) {
                     $master->add($f, $info[$f]);
                     $check_duplicates[$f] = true;
                 } else {
                     // Field does not allow multiple values.
                     // Set value if no value yet.
                     if (empty($master_data[$f])) {
                         $master[$f] = $master_data[$f] = $info[$f];
                     }
                 }
             }
         }
         // photo
         if (!$master_data['photo'] && $info['photo'] && !$update_photo) {
             $filename_original = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.original.jpg", true, 'contacts');
             if (file_exists($filename_original)) {
                 $update_photo = array('original' => $filename_original);
                 $filename_crop = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.jpg", true, 'contacts');
                 if (file_exists($filename_crop)) {
                     $update_photo['crop'] = $filename_crop;
                 }
             }
         }
         // birthday parts
         if (!empty($data_fields['birthday'])) {
             foreach (array('birth_day', 'birth_month', 'birth_year') as $f) {
                 if (empty($master_data[$f]) && !empty($info[$f])) {
                     $master[$f] = $master_data[$f] = $info[$f];
                 }
             }
         }
     }
     // Remove duplicates
     foreach (array_keys($check_duplicates) as $f) {
         $values = $master[$f];
         if (!is_array($values) || count($values) <= 1) {
             continue;
         }
         $unique_values = array();
         // md5 => true
         foreach ($values as $k => $v) {
             if (is_array($v)) {
                 if (isset($v['value']) && is_string($v['value'])) {
                     $v = $v['value'];
                 } else {
                     unset($v['ext'], $v['status']);
                     ksort($v);
                     $v = serialize($v);
                 }
             }
             $hash = md5(mb_strtolower($v));
             if (!empty($unique_values[$hash])) {
                 unset($values[$k]);
                 continue;
             }
             $unique_values[$hash] = true;
         }
         $master[$f] = array_values($values);
     }
     // Save master contact
     $errors = $master->save(array(), 42);
     // 42 == do not validate anything at all
     if ($errors) {
         $errormsg = array();
         foreach ($errors as $field => $err) {
             if (!is_array($err)) {
                 $err = array($err);
             }
             foreach ($err as $str) {
                 $errormsg[] = $field . ': ' . $str;
             }
         }
         $result['error'] = implode("\n<br>", $errormsg);
         return $result;
     }
     // Merge categories
     $category_ids = array();
     $ccm = new waContactCategoriesModel();
     foreach ($ccm->getContactsCategories($merge_ids) as $cid => $cats) {
         $category_ids += array_flip($cats);
     }
     $category_ids = array_keys($category_ids);
     $ccm->add($master_id, $category_ids);
     // update photo
     if ($update_photo) {
         $rand = mt_rand();
         $path = wa()->getDataPath(waContact::getPhotoDir($master['id']), true, 'contacts', false);
         // delete old image
         if (file_exists($path)) {
             waFiles::delete($path);
         }
         waFiles::create($path);
         $filename = $path . "/" . $rand . ".original.jpg";
         waFiles::create($filename);
         waImage::factory($update_photo['original'])->save($filename, 90);
         if (!empty($update_photo['crop'])) {
             $filename = $path . "/" . $rand . ".jpg";
             waFiles::create($filename);
             waImage::factory($update_photo['crop'])->save($filename, 90);
         } else {
             waFiles::copy($filename, $path . "/" . $rand . ".jpg");
         }
         $master->save(array('photo' => $rand));
     }
     $result['total_merged'] = count($contacts_data) + 1;
     $contact_ids = array_keys($contacts_data);
     // wa_log
     $log_model = new waLogModel();
     $log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // wa_login_log
     $login_log_model = new waLoginLogModel();
     $login_log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // Merge event
     $params = array('contacts' => $contact_ids, 'id' => $master_data['id']);
     wa()->event(array('contacts', 'merge'), $params);
     // Delete all merged contacts
     $contact_model = new waContactModel();
     $contact_model->delete($contact_ids, false);
     // false == do not trigger event
     $history_model = new contactsHistoryModel();
     foreach ($contact_ids as $contact_id) {
         $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id));
     }
     return $result;
 }
示例#10
0
 /**
  * Returns image object for specified original image.
  * 
  * @param string $src_image_path Path to original image
  * @param string $size Size value string of the form '200x0', '96x96', etc.
  * @param int|bool $max_size Optional maximum size limit
  * @throws waException
  * @return waImageImagick|waImageGd
  */
 public static function generateThumb($src_image_path, $size, $max_size = false)
 {
     $image = waImage::factory($src_image_path);
     $width = $height = null;
     $size_info = self::parseSize($size);
     $type = $size_info['type'];
     $width = $size_info['width'];
     $height = $size_info['height'];
     switch ($type) {
         case 'max':
             if (is_numeric($max_size) && $width > $max_size) {
                 return null;
             }
             $image->resize($width, $height);
             break;
         case 'crop':
             if (is_numeric($max_size) && $width > $max_size) {
                 return null;
             }
             $image->resize($width, $height, waImage::INVERSE)->crop($width, $height);
             break;
         case 'width':
             if (is_numeric($max_size) && ($width > $max_size || $height > $max_size)) {
                 return null;
             }
             $image->resize($width, $height);
             break;
         case 'height':
             if (is_numeric($max_size) && ($width > $max_size || $height > $max_size)) {
                 return null;
             }
             $image->resize($width, $height);
             break;
         case 'rectangle':
             if (is_numeric($max_size) && ($width > $max_size || $height > $max_size)) {
                 return null;
             }
             if ($width > $height) {
                 $w = $image->width;
                 $h = $image->width * $height / $width;
             } else {
                 $h = $image->height;
                 $w = $image->height * $width / $height;
             }
             $image->crop($w, $h)->resize($width, $height, waImage::INVERSE);
             break;
         default:
             throw new waException("Unknown type");
             break;
     }
     return $image;
 }
 public function importPhoto($id, $album)
 {
     $this->log('Import photo: ' . $id);
     $row = $this->query("SELECT * FROM PIXLIST WHERE PL_ID = " . (int) $id);
     $data = array('name' => preg_replace('/\\.[^\\.]+$/', '', $row['PL_FILENAME']), 'description' => $row['PL_DESC'], 'upload_datetime' => $row['PL_UPLOADDATETIME'], 'width' => $row['PL_WIDTH'], 'height' => $row['PL_HEIGHT'], 'size' => $row['PL_FILESIZE'], 'ext' => waFiles::extension($row['PL_DISKFILENAME']), 'contact_id' => $this->getContactId($row['C_ID']), 'status' => $album['status'] ? 1 : 0);
     if ($data['status'] <= 0) {
         $data['hash'] = md5(uniqid(time(), true));
     } else {
         $data['hash'] = '';
     }
     // insert photo
     $data['id'] = $this->getPhotoModel()->insert($data);
     // set url
     $this->getPhotoModel()->updateById($data['id'], array('url' => 'DSC_' . $data['id']));
     // copy file
     $new_path = photosPhoto::getPhotoPath($data);
     $this->moveFile($row, $new_path);
     // fix width and height for old photos
     if (!$data['width'] && !$data['height'] && file_exists($new_path)) {
         $image = waImage::factory($new_path);
         $this->getPhotoModel()->updateById($data['id'], array('width' => $image->width, 'height' => $image->height));
     }
     if ($exif_data = photosExif::getInfo($new_path)) {
         $this->getExifModel()->save($data['id'], $exif_data);
     }
     // set rights
     $sql = "INSERT IGNORE INTO photos_photo_rights SET group_id = 0, photo_id = " . (int) $data['id'];
     $this->dest->exec($sql);
     if (!$album['status']) {
         $sql = "INSERT IGNORE INTO photos_photo_rights\n                    SET group_id = -" . (int) $data['contact_id'] . ", photo_id = " . (int) $data['id'];
         $this->dest->exec($sql);
     }
     // add photo to album
     $sql = "INSERT IGNORE INTO photos_album_photos\n                SET album_id = " . $album['id'] . ", photo_id = " . (int) $data['id'] . ", sort = " . (int) $row['PL_SORT'];
     $this->dest->exec($sql);
     // save old id => new id (for widgets)
     $this->old_photos[$id] = $data['id'];
     return $data['id'];
 }
示例#12
0
$file = explode("/", $file);
if (count($file) != 4) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$request_file = $file[3];
$contact_id = (int) $file[2];
$file = explode(".", $file[3]);
if (!$contact_id || count($file) != 3) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$size = explode("x", $file[1]);
if (count($size) != 2 || !$size[0] || !$size[1]) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$file = $file[0] . ".jpg";
$path = wa()->getDataPath(waContact::getPhotoDir($contact_id), true, 'contacts', false);
$filepath = "{$path}{$file}";
if (!file_exists($filepath)) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
if ($size[0] == $size[1]) {
    waImage::factory($filepath)->resize($size[0], $size[1])->save($path . $request_file);
} else {
    waImage::factory($filepath)->resize($size[0], $size[1], waImage::INVERSE)->crop($size[0], $size[1])->save($path . $request_file);
}
clearstatcache();
waFiles::readFile($path . $request_file);
 protected function correctOrientation($orientation, waImage $image)
 {
     $angles = array(3 => '180', 4 => '180', 5 => '90', 6 => '90', 7 => '-90', 8 => '-90');
     if (isset($angles[$orientation])) {
         $image->rotate($angles[$orientation]);
         return true;
     }
     return false;
 }
示例#14
0
 /**
  * Adds an image to contact.
  *
  * @param string $file Path to image file
  * @throws waException
  * @return string
  */
 public function setPhoto($file)
 {
     if (!file_exists($file)) {
         throw new waException('file not exists');
     }
     if (!$this->getId()) {
         throw new waException('Contact not saved!');
     }
     $rand = mt_rand();
     $path = wa()->getDataPath(self::getPhotoDir($this->getId()), true, 'contacts');
     // delete old image
     if (file_exists($path)) {
         waFiles::delete($path);
     }
     waFiles::create($path);
     $filename = $path . "/" . $rand . ".original.jpg";
     waFiles::create($filename);
     waImage::factory($file)->save($filename, 90);
     waFiles::copy($filename, $path . "/" . $rand . ".jpg");
     waContactFields::getStorage('waContactInfoStorage')->set($this, array('photo' => $rand));
     return $this->getPhoto();
 }
示例#15
0
    $root_url = "../../../../../";
}
$file = explode("/", $file);
if (count($file) != 2) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$contact_id = (int) $file[0];
$file = explode(".", $file[1]);
if (!$contact_id || count($file) != 3) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$size = explode("x", $file[1]);
if (count($size) != 2 || !$size[0] || !$size[1]) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
$file = $file[0] . ".jpg";
$path = wa()->getDataPath("photo/", true, "contacts");
if (!file_exists($path . $contact_id . "/" . $file)) {
    header("Location: {$root_url}wa-content/img/userpic96.jpg");
    exit;
}
if ($size[0] == $size[1]) {
    waImage::factory($path . $contact_id . "/" . $file)->resize($size[0], $size[1])->save($path . $request_file);
} else {
    waImage::factory($path . $contact_id . "/" . $file)->resize($size[0], $size[1], waImage::INVERSE)->crop($size[0], $size[1])->save($path . $request_file);
}
clearstatcache();
waFiles::readFile($path . $request_file);
示例#16
0
 /**
  * @return bool
  */
 protected function saveFromPost($form, $contact)
 {
     $data = $form->post();
     if (!$data || !is_array($data)) {
         return false;
     }
     // save photo before all
     $photo_file = waRequest::file('photo_file');
     if (array_key_exists('photo', $data)) {
         if ($photo_file->uploaded() && ($avatar = $photo_file->waImage())) {
             // add/update photo
             $square = min($avatar->height, $avatar->width);
             // setPhoto with crop
             $rand = mt_rand();
             $path = wa()->getDataPath(waContact::getPhotoDir($contact->getId()), true, 'contacts', false);
             // delete old image
             if (file_exists($path)) {
                 waFiles::delete($path);
             }
             waFiles::create($path);
             $filename = $path . $rand . ".original.jpg";
             waFiles::create($filename);
             waImage::factory($photo_file)->save($filename, 90);
             $filename = $path . $rand . ".jpg";
             waFiles::create($filename);
             waImage::factory($photo_file)->crop($square, $square)->save($filename, 90);
             waContactFields::getStorage('waContactInfoStorage')->set($contact, array('photo' => $rand));
         } elseif (empty($data['photo'])) {
             // remove photo
             $contact->set('photo', "");
         }
         $this->form->values['photo'] = $data['photo'] = $contact->get('photo');
     }
     // Validation
     if (!$form->isValid($contact)) {
         return false;
     }
     // Password validation
     if (!empty($data['password']) && $data['password'] !== $data['password_confirm']) {
         $form->errors('password', _ws('Passwords do not match'));
         return false;
     } elseif (empty($data['password']) || empty($data['password_confirm'])) {
         unset($data['password']);
     }
     unset($data['password_confirm']);
     // get old data for logging
     if ($this->contact) {
         $old_data = array();
         foreach ($data as $field_id => $field_value) {
             $old_data[$field_id] = $this->contact->get($field_id);
         }
     }
     foreach ($data as $field => $value) {
         $contact->set($field, $value);
     }
     $errors = $contact->save();
     // If something went wrong during save for any reason,
     // show it to user. In theory it shouldn't but better be safe.
     if ($errors) {
         foreach ($errors as $field => $errs) {
             foreach ($errs as $e) {
                 $form->errors($field, $e);
             }
         }
         return false;
     }
     // get new data for logging
     $new_data = array();
     foreach ($data as $field_id => $field_value) {
         if (!isset($errors[$field_id])) {
             $new_data[$field_id] = $this->contact->get($field_id);
         }
     }
     $this->logProfileEdit($old_data, $new_data);
     return true;
 }
示例#17
0
 public static function generateThumb($main_thumbnail_info, $original_path, $size, $sharpen = false, $max_size = false)
 {
     $main_thumbnail_path = $main_thumbnail_info['path'];
     $main_thumbnail_size = $main_thumbnail_info['size'];
     if (!file_exists($main_thumbnail_path)) {
         $size_info = photosPhoto::parseSize($main_thumbnail_size);
         $type = $size_info['type'];
         $width = $size_info['width'];
         $height = $size_info['height'];
         if ($image = self::_generateThumb($original_path, $type, $width, $height)) {
             $image->save($main_thumbnail_path);
         }
         $main_thumbnail_width = $image->width;
         $main_thumbnail_height = $image->height;
     } else {
         $image = waImage::factory($main_thumbnail_path);
         $main_thumbnail_width = $image->width;
         $main_thumbnail_height = $image->height;
     }
     $path = $main_thumbnail_path;
     $width = $height = null;
     $size_info = photosPhoto::parseSize($size);
     $type = $size_info['type'];
     $width = $size_info['width'];
     $height = $size_info['height'];
     if (!$width && !$height) {
         return null;
     }
     switch ($type) {
         case 'max':
             if (is_numeric($max_size) && $width > $max_size) {
                 return null;
             }
             if ($width > max($main_thumbnail_width, $main_thumbnail_height)) {
                 $image = waImage::factory($original_path);
                 // make thumb from original photo
             }
             break;
         case 'crop':
             if (is_numeric($max_size) && $width > $max_size) {
                 return null;
             }
         case 'rectangle':
             if (is_numeric($max_size) && ($width > $max_size || $height > $max_size)) {
                 return null;
             }
             if ($width > $main_thumbnail_width || $height > $main_thumbnail_height) {
                 $image = waImage::factory($original_path);
                 // make thumb from original photo
             }
             break;
         case 'width':
             $w = !is_null($width) ? $width : $height;
             $original_image = waImage::factory($original_path);
             $h = $original_image->height * ($w / $original_image->width);
             $w = round($w);
             $h = round($h);
             if ($w == $main_thumbnail_width && $h == $main_thumbnail_height) {
                 return $image;
             }
             if (is_numeric($max_size) && ($w > $max_size || $h > $max_size)) {
                 return null;
             }
             if ($w > $main_thumbnail_width || $h > $main_thumbnail_height) {
                 $image = $original_image;
                 // make thumb from original photo
             }
             break;
         case 'height':
             $h = !is_null($width) ? $width : $height;
             $original_image = waImage::factory($original_path);
             $w = $original_image->width * ($h / $original_image->height);
             $w = round($w);
             $h = round($h);
             if ($w == $main_thumbnail_width && $h == $main_thumbnail_height) {
                 return $image;
             }
             if (is_numeric($max_size) && ($w > $max_size || $h > $max_size)) {
                 return null;
             }
             if ($w > $main_thumbnail_width || $h > $main_thumbnail_height) {
                 $image = $original_image;
                 // make thumb from original photo
             }
             break;
         default:
             $type = 'unknown';
             break;
     }
     return self::_generateThumb($image, $type, $width, $height, $sharpen);
 }