예제 #1
0
 /**
  * Return the content of the asset
  *
  * @return mixed The asset content
  */
 protected function _get()
 {
     if (empty($this->content)) {
         switch ($this->mode) {
             case self::MODE_DATA:
                 $this->content = Media::get($this->path);
                 break;
             case self::MODE_FILE:
                 $this->content = file_get_contents($this->filename);
                 break;
             case self::MODE_STREAM:
                 $this->content = stream_get_contents($this->stream);
                 fclose($this->stream);
                 break;
         }
     }
     return $this->content;
 }
예제 #2
0
 /**
  * Get the total file usage
  * @param bool $user
  * @return int
  */
 function getFileUsage($user = false)
 {
     $total = 0;
     if (!empty($user)) {
         $search = ['user' => $user];
     } else {
         $search = [];
     }
     if ($media = Media::get($search, [], 9999, 0)) {
         foreach ($media as $post) {
             /* @var Media $post */
             if ($attachments = $post->getAttachments()) {
                 foreach ($attachments as $attachment) {
                     $total += $attachment['length'];
                 }
             }
         }
     }
     return $total;
 }
예제 #3
0
파일: link.php 프로젝트: rasomu/chuza
	function has_thumb() {
		global $globals;
		if ($this->thumb_x > 0 && $this->thumb_y > 0) {
			$chain = get_cache_dir_chain($this->id);
			$file = $globals['cache_dir']."/$chain/thumb-$this->id.jpg";
			$filepath = mnmpath."/$file";
			if (is_readable($filepath)) {
				return $globals['base_static'] . $file;
			} elseif ($globals['Amazon_S3_media_bucket'] && $globals['Amazon_S3_local_cache']) {
				create_cache_dir_chain(mnmpath.'/'.$globals['cache_dir'], $chain);
        		// Get thumbnail from S3
				if (Media::get("$this->id.jpg", 'thumbs', $filepath)) {
					return $globals['base_static'] . $file;
				} else {
					// Do extra check, if S3 is working, mark thumb as deleted
					if (($buckets = Media::buckets(false)) && in_array($globals['Amazon_S3_media_bucket'], $buckets)
							&& is_writable(mnmpath.'/'.$globals['cache_dir'])) { // Double check
						syslog(LOG_NOTICE, "Meneame, deleting unexisting thumb for $this->id");
						$this->delete_thumb();
					}
				}
			}
        }
		return false;
	}
 public function filter_post_content_mediaurl($content, $post)
 {
     return Media::get($content)->url;
 }
예제 #5
0
 /**
  * Get a list of users who have liked this media.
  * @param  integer $id          media id
  * @param  array  $requestOpts [description]
  * @return [type]              [description]
  */
 public function getLikes($id, $requestOpts = array())
 {
     return parent::get($id . '/likes', array(), $requestOpts);
 }
예제 #6
0
 /**
  * @param array $pa_options Options include:
  *		dontUseDefaultIcons = If set to true, write will fail rather than use default icons when preview can't be generated. Default is false – to use default icons.
  *
  */
 public function write($ps_filepath, $ps_mimetype, $pa_options = null)
 {
     if (!$this->handle) {
         return false;
     }
     $vb_dont_allow_default_icons = isset($pa_options['dontUseDefaultIcons']) && $pa_options['dontUseDefaultIcons'] ? true : false;
     # is mimetype valid?
     if (!($vs_ext = $this->info["EXPORT"][$ps_mimetype])) {
         $this->postError(1610, _t("Can't convert file to %1", $ps_mimetype), "WLPlugPDFWand->write()");
         return false;
     }
     # write the file
     if ($ps_mimetype == "application/pdf") {
         if (!copy($this->filepath, $ps_filepath . ".pdf")) {
             $this->postError(1610, _t("Couldn't write file to '%1'", $ps_filepath), "WLPlugPDFWand->write()");
             return false;
         }
     } else {
         $vb_use_default_icon = true;
         if (caMediaPluginGhostscriptInstalled($this->ops_ghostscript_path)) {
             $vn_scaling_correction = $this->get("scaling_correction");
             $vs_res = "72x72";
             if (ceil($this->get("resolution")) > 0) {
                 $vn_res = $this->get("resolution");
                 if ($vn_scaling_correction) {
                     $vn_res *= 2;
                 }
                 $vs_res = ceil($vn_res) . "x" . ceil($vn_res);
             }
             $vn_page = ceil($this->get("page"));
             $vn_quality = ceil($this->get("quality"));
             if ($vn_quality > 100) {
                 $vn_quality = 100;
             }
             if ($vn_quality < 1) {
                 $vn_quality = 50;
             }
             if ($vn_page < 1) {
                 $vn_page = 1;
             }
             if ($this->get("antialiasing")) {
                 $vs_antialiasing = "-dTextAlphaBits=4 -dGraphicsAlphaBits=4";
             } else {
                 $vs_antialiasing = "";
             }
             $vb_processed_preview = false;
             switch ($ps_mimetype) {
                 case 'image/jpeg':
                     exec($this->ops_ghostscript_path . " -dNOPAUSE -dBATCH -sDEVICE=" . ($vn_scaling_correction ? "tiff24nc" : "jpeg") . " {$vs_antialiasing} -dJPEGQ=" . $vn_quality . " -dFirstPage=" . $vn_page . " -dLastPage=" . $vn_page . " -sOutputFile=" . caEscapeShellArg($ps_filepath . "." . $vs_ext) . " -r" . $vs_res . " " . caEscapeShellArg($this->handle["filepath"]), $va_output, $vn_return);
                     if ($vn_return == 0) {
                         $vb_processed_preview = true;
                     }
                     break;
                 case 'image/tiff':
                 case 'image/png':
                 case 'image/gif':
                     exec($this->ops_ghostscript_path . " -dNOPAUSE -dBATCH -sDEVICE=tiff24nc {$vs_antialiasing} -dFirstPage=" . $vn_page . " -dLastPage=" . $vn_page . " -sOutputFile=" . caEscapeShellArg($ps_filepath . "." . $vs_ext) . " -r" . $vs_res . " " . caEscapeShellArg($this->handle["filepath"]), $va_output, $vn_return);
                     if ($vn_return == 0) {
                         $vb_processed_preview = true;
                     }
                     break;
                 default:
                     //die("Unsupported output type in PDF plug-in: $ps_mimetype [this shouldn't happen]");
                     break;
             }
             if ($vb_processed_preview) {
                 if ($vs_crop = $this->get("crop")) {
                     $o_media = new Media();
                     list($vn_w, $vn_h) = explode("x", $vs_crop);
                     if ($vn_w > 0 && $vn_h > 0) {
                         $o_media->read($ps_filepath . "." . $vs_ext);
                         if (!$o_media->numErrors()) {
                             $o_media->transform('SCALE', array('mode' => 'fill_box', 'antialiasing' => 0.5, 'width' => $vn_w, 'height' => $vn_h));
                             $o_media->write($ps_filepath, $ps_mimetype, array());
                             if (!$o_media->numErrors()) {
                                 $this->properties["width"] = $vn_w;
                                 $this->properties["height"] = $vn_h;
                                 $vb_use_default_icon = false;
                             }
                         }
                     }
                 } else {
                     if ($vn_scaling_correction) {
                         $o_media = new Media(true);
                         $o_media->read($ps_filepath . "." . $vs_ext);
                         if (!$o_media->numErrors()) {
                             $vn_w = $o_media->get('width') * $vn_scaling_correction;
                             $vn_h = $o_media->get('height') * $vn_scaling_correction;
                             if ($vn_w > $vn_h || $this->get("target_height") == 0) {
                                 $vn_r = $this->get("target_width") / $vn_w;
                                 $vn_w = $this->get("target_width");
                                 $vn_h *= $vn_r;
                             } else {
                                 $vn_r = $this->get("target_height") / $vn_h;
                                 $vn_h = $this->get("target_height");
                                 $vn_w *= $vn_r;
                             }
                             $vn_w = ceil($vn_w);
                             $vn_h = ceil($vn_h);
                             $this->properties["width"] = $vn_w;
                             $this->properties["height"] = $vn_h;
                             $o_media->transform('SCALE', array('mode' => 'bounding_box', 'antialiasing' => 0.5, 'width' => $vn_w, 'height' => $vn_h));
                             $o_media->transform('UNSHARPEN_MASK', array('sigma' => 0.5, 'radius' => 1, 'threshold' => 1.0, 'amount' => 0.1));
                             $o_media->set('quality', $vn_quality);
                             $o_media->write($ps_filepath, $ps_mimetype, array());
                             if (!$o_media->numErrors()) {
                                 $vb_use_default_icon = false;
                             }
                         }
                     } else {
                         $vb_use_default_icon = false;
                     }
                 }
             }
         }
         if ($vb_use_default_icon) {
             return $vb_dont_allow_default_icons ? null : __CA_MEDIA_DOCUMENT_DEFAULT_ICON__;
         }
     }
     $this->properties["mimetype"] = $ps_mimetype;
     $this->properties["filesize"] = filesize($ps_filepath . "." . $vs_ext);
     $this->properties["typename"] = $this->typenames[$ps_mimetype];
     return $ps_filepath . "." . $vs_ext;
 }
예제 #7
0
파일: media.php 프로젝트: anupom/my-blog
 /**
  * Copy the asset using the specified from and to paths
  *
  * @param string $pathfrom The virtual path source
  * @param string $pathto The virtual path destination
  * @return boolean true on success
  */
 public static function copy($pathfrom, $pathto)
 {
     if ($source = Media::get($pathfrom)) {
         return Media::put($pathto, $source);
     } else {
         return false;
     }
 }
예제 #8
0
function avatar_get_from_db($user, $size = 0)
{
    global $db, $globals;
    if (!in_array($size, $globals['avatars_allowed_sizes'])) {
        return false;
    }
    $time = $db->get_var("select user_avatar from users where user_id={$user}");
    if (!$time > 0) {
        return false;
    }
    if (!$globals['Amazon_S3_local_cache'] && $globals['Amazon_S3_media_bucket'] && is_writable('/tmp')) {
        $subdir = '/tmp';
    } else {
        if (!Upload::create_cache_dir($user)) {
            return false;
        }
        $subdir = Upload::get_cache_dir($user);
    }
    if (!is_writable($subdir)) {
        return false;
    }
    $file_base = $subdir . "/{$user}-{$time}";
    $delete = false;
    $original = false;
    $http_code = 0;
    if ($globals['Amazon_S3_media_bucket']) {
        $original == false;
        if (Media::get("{$user}-{$time}-{$size}.jpg", 'avatars', "{$file_base}-{$size}.jpg")) {
            return file_get_contents("{$file_base}-{$size}.jpg");
        }
        if (Media::get("{$user}-{$time}.jpg", 'avatars', "{$file_base}-orig.jpg")) {
            $delete_it = true;
            $original = "{$file_base}-orig.jpg";
        } else {
            $http_code = Media::$lastHTTPCode;
            if (is_readable($file_base . '-80.jpg') && filesize($file_base . '-80.jpg') > 0 || Media::get("{$user}-{$time}-80.jpg", 'avatars', "{$file_base}-80.jpg")) {
                $original = $file_base . '-80.jpg';
            }
        }
        if ($globals['Amazon_S3_delete_allowed'] && !$original && $http_code == 404 && Media::$lastHTTPCode == 404) {
            // The images were not found in S3
            if (is_writable(mnmpath . '/' . $globals['cache_dir'])) {
                // Double check
                syslog(LOG_INFO, "Meneame, removing avatars not found in S3 user {$user} time {$time}");
                avatars_remove($user);
            }
            return false;
        }
    } else {
        //Get from DB
        if (!is_readable($file_base . '-80.jpg')) {
            $img = $db->get_var("select avatar_image from avatars where avatar_id={$user}");
            if (!strlen($img) > 0) {
                if (is_writable(mnmpath . '/' . $globals['cache_dir'])) {
                    // Double check
                    avatars_remove($user);
                }
                return false;
            }
            file_put_contents($file_base . '-80.jpg', $img);
            $original = $file_base . '-80.jpg';
        }
    }
    if ($original && $size > 0 && $size != 80) {
        avatar_resize($original, "{$file_base}-{$size}.jpg", $size);
        if ($delete_it) {
            @unlink($original);
        }
    }
    return @file_get_contents("{$file_base}-{$size}.jpg");
}
예제 #9
0
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     if ($this->ID) {
         Session::set("FamilyID", $this->ID);
     }
     $nameField = TextField::create('Name', 'Family Name');
     $fields->replaceField('Name', $nameField);
     $houseNoField = TextField::create('HouseNo', 'House No (govt)');
     $fields->replaceField('HouseNo', $houseNoField);
     $parishes = Parish::get()->map('ID', 'NameWithLocation')->toArray();
     $parishField = DropdownField::create('ParishID', 'Parish')->setSource($parishes);
     $parishField->setEmptyString('select...');
     $fields->replaceField('ParishID', $parishField);
     //remove FamilyMembers tab
     $fields->removeByName('FamilyMembers');
     $memberGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $familyMemberList = FamilyMember::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     $familyMemberGridField = new GridField('Members', 'Family members', $familyMemberList, $memberGridFieldConfig);
     $fields->addFieldsToTab('Root.Members', array($familyMemberGridField));
     //house gridfield
     $houseGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $houseList = House::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($houseList->count()) {
         $houseGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $houseGridField = new GridField('House', 'House', $houseList, $houseGridFeildConfig);
     $fields->addFieldsToTab('Root.Housing', array($houseGridField));
     //land gridfield
     $landGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $landList = Land::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($landList->count()) {
         $landGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $landGridField = new GridField('Land', 'Land', $landList, $landGridFeildConfig);
     $fields->addFieldsToTab('Root.Housing', array($landGridField));
     //ShiftedFrom gridfield
     $shiftedFromGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $shiftedFromList = ShiftedFrom::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($shiftedFromList->count()) {
         $shiftedFromGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $shiftedFromGridField = new GridField('Shifted', 'Shifted', $shiftedFromList, $shiftedFromGridFeildConfig);
     $fields->addFieldsToTab('Root.Housing', array($shiftedFromGridField));
     //Agriculture gridfield
     $agricultureGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $agricultureList = Agriculture::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($agricultureList->count()) {
         $agricultureGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $agricultureGridField = new GridField('Agriculture', 'Agriculture', $agricultureList, $agricultureGridFeildConfig);
     $fields->addFieldsToTab('Root.Occupation', array($agricultureGridField));
     //Business gridfield
     $businessGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $businessList = Business::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($businessList->count()) {
         $businessGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $businessGridField = new GridField('Business', 'Business', $businessList, $businessGridFeildConfig);
     $fields->addFieldsToTab('Root.Occupation', array($businessGridField));
     //MonthlyIncome gridfield
     $monthlyIncomeGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $monthlyIncomeList = MonthlyIncome::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($monthlyIncomeList->count()) {
         $monthlyIncomeGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $monthlyIncomeGridField = new GridField('MonthlyIncome', 'MonthlyIncome', $monthlyIncomeList, $monthlyIncomeGridFeildConfig);
     $fields->addFieldsToTab('Root.Monthly', array($monthlyIncomeGridField));
     //MonthlyExpense gridfield
     $monthlyExpenseGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $monthlyExpenseList = MonthlyExpense::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($monthlyExpenseList->count()) {
         $monthlyExpenseGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $monthlyExpenseGridField = new GridField('MonthlyExpense', 'MonthlyExpense', $monthlyExpenseList, $monthlyExpenseGridFeildConfig);
     $fields->addFieldsToTab('Root.Monthly', array($monthlyExpenseGridField));
     //Vehicle gridfield
     $vehicleGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $vehicleList = Vehicle::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($vehicleList->count()) {
         $vehicleGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $vehicleGridField = new GridField('Vehicle', 'Vehicle', $vehicleList, $vehicleGridFeildConfig);
     $fields->addFieldsToTab('Root.OtherDetails', array($vehicleGridField));
     //Appliance gridfield
     $applianceGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $applianceList = Appliance::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($applianceList->count()) {
         $applianceGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $applianceGridField = new GridField('Appliance', 'Appliance', $applianceList, $applianceGridFeildConfig);
     $fields->addFieldsToTab('Root.OtherDetails', array($applianceGridField));
     //OtherFacility gridfield
     $otherFacilityGridFeildConfig = GridFieldConfig_RecordEditor::create();
     $otherFacilityList = OtherFacility::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($otherFacilityList->count()) {
         $otherFacilityGridFeildConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $otherFacilityGridField = new GridField('OtherFacility', 'Other Facility', $otherFacilityList, $otherFacilityGridFeildConfig);
     $fields->addFieldsToTab('Root.OtherDetails', array($otherFacilityGridField));
     //Media gridfield
     $mediaGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $mediaList = Media::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($mediaList->count()) {
         $mediaGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $mediaGridField = new GridField('Media', 'Media', $mediaList, $mediaGridFieldConfig);
     $fields->addFieldsToTab('Root.OtherDetails', array($mediaGridField));
     //CatholicMagazine gridfield
     $catholicMagazineGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $catholicMagazineList = CatholicMagazine::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($catholicMagazineList->count()) {
         $catholicMagazineGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $catholicMagazineGridField = new GridField('CatholicMagazine', 'Catholic Magazine', $catholicMagazineList, $catholicMagazineGridFieldConfig);
     $fields->addFieldsToTab('Root.OtherDetails', array($catholicMagazineGridField));
     //Loan gridfield
     $loanGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $loanList = Loan::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($loanList->count()) {
         $loanGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $loanGridField = new GridField('Loan', 'Loan', $loanList, $loanGridFieldConfig);
     $fields->addFieldsToTab('Root.Financial', array($loanGridField));
     //Saving gridfield
     $savingGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $savingList = Saving::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($savingList->count()) {
         $savingGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $savingGridField = new GridField('Saving', 'Saving', $savingList, $savingGridFieldConfig);
     $fields->addFieldsToTab('Root.Financial', array($savingGridField));
     //Talent gridfield
     $talentGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $talentList = Talent::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($talentList->count()) {
         $talentGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $talentGridField = new GridField('Talent', 'Talent', $talentList, $talentGridFieldConfig);
     $fields->addFieldsToTab('Root.Members', array($talentGridField));
     //Contact gridfield
     $contactGridFieldConfig = GridFieldConfig_RecordEditor::create();
     $contactList = Contact::get()->filter(array('FamilyID' => $this->ID))->sort('ID ASC');
     // remove add button if record already exists
     if ($contactList->count()) {
         $contactGridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
     }
     $contactGridField = new GridField('Contact', 'Contact', $contactList, $contactGridFieldConfig);
     $fields->addFieldsToTab('Root.Contact', array($contactGridField));
     return $fields;
 }
예제 #10
0
 /**
  * Get a full list of comments on a media.
  * @param  integer $id          media id
  * @param  array  $requestOpts request options
  * @return array  results
  */
 public function get($id, $params = array(), $requestOpts = array())
 {
     return parent::get($id, $params, $requestOpts);
 }
예제 #11
0
파일: link.php 프로젝트: manelio/woolr
 function thumb_download($basename = 'thumb', $delete = true)
 {
     global $globals;
     $file = Upload::get_cache_relative_dir($this->id) . "/{$basename}-{$this->id}.jpg";
     $filepath = mnmpath . "/{$file}";
     if ($basename == "thumb_medium") {
         $s3_base = "medium_";
         $s3_filename = "medium_{$this->id}.jpg";
     } elseif ($basename == "thumb_2x") {
         $s3_base = "2x_";
         $s3_filename = "2x_{$this->id}.jpg";
     } else {
         $s3_base = "";
         $s3_filename = "{$this->id}.jpg";
     }
     if ($this->thumb_x > 0 && $this->thumb_y > 0 && $globals['Amazon_S3_media_bucket'] && $globals['Amazon_S3_local_cache']) {
         Upload::create_cache_dir($this->id);
         // Get thumbnail from S3
         if (Media::get($s3_filename, 'thumbs', $filepath)) {
             return $filepath;
         } elseif ($delete) {
             // Do extra check, if S3 is working, mark thumb as deleted
             if (($buckets = Media::buckets(false)) && in_array($globals['Amazon_S3_media_bucket'], $buckets) && is_writable(mnmpath . '/' . $globals['cache_dir'])) {
                 // Double check
                 syslog(LOG_NOTICE, "Meneame, deleting unexisting thumb for {$base}_{$this->id}");
                 $this->delete_thumb($s3_base);
             }
         }
     }
     return false;
 }
예제 #12
0
function avatar_get_from_db($user, $size = 0)
{
    global $db, $globals;
    if (!in_array($size, $globals['avatars_allowed_sizes'])) {
        return false;
    }
    $time = $db->get_var("select user_avatar from users where user_id={$user}");
    if (!$globals['Amazon_S3_local_cache'] && $globals['Amazon_S3_media_bucket'] && is_writable('/tmp')) {
        $subdir = '/tmp';
    } else {
        $chain = get_cache_dir_chain($user);
        create_cache_dir_chain(get_avatars_dir(), $chain);
        $subdir = get_avatars_dir() . '/' . $chain;
    }
    if (!is_writable($subdir)) {
        return false;
    }
    $file_base = $subdir . "/{$user}-{$time}";
    $delete = false;
    $original = false;
    if ($globals['Amazon_S3_media_bucket']) {
        // Get avatar from S3
        // Try up to 3 times to download from Amazon
        $try = 0;
        while ($original == false && $try < 3) {
            if (Media::get("{$user}-{$time}-{$size}.jpg", 'avatars', "{$file_base}-{$size}.jpg")) {
                return file_get_contents("{$file_base}-{$size}.jpg");
            }
            if (Media::get("{$user}-{$time}.jpg", 'avatars', "{$file_base}-orig.jpg")) {
                $delete_it = true;
                $original = "{$file_base}-orig.jpg";
            } elseif (is_readable($file_base . '-80.jpg') && filesize($file_base . '-80.jpg') > 0 || Media::get("{$user}-{$time}-80.jpg", 'avatars', "{$file_base}-80.jpg")) {
                $original = $file_base . '-80.jpg';
            } else {
                $try++;
                usleep(rand(1, 20));
                // Wait a little to minimize race-conditions
            }
        }
        if (!$original) {
            // The images were not found in S3
            if (($buckets = Media::buckets(false)) && in_array($globals['Amazon_S3_media_bucket'], $buckets) && is_writable(mnmpath . '/' . $globals['cache_dir'])) {
                // Double check
                avatars_remove($user);
            }
            return false;
        }
    } else {
        //Get from DB
        if (!is_readable($file_base . '-80.jpg')) {
            $img = $db->get_var("select avatar_image from avatars where avatar_id={$user}");
            if (!strlen($img) > 0) {
                if (is_writable(mnmpath . '/' . $globals['cache_dir'])) {
                    // Double check
                    avatars_remove($user);
                }
                return false;
            }
            file_put_contents($file_base . '-80.jpg', $img);
            $original = $file_base . '-80.jpg';
        }
    }
    if ($size > 0 && $size != 80) {
        avatar_resize($original, "{$file_base}-{$size}.jpg", $size);
        if ($delete_it) {
            @unlink($original);
        }
    }
    return file_get_contents("{$file_base}-{$size}.jpg");
}
		function cacheThumbnail($itemId, $item) {
			global $database, $db;
			if (!isset($item) || !is_array($item) || !defined('ROOT') || !isset($itemId) || !Validator::getBool($itemId))
				return false;

			$cacheDir = ROOT. '/cache/thumbnail';
			if (!is_dir($cacheDir)) func::mkpath($cacheDir);
			if (!is_writeable($cacheDir)) return false;

			$division = ord(substr(str_replace("http://","",$item['permalink']), 0, 1));

			requireComponent('LZ.PHP.Media');
			$media = new Media;
			$media->set('outputPath', $cacheDir.'/'.$division);

			$item['id'] = $itemId; // for uniqueId

			list($thumbnailLimit, $thumbnailSize, $thumbnailType) = Settings::gets('thumbnailLimit, thumbnailSize, thumbnailType');
			if($thumbnailLimit == 0) return false;

			if (!$result = $media->get($item, $thumbnailSize, $thumbnailLimit, $thumbnailType))
				return false;

			foreach($result['movies'] as $m_item) {
				$tFilename = $db->escape(str_replace($cacheDir, '', $m_item['filename']['fullpath']));
				$tSource = $db->escape($m_item['source']);

				if(!empty($tFilename)) {
					$width = $m_item['width'];
					$height = $m_item['height'];
					$via = $m_item['via'];					
					$insertId = $media->add($itemId, $tFilename, $tSource, $width, $height, 'movie', $via);
				}
			}

			foreach($result['images'] as $i_item) {
				$tFilename = $db->escape(str_replace($cacheDir, '', $i_item['filename']['fullpath']));
				$tSource = $db->escape($i_item['source']);

				if(!empty($tFilename) && $i_item['width'] > 100 && $i_item['height'] > 100) {
					$width = $i_item['width'];
					$height = $i_item['height'];
					$insertId = $media->add($itemId, $tFilename, $tSource, $width, $height, 'image');
				}
			}
	
			if(isset($insertId)) {
				$db->execute("UPDATE {$database['prefix']}FeedItems SET thumbnailId='$insertId' WHERE id='$itemId'");
			}

			return true;
		}
예제 #14
0
 /**
  * Apply media transformation to media in specified field of current loaded row. When a transformation is applied
  * it is applied to all versions, including the "original." A copy of the original is stashed in a "virtual" version named "_undo_"
  * to make it possible to recover the original media, if desired, by calling removeMediaTransformations().
  *
  * @param string $ps_field The name of the media field
  * @param string $ps_op A valid media transformation op code, as defined by the media plugin handling the media being transformed.
  * @param array $pa_params The parameters for the op code, as defined by the media plugin handling the media being transformed.
  * @param array $pa_options An array of options. No options are currently implemented.
  *
  * @return bool True on success, false if an error occurred.
  */
 public function applyMediaTransformation($ps_field, $ps_op, $pa_params, $pa_options = null)
 {
     $va_media_info = $this->getMediaInfo($ps_field);
     if (!is_array($va_media_info)) {
         return null;
     }
     if (isset($pa_options['revert']) && $pa_options['revert'] && isset($va_media_info['_undo_'])) {
         $vs_path = $vs_undo_path = $this->getMediaPath($ps_field, '_undo_');
         $va_transformation_history = array();
     } else {
         $vs_path = $this->getMediaPath($ps_field, 'original');
         // Copy original into "undo" slot (if undo slot is empty)
         $vs_undo_path = !isset($va_media_info['_undo_']) ? $vs_path : $this->getMediaPath($ps_field, '_undo_');
         if (!is_array($va_transformation_history = $va_media_info['TRANSFORMATION_HISTORY'])) {
             $va_transformation_history = array();
         }
     }
     // TODO: Check if transformation valid for this media
     // Apply transformation to original
     $o_media = new Media();
     $o_media->read($vs_path);
     $o_media->transform($ps_op, $pa_params);
     $va_transformation_history[$ps_op][] = $pa_params;
     $vs_tmp_basename = tempnam(caGetTempDirPath(), 'ca_media_rotation_tmp');
     $o_media->write($vs_tmp_basename, $o_media->get('mimetype'), array());
     // Regenerate derivatives
     $this->setMode(ACCESS_WRITE);
     $this->set($ps_field, $vs_tmp_basename . "." . $va_media_info['original']['EXTENSION'], $vs_undo_path ? array('undo' => $vs_undo_path, 'TRANSFORMATION_HISTORY' => $va_transformation_history) : array('TRANSFORMATION_HISTORY' => $va_transformation_history));
     $this->setAsChanged($ps_field);
     $this->update();
     return $this->numErrors() ? false : true;
 }
예제 #15
0
 /**
  * Method invoked when the task queue needs to actually execute the task. For mediaproc this means
  * actually doing the processing of media!
  *
  * Return false on failure/error and sets the error property with an error description. Returns an array
  * with processing details on success.
  *
  * @param array $pa_parameters An unserialized parameters array for the current task (eg. unserialized data from ca_task_queue.parameters)
  * @return array Returns false on error, or an array with processing details on success
  */
 public function process($pa_parameters)
 {
     $vs_table = $pa_parameters["TABLE"];
     // name of table of record we're processing
     $vs_field = $pa_parameters["FIELD"];
     // name of field in record we're processing
     $vs_pk = $pa_parameters["PK"];
     // Field name of primary key of record we're processing
     $vn_id = $pa_parameters["PK_VAL"];
     // Value of primary key
     $vs_input_mimetype = $pa_parameters["INPUT_MIMETYPE"];
     // Mimetype of input file
     $vs_input_file = $pa_parameters["FILENAME"];
     // Full path to input file
     // Array of media versions to process; keys are version names,
     // values are arrays with info about processing for that version
     // Currently the info array contains a single key, 'VOLUME', which indicates
     // the volume the version should be written to
     $va_versions = $pa_parameters["VERSIONS"];
     $va_options = $pa_parameters["OPTIONS"];
     // Array of processing options; names of options to employ are keys, settings are values
     // If true, then input media is *not* deleted
     $vb_dont_delete_original_media = (bool) $pa_parameters["DONT_DELETE_OLD_MEDIA"];
     $va_report = array('errors' => array(), 'notes' => array());
     $o_dm = Datamodel::load();
     $o_media_volumes = new MediaVolumes();
     $o_media = new Media();
     $o_media_proc_settings = new MediaProcessingSettings($vs_table, $vs_field);
     $vs_media_type = $o_media_proc_settings->canAccept($vs_input_mimetype);
     $va_version_info = $o_media_proc_settings->getMediaTypeVersions($vs_media_type);
     if (!file_exists($vs_input_file)) {
         $o_eventlog = new EventLog();
         $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = file '{$vs_input_file}' did not exist; queued file was discarded"));
         $va_report['errors'][] = _t("Record %1.field = file '%2' did not exist; queued file was discarded", $vs_table, $vs_input_file);
         return $va_report;
     }
     if ($t_instance = $o_dm->getInstanceByTableName($vs_table, true)) {
         if ($t_instance->hasField($vs_field)) {
             if (!$t_instance->load($vn_id)) {
                 # record no longer exists
                 if (!$vb_dont_delete_original_media) {
                     @unlink($vs_input_file);
                 }
                 $o_eventlog = new EventLog();
                 $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded"));
                 $o_media->cleanup();
                 $va_report['errors'][] = _t("Record %1.field = %2 did not exist; queued file was discarded", $vs_table, $vn_id);
                 return $va_report;
             }
         } else {
             # bad field name
             $this->error->setError(551, _t("Invalid media field '%1' in table '%2'", $vs_field, $vs_table), "mediaproc->process()");
             return false;
         }
     } else {
         # bad table name
         $this->error->setError(550, _t("Invalid media field table '%1'", $vs_table), "mediaproc->process()");
         return false;
     }
     $va_old_media_to_delete = array();
     foreach ($va_versions as $v => $va_version_settings) {
         $vs_use_icon = null;
         if (!file_exists($vs_input_file)) {
             $this->error->setError(505, _t("Input media file '%1' does not exist", $vs_input_file), "mediaproc->process()");
             $o_media->cleanup();
             return false;
         }
         if (!is_readable($vs_input_file)) {
             $this->error->setError(506, _t("Denied permission to read input media file '%1'", $vs_input_file), "mediaproc->process()");
             $o_media->cleanup();
             return false;
         }
         if (!$o_media->read($vs_input_file)) {
             $this->error->setError(1600, _t("Could not process input media file '%1': %2", $vs_input_file, join('; ', $o_media->getErrors())), "mediaproc->process()");
             $o_media->cleanup();
             return false;
         }
         $vs_rule = isset($va_version_info[$v]['RULE']) ? $va_version_info[$v]['RULE'] : '';
         $va_rules = $o_media_proc_settings->getMediaTransformationRule($vs_rule);
         $va_volume_info = $o_media_volumes->getVolumeInformation($va_version_settings['VOLUME']);
         if (sizeof($va_rules) == 0) {
             $vs_output_mimetype = $vs_input_mimetype;
             #
             # don't process this media, just copy the file
             #
             $vs_ext = $o_media->mimetype2extension($vs_output_mimetype);
             if (!$vs_ext) {
                 $this->error->setError(1600, _t("File could not be copied for %1; can't convert mimetype %2 to extension", $vs_field, $vs_output_mimetype), "mediaproc->process()");
                 $o_media->cleanup();
                 return false;
             }
             if (($vs_dirhash = $this->_getDirectoryHash($va_volume_info["absolutePath"], $vn_id)) === false) {
                 $this->error->setError(1600, _t("Couldn't create subdirectory for file for %1", $vs_field), "mediaproc->process()");
                 $o_media->cleanup();
                 return false;
             }
             $vs_magic = rand(0, 99999);
             $vs_filepath = $va_volume_info["absolutePath"] . "/" . $vs_dirhash . "/" . $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext;
             if (!copy($vs_input_file, $vs_filepath)) {
                 $this->error->setError(504, _t("File could not be copied for %1", $vs_field), "mediaproc->process()");
                 $o_media->cleanup();
                 return false;
             }
             if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) {
                 $entity_key = join("/", array($vs_table, $vs_field, $vn_id, $v));
                 $row_key = join("/", array($vs_table, $vn_id));
                 foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) {
                     $vs_mirror_method = $va_mirror_info["method"];
                     $vs_queue = $vs_mirror_method . "mirror";
                     $tq = new TaskQueue();
                     if (!$tq->cancelPendingTasksForEntity($entity_key)) {
                         $this->error->setError(560, _t("Could not cancel pending tasks"), "mediaproc->process()");
                         $o_media->cleanup();
                         return false;
                     }
                     if ($tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $va_version_settings['VOLUME'], "FIELD" => $vs_field, "TABLE" => $vs_table, "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $vs_filepath, "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $vs_dirhash, "FILENAME" => $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $vs_pk, "PK_VAL" => $vn_id), array("priority" => 100, "entity_key" => $entity_key, "row_key" => $row_key))) {
                         continue;
                     } else {
                         $this->error->setError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $vs_queue), "mediaproc->process()");
                     }
                 }
             }
             $media_desc[$v] = array("VOLUME" => $va_version_settings['VOLUME'], "MIMETYPE" => $vs_output_mimetype, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height"), "PROPERTIES" => $o_media->getProperties(), "FILENAME" => $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext, "HASH" => $vs_dirhash, "MAGIC" => $vs_magic, "EXTENSION" => $vs_ext, "MD5" => md5_file($vs_filepath));
         } else {
             $o_media->set('version', $v);
             while (list($operation, $pa_parameters) = each($va_rules)) {
                 if ($operation === 'SET') {
                     foreach ($pa_parameters as $pp => $pv) {
                         if ($pp == 'format') {
                             $vs_output_mimetype = $pv;
                         } else {
                             $o_media->set($pp, $pv);
                         }
                     }
                 } else {
                     if (!$o_media->transform($operation, $pa_parameters)) {
                         $this->error = $o_media->errors[0];
                         $o_media->cleanup();
                         return false;
                     }
                 }
             }
             if (!$vs_output_mimetype) {
                 $vs_output_mimetype = $vs_input_mimetype;
             }
             if (!($vs_ext = $o_media->mimetype2extension($vs_output_mimetype))) {
                 $this->error->setError(1600, _t("File could not be processed for %1; can't convert mimetype %2 to extension", $vs_field, $vs_output_mimetype), "mediaproc->process()");
                 $o_media->cleanup();
                 return false;
             }
             if (($vs_dirhash = $this->_getDirectoryHash($va_volume_info["absolutePath"], $vn_id)) === false) {
                 $this->error->setError(1600, _t("Couldn't create subdirectory for file for %1", $vs_field), "mediaproc->process()");
                 $o_media->cleanup();
                 return false;
             }
             $vs_magic = rand(0, 99999);
             $vs_filepath = $va_volume_info["absolutePath"] . "/" . $vs_dirhash . "/" . $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v;
             if (!($vs_output_file = $o_media->write($vs_filepath, $vs_output_mimetype, $va_options))) {
                 $this->error = $o_media->errors[0];
                 $o_media->cleanup();
                 return false;
             } else {
                 if ($vs_output_file === __CA_MEDIA_VIDEO_DEFAULT_ICON__ || $vs_output_file === __CA_MEDIA_AUDIO_DEFAULT_ICON__ || $vs_output_file === __CA_MEDIA_DOCUMENT_DEFAULT_ICON__) {
                     $vs_use_icon = $vs_output_file;
                 } else {
                     $va_output_files[] = $vs_output_file;
                 }
             }
             if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) {
                 $entity_key = join("/", array($vs_table, $vs_field, $vn_id, $v));
                 $row_key = join("/", array($vs_table, $vn_id));
                 foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) {
                     $vs_mirror_method = $va_mirror_info["method"];
                     $vs_queue = $vs_mirror_method . "mirror";
                     $tq = new TaskQueue();
                     if (!$tq->cancelPendingTasksForEntity($entity_key)) {
                         $this->error->setError(560, _t("Could not cancel pending tasks"), "mediaproc->process()");
                         $o_media->cleanup();
                         return false;
                     }
                     if ($tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $va_version_settings['VOLUME'], "FIELD" => $vs_field, "TABLE" => $vs_table, "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $vs_filepath, "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $vs_dirhash, "FILENAME" => $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $vs_pk, "PK_VAL" => $vn_id), array("priority" => 100, "entity_key" => $entity_key, "row_key" => $row_key))) {
                         continue;
                     } else {
                         $this->error->setError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $vs_queue), "mediaproc->process()");
                     }
                 }
             }
             if ($vs_use_icon) {
                 $media_desc[$v] = array("MIMETYPE" => $vs_output_mimetype, "USE_ICON" => $vs_use_icon, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height"));
             } else {
                 $media_desc[$v] = array("VOLUME" => $va_version_settings['VOLUME'], "MIMETYPE" => $vs_output_mimetype, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height"), "PROPERTIES" => $o_media->getProperties(), "FILENAME" => $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext, "HASH" => $vs_dirhash, "MAGIC" => $vs_magic, "EXTENSION" => $vs_ext, "MD5" => md5_file($vs_filepath . "." . $vs_ext));
             }
         }
         if (!$vb_dont_delete_original_media) {
             $vs_old_media_path = $t_instance->getMediaPath($vs_field, $v);
             if ($vs_old_media_path && $vs_filepath . "." . $vs_ext != $vs_old_media_path && $vs_input_file != vs_old_media_path) {
                 //@unlink($t_instance->getMediaPath($vs_field, $v));
                 $va_old_media_to_delete[] = $vs_old_media_path;
             }
         }
     }
     #
     # Update record
     #
     if ($t_instance->load($vn_id)) {
         if (method_exists($t_instance, "useBlobAsMediaField")) {
             // support for attributes - force field to be FT_MEDIA
             $t_instance->useBlobAsMediaField(true);
         }
         $md = $t_instance->get($vs_field);
         $va_merged_media_desc = is_array($md) ? $md : array();
         foreach ($media_desc as $vs_k => $va_v) {
             $va_merged_media_desc[$vs_k] = $va_v;
         }
         $t_instance->setMode(ACCESS_WRITE);
         $t_instance->setMediaInfo($vs_field, $va_merged_media_desc);
         $t_instance->update();
         if ($t_instance->numErrors()) {
             # get rid of files we just created
             foreach ($va_output_files as $vs_to_delete) {
                 @unlink($vs_to_delete);
             }
             $this->error->setError(560, _t("Could not update %1.%2: %3", $vs_table, $vs_field, join(", ", $t_instance->getErrors())), "mediaproc->process()");
             $o_media->cleanup();
             return false;
         }
         $va_report['notes'][] = _t("Processed file %1", $vs_input_file);
         // Generate preview frames for media that support that (Eg. video)
         // and add them as "multifiles" assuming the current model supports that (ca_object_representations does)
         $o_config = Configuration::load();
         if (((bool) $o_config->get('video_preview_generate_frames') || (bool) $o_config->get('document_preview_generate_pages')) && method_exists($t_instance, 'addFile')) {
             $o_media->read($vs_input_file);
             $va_preview_frame_list = $o_media->writePreviews(array('width' => $o_media->get("width"), 'height' => $o_media->get("height"), 'numberOfFrames' => $o_config->get('video_preview_max_number_of_frames'), 'numberOfPages' => $o_config->get('document_preview_max_number_of_pages'), 'frameInterval' => $o_config->get('video_preview_interval_between_frames'), 'pageInterval' => $o_config->get('document_preview_interval_between_pages'), 'startAtTime' => $o_config->get('video_preview_start_at'), 'endAtTime' => $o_config->get('video_preview_end_at'), 'startAtPage' => $o_config->get('document_preview_start_page'), 'outputDirectory' => __CA_APP_DIR__ . '/tmp'));
             $t_instance->removeAllFiles();
             // get rid of any previously existing frames (they might be hanging around if we're editing an existing record)
             if (is_array($va_preview_frame_list)) {
                 foreach ($va_preview_frame_list as $vn_time => $vs_frame) {
                     $t_instance->addFile($vs_frame, $vn_time, true);
                     // the resource path for each frame is it's time, in seconds (may be fractional) for video, or page number for documents
                     @unlink($vs_frame);
                     // clean up tmp preview frame file
                 }
             }
         }
         if (!$vb_dont_delete_original_media) {
             @unlink($vs_input_file);
         }
         foreach ($va_old_media_to_delete as $vs_to_delete) {
             @unlink($vs_to_delete);
         }
         $o_media->cleanup();
         return $va_report;
     } else {
         # record no longer exists
         if (!$vb_dont_delete_original_media) {
             @unlink($vs_input_file);
         }
         $o_eventlog = new EventLog();
         $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded"));
         $o_media->cleanup();
         $va_report['errors'][] = _t("Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded");
         return $va_report;
     }
 }
예제 #16
0
파일: upload.php 프로젝트: manelio/woolr
 function restore()
 {
     global $globals;
     if ($globals['Amazon_S3_media_bucket']) {
         Upload::create_cache_dir($this->id);
         $res = Media::get($this->filename(), $this->type, $this->pathname());
         @chmod($this->pathname(), 0777);
         return $res;
     }
 }
예제 #17
0
 /**
  * @param array $pa_options Options include:
  *		dontUseDefaultIcons = If set to true, write will fail rather than use default icons when preview can't be generated. Default is false – to use default icons.
  *
  */
 public function write($ps_filepath, $ps_mimetype, $pa_options = null)
 {
     if (!$this->handle) {
         return false;
     }
     $vb_dont_allow_default_icons = isset($pa_options['dontUseDefaultIcons']) && $pa_options['dontUseDefaultIcons'] ? true : false;
     # is mimetype valid?
     if (!($vs_ext = $this->info["EXPORT"][$ps_mimetype])) {
         $this->postError(1610, _t("Can't convert file to %1", $ps_mimetype), "WLPlugMediaOffice->write()");
         return false;
     }
     # write the file
     if ($ps_mimetype == "application/msword") {
         if (!copy($this->filepath, $ps_filepath . ".doc")) {
             $this->postError(1610, _t("Couldn't write file to '%1'", $ps_filepath), "WLPlugMediaOffice->write()");
             return false;
         }
     } else {
         if (!isset(WLPlugMediaOffice::$s_pdf_conv_cache[$this->filepath]) && $this->opb_libre_office_installed) {
             $vs_tmp_dir_path = caGetTempDirPath();
             $va_tmp = explode("/", $this->filepath);
             $vs_out_file = array_pop($va_tmp);
             putenv("HOME={$vs_tmp_dir_path}");
             // libreoffice will fail silently if you don't set this environment variable to a directory it can write to. Nice way to waste a day debugging. Yay!
             exec($this->ops_libreoffice_path . " --nologo --nofirststartwizard --headless -convert-to pdf " . caEscapeShellArg($this->filepath) . "  -outdir " . caEscapeShellArg($vs_tmp_dir_path) . " 2>&1", $va_output, $vn_return);
             exec($this->ops_libreoffice_path . " --nologo --nofirststartwizard --headless -convert-to html " . caEscapeShellArg($this->filepath) . "  -outdir " . caEscapeShellArg($vs_tmp_dir_path) . " 2>&1", $va_output, $vn_return);
             $va_out_file = explode(".", $vs_out_file);
             if (sizeof($va_out_file) > 1) {
                 array_pop($va_out_file);
             }
             $this->handle['content'] = strip_tags(file_get_contents("{$vs_tmp_dir_path}/" . join(".", $va_out_file) . ".html"));
             $va_out_file[] = 'pdf';
             WLPlugMediaOffice::$s_pdf_conv_cache[$this->filepath] = "{$vs_tmp_dir_path}/" . join(".", $va_out_file);
             $o_media = new Media();
             if ($o_media->read(WLPlugMediaOffice::$s_pdf_conv_cache[$this->filepath])) {
                 $this->set('width', $this->ohandle["width"] = $o_media->get('width'));
                 $this->set('height', $this->ohandle["height"] = $o_media->get('height'));
                 $this->set('resolution', $this->ohandle["resolution"] = $o_media->get('resolution'));
             }
         }
         if ($vs_media = WLPlugMediaOffice::$s_pdf_conv_cache[$this->filepath]) {
             switch ($ps_mimetype) {
                 case 'application/pdf':
                     $o_media = new Media();
                     $o_media->read($vs_media);
                     $o_media->set('version', $this->get('version'));
                     $o_media->write($ps_filepath, $ps_mimetype, array());
                     $vs_filepath_with_extension = $ps_filepath . ".pdf";
                     break;
                 case 'image/jpeg':
                     $o_media = new Media();
                     $o_media->read($vs_media);
                     $o_media->set('version', $this->get('version'));
                     foreach ($this->opa_transformations as $va_transform) {
                         $o_media->transform($va_transform['op'], $va_transform['params']);
                     }
                     $o_media->write($ps_filepath, $ps_mimetype, array());
                     $this->set('width', $o_media->get('width'));
                     $this->set('height', $o_media->get('height'));
                     $vs_filepath_with_extension = $ps_filepath . ".jpg";
                     break;
             }
         }
         # use default media icons
         if (!file_exists($vs_filepath_with_extension)) {
             // always jpegs
             return $vb_dont_allow_default_icons ? null : __CA_MEDIA_DOCUMENT_DEFAULT_ICON__;
         }
     }
     $this->properties["mimetype"] = $ps_mimetype;
     $this->properties["filesize"] = filesize($ps_filepath . "." . $vs_ext);
     //$this->properties["typename"] = $this->typenames[$ps_mimetype];
     return $ps_filepath . "." . $vs_ext;
 }