I really need to be able to extract the metadata from a .ttf true type font file.
I'm building a central database of all the fonts all our designers use (they're forever swapping fonts via email to take over design elements, etc). I want to get all the fonts, some have silly names like 00001.ttf, so file name is no help, but I know the fonts have metadata, I need some way to extract that in PHP.
Then I can create a loop to look through the directories I've specified, get this data (and any other data I can get at the same time, and add it to a database.
I just really need help with the reading of this metadata part.
I came across this link. It will do what you want (I've tested it and posted results). Just pass the class the path of the TTF file you want to parse the data out of. then use $fontinfo[1].' '.$fontinfo[2] for the name.
In case you don't want to register, here is the class
Resulting Data
Array
(
[1] => Almonte Snow
[2] => Regular
[3] => RayLarabie: Almonte Snow: 2000
[4] => Almonte Snow
[5] => Version 2.000 2004
[6] => AlmonteSnow
[8] => Ray Larabie
[9] => Ray Larabie
[10] => Larabie Fonts is able to offer unique free fonts through the generous support of visitors to the site. Making fonts is my full-time job and every donation, in any amount, enables me to continue running the site and creating new fonts. If you would like to support Larabie Fonts visit www.larabiefonts.com for details.
[11] => http://www.larabiefonts.com
[12] => http://www.typodermic.com
)
Usage
<?php
include 'ttfInfo.class.php';
$fontinfo = getFontInfo('c:\windows\fonts\_LDS_almosnow.ttf');
echo '<pre>';
print_r($fontinfo);
echo '</pre>';
?>
ttfInfo.class.php
<?php
/**
* ttfInfo class
* Retrieve data stored in a TTF files 'name' table
*
* #original author Unknown
* found at http://www.phpclasses.org/browse/package/2144.html
*
* #ported for used on http://www.nufont.com
* #author Jason Arencibia
* #version 0.2
* #copyright (c) 2006 GrayTap Media
* #website http://www.graytap.com
* #license GPL 2.0
* #access public
*
* #todo: Make it Retrieve additional information from other tables
*
*/
class ttfInfo {
/**
* variable $_dirRestriction
* Restrict the resource pointer to this directory and above.
* Change to 1 for to allow the class to look outside of it current directory
* #protected
* #var int
*/
protected $_dirRestriction = 1;
/**
* variable $_dirRestriction
* Restrict the resource pointer to this directory and above.
* Change to 1 for nested directories
* #protected
* #var int
*/
protected $_recursive = 0;
/**
* variable $fontsdir
* This is to declare this variable as protected
* don't edit this!!!
* #protected
*/
protected $fontsdir;
/**
* variable $filename
* This is to declare this varable as protected
* don't edit this!!!
* #protected
*/
protected $filename;
/**
* function setFontFile()
* set the filename
* #public
* #param string $data the new value
* #return object reference to this
*/
public function setFontFile($data)
{
if ($this->_dirRestriction && preg_match('[\.\/|\.\.\/]', $data))
{
$this->exitClass('Error: Directory restriction is enforced!');
}
$this->filename = $data;
return $this;
} // public function setFontFile
/**
* function setFontsDir()
* set the Font Directory
* #public
* #param string $data the new value
* #return object referrence to this
*/
public function setFontsDir($data)
{
if ($this->_dirRestriction && preg_match('[\.\/|\.\.\/]', $data))
{
$this->exitClass('Error: Directory restriction is enforced!');
}
$this->fontsdir = $data;
return $this;
} // public function setFontsDir
/**
* function readFontsDir()
* #public
* #return information contained in the TTF 'name' table of all fonts in a directory.
*/
public function readFontsDir()
{
if (empty($this->fontsdir)) { $this->exitClass('Error: Fonts Directory has not been set with setFontsDir().'); }
if (empty($this->backupDir)){ $this->backupDir = $this->fontsdir; }
$this->array = array();
$d = dir($this->fontsdir);
while (false !== ($e = $d->read()))
{
if($e != '.' && $e != '..')
{
$e = $this->fontsdir . $e;
if($this->_recursive && is_dir($e))
{
$this->setFontsDir($e);
$this->array = array_merge($this->array, readFontsDir());
}
else if ($this->is_ttf($e) === true)
{
$this->setFontFile($e);
$this->array[$e] = $this->getFontInfo();
}
}
}
if (!empty($this->backupDir)){ $this->fontsdir = $this->backupDir; }
$d->close();
return $this;
} // public function readFontsDir
/**
* function setProtectedVar()
* #public
* #param string $var the new variable
* #param string $data the new value
* #return object reference to this
* DISABLED, NO REAL USE YET
public function setProtectedVar($var, $data)
{
if ($var == 'filename')
{
$this->setFontFile($data);
} else {
//if (isset($var) && !empty($data))
$this->$var = $data;
}
return $this;
}
*/
/**
* function getFontInfo()
* #public
* #return information contained in the TTF 'name' table.
*/
public function getFontInfo()
{
$fd = fopen ($this->filename, "r");
$this->text = fread ($fd, filesize($this->filename));
fclose ($fd);
$number_of_tables = hexdec($this->dec2ord($this->text[4]).$this->dec2ord($this->text[5]));
for ($i=0;$i<$number_of_tables;$i++)
{
$tag = $this->text[12+$i*16].$this->text[12+$i*16+1].$this->text[12+$i*16+2].$this->text[12+$i*16+3];
if ($tag == 'name')
{
$this->ntOffset = hexdec(
$this->dec2ord($this->text[12+$i*16+8]).$this->dec2ord($this->text[12+$i*16+8+1]).
$this->dec2ord($this->text[12+$i*16+8+2]).$this->dec2ord($this->text[12+$i*16+8+3]));
$offset_storage_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+4]).$this->dec2ord($this->text[$this->ntOffset+5]));
$number_name_records_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+2]).$this->dec2ord($this->text[$this->ntOffset+3]));
}
}
$storage_dec = $offset_storage_dec + $this->ntOffset;
$storage_hex = strtoupper(dechex($storage_dec));
for ($j=0;$j<$number_name_records_dec;$j++)
{
$platform_id_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+0]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+1]));
$name_id_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+6]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+7]));
$string_length_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+8]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+9]));
$string_offset_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+10]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+11]));
if (!empty($name_id_dec) and empty($font_tags[$name_id_dec]))
{
for($l=0;$l<$string_length_dec;$l++)
{
if (ord($this->text[$storage_dec+$string_offset_dec+$l]) == '0') { continue; }
else { $font_tags[$name_id_dec] .= ($this->text[$storage_dec+$string_offset_dec+$l]); }
}
}
}
return $font_tags;
} // public function getFontInfo
/**
* function getCopyright()
* #public
* #return 'Copyright notice' contained in the TTF 'name' table at index 0
*/
public function getCopyright()
{
$this->info = $this->getFontInfo();
return $this->info[0];
} // public function getCopyright
/**
* function getFontFamily()
* #public
* #return 'Font Family name' contained in the TTF 'name' table at index 1
*/
public function getFontFamily()
{
$this->info = $this->getFontInfo();
return $this->info[1];
} // public function getFontFamily
/**
* function getFontSubFamily()
* #public
* #return 'Font Subfamily name' contained in the TTF 'name' table at index 2
*/
public function getFontSubFamily()
{
$this->info = $this->getFontInfo();
return $this->info[2];
} // public function getFontSubFamily
/**
* function getFontId()
* #public
* #return 'Unique font identifier' contained in the TTF 'name' table at index 3
*/
public function getFontId()
{
$this->info = $this->getFontInfo();
return $this->info[3];
} // public function getFontId
/**
* function getFullFontName()
* #public
* #return 'Full font name' contained in the TTF 'name' table at index 4
*/
public function getFullFontName()
{
$this->info = $this->getFontInfo();
return $this->info[4];
} // public function getFullFontName
/**
* function dec2ord()
* Used to lessen redundant calls to multiple functions.
* #protected
* #return object
*/
protected function dec2ord($dec)
{
return $this->dec2hex(ord($dec));
} // protected function dec2ord
/**
* function dec2hex()
* private function to perform Hexadecimal to decimal with proper padding.
* #protected
* #return object
*/
protected function dec2hex($dec)
{
return str_repeat('0', 2-strlen(($hex=strtoupper(dechex($dec))))) . $hex;
} // protected function dec2hex
/**
* function dec2hex()
* private function to perform Hexadecimal to decimal with proper padding.
* #protected
* #return object
*/
protected function exitClass($message)
{
echo $message;
exit;
} // protected function dec2hex
/**
* function dec2hex()
* private helper function to test in the file in question is a ttf.
* #protected
* #return object
*/
protected function is_ttf($file)
{
$ext = explode('.', $file);
$ext = $ext[count($ext)-1];
return preg_match("/ttf$/i",$ext) ? true : false;
} // protected function is_ttf
} // class ttfInfo
function getFontInfo($resource)
{
$ttfInfo = new ttfInfo;
$ttfInfo->setFontFile($resource);
return $ttfInfo->getFontInfo();
}
?>
Update 2021
Here is an updated version of the class with some fixes
https://github.com/HusamAamer/TTFInfo.git
Very similar to the previously posted answer... I've been using this class for a long time now.
class fontAttributes extends baseClass
{
// --- ATTRIBUTES ---
/**
* #access private
* #var string
*/
private $_fileName = NULL ; // Name of the truetype font file
/**
* #access private
* #var string
*/
private $_copyright = NULL ; // Copyright
/**
* #access private
* #var string
*/
private $_fontFamily = NULL ; // Font Family
/**
* #access private
* #var string
*/
private $_fontSubFamily = NULL ; // Font SubFamily
/**
* #access private
* #var string
*/
private $_fontIdentifier = NULL ; // Font Unique Identifier
/**
* #access private
* #var string
*/
private $_fontName = NULL ; // Font Name
/**
* #access private
* #var string
*/
private $_fontVersion = NULL ; // Font Version
/**
* #access private
* #var string
*/
private $_postscriptName = NULL ; // Postscript Name
/**
* #access private
* #var string
*/
private $_trademark = NULL ; // Trademark
// --- OPERATIONS ---
private function _returnValue($inString)
{
if (ord($inString) == 0) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($inString,"UTF-8","UTF-16");
} else {
return str_replace(chr(00),'',$inString);
}
} else {
return $inString;
}
} // function _returnValue()
/**
* #access public
* #return integer
*/
public function getCopyright()
{
return $this->_returnValue($this->_copyright);
} // function getCopyright()
/**
* #access public
* #return integer
*/
public function getFontFamily()
{
return $this->_returnValue($this->_fontFamily);
} // function getFontFamily()
/**
* #access public
* #return integer
*/
public function getFontSubFamily()
{
return $this->_returnValue($this->_fontSubFamily);
} // function getFontSubFamily()
/**
* #access public
* #return integer
*/
public function getFontIdentifier()
{
return $this->_returnValue($this->_fontIdentifier);
} // function getFontIdentifier()
/**
* #access public
* #return integer
*/
public function getFontName()
{
return $this->_returnValue($this->_fontName);
} // function getFontName()
/**
* #access public
* #return integer
*/
public function getFontVersion()
{
return $this->_returnValue($this->_fontVersion);
} // function getFontVersion()
/**
* #access public
* #return integer
*/
public function getPostscriptName()
{
return $this->_returnValue($this->_postscriptName);
} // function getPostscriptName()
/**
* #access public
* #return integer
*/
public function getTrademark()
{
return $this->_returnValue($this->_trademark);
} // function getTrademark()
/**
* Convert a big-endian word or longword value to an integer
*
* #access private
* #return integer
*/
private function _UConvert($bytesValue,$byteCount)
{
$retVal = 0;
$bytesLength = strlen($bytesValue);
for ($i=0; $i < $bytesLength; $i++) {
$tmpVal = ord($bytesValue{$i});
$t = pow(256,($byteCount-$i-1));
$retVal += $tmpVal*$t;
}
return $retVal;
} // function UConvert()
/**
* Convert a big-endian word value to an integer
*
* #access private
* #return integer
*/
private function _USHORT($stringValue) {
return $this->_UConvert($stringValue,2);
}
/**
* Convert a big-endian word value to an integer
*
* #access private
* #return integer
*/
private function _ULONG($stringValue) {
return $this->_UConvert($stringValue,4);
}
/**
* Read the Font Attributes
*
* #access private
* #return integer
*/
private function readFontAttributes() {
$fontHandle = fopen($this->_fileName, "rb");
// Read the file header
$TT_OFFSET_TABLE = fread($fontHandle, 12);
$uMajorVersion = $this->_USHORT(substr($TT_OFFSET_TABLE,0,2));
$uMinorVersion = $this->_USHORT(substr($TT_OFFSET_TABLE,2,2));
$uNumOfTables = $this->_USHORT(substr($TT_OFFSET_TABLE,4,2));
// $uSearchRange = $this->_USHORT(substr($TT_OFFSET_TABLE,6,2));
// $uEntrySelector = $this->_USHORT(substr($TT_OFFSET_TABLE,8,2));
// $uRangeShift = $this->_USHORT(substr($TT_OFFSET_TABLE,10,2));
// Check is this is a true type font and the version is 1.0
if ($uMajorVersion != 1 || $uMinorVersion != 0) {
fclose($fontHandle);
throw new Exception($this->_fileName.' is not a Truetype font file') ;
}
// Look for details of the name table
$nameTableFound = false;
for ($t=0; $t < $uNumOfTables; $t++) {
$TT_TABLE_DIRECTORY = fread($fontHandle, 16);
$szTag = substr($TT_TABLE_DIRECTORY,0,4);
if (strtolower($szTag) == 'name') {
// $uCheckSum = $this->_ULONG(substr($TT_TABLE_DIRECTORY,4,4));
$uOffset = $this->_ULONG(substr($TT_TABLE_DIRECTORY,8,4));
// $uLength = $this->_ULONG(substr($TT_TABLE_DIRECTORY,12,4));
$nameTableFound = true;
break;
}
}
if (!$nameTableFound) {
fclose($fontHandle);
throw new Exception('Can\'t find name table in '.$this->_fileName) ;
}
// Set offset to the start of the name table
fseek($fontHandle,$uOffset,SEEK_SET);
$TT_NAME_TABLE_HEADER = fread($fontHandle, 6);
// $uFSelector = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,0,2));
$uNRCount = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,2,2));
$uStorageOffset = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,4,2));
$attributeCount = 0;
for ($a=0; $a < $uNRCount; $a++) {
$TT_NAME_RECORD = fread($fontHandle, 12);
$uNameID = $this->_USHORT(substr($TT_NAME_RECORD,6,2));
if ($uNameID <= 7) {
// $uPlatformID = $this->_USHORT(substr($TT_NAME_RECORD,0,2));
$uEncodingID = $this->_USHORT(substr($TT_NAME_RECORD,2,2));
// $uLanguageID = $this->_USHORT(substr($TT_NAME_RECORD,4,2));
$uStringLength = $this->_USHORT(substr($TT_NAME_RECORD,8,2));
$uStringOffset = $this->_USHORT(substr($TT_NAME_RECORD,10,2));
if ($uStringLength > 0) {
$nPos = ftell($fontHandle);
fseek($fontHandle,$uOffset + $uStringOffset + $uStorageOffset,SEEK_SET);
$testValue = fread($fontHandle, $uStringLength);
if (trim($testValue) > '') {
switch ($uNameID) {
case 0 : if ($this->_copyright == NULL) {
$this->_copyright = $testValue;
$attributeCount++;
}
break;
case 1 : if ($this->_fontFamily == NULL) {
$this->_fontFamily = $testValue;
$attributeCount++;
}
break;
case 2 : if ($this->_fontSubFamily == NULL) {
$this->_fontSubFamily = $testValue;
$attributeCount++;
}
break;
case 3 : if ($this->_fontIdentifier == NULL) {
$this->_fontIdentifier = $testValue;
$attributeCount++;
}
break;
case 4 : if ($this->_fontName == NULL) {
$this->_fontName = $testValue;
$attributeCount++;
}
break;
case 5 : if ($this->_fontVersion == NULL) {
$this->_fontVersion = $testValue;
$attributeCount++;
}
break;
case 6 : if ($this->_postscriptName == NULL) {
$this->_postscriptName = $testValue;
$attributeCount++;
}
break;
case 7 : if ($this->_trademark == NULL) {
$this->_trademark = $testValue;
$attributeCount++;
}
break;
}
}
fseek($fontHandle,$nPos,SEEK_SET);
}
}
if ($attributeCount > 7) {
break;
}
}
fclose($fontHandle);
return true;
}
/**
* #access constructor
* #return void
*/
function __construct($fileName='') {
if ($fileName == '') {
throw new Exception('Font File has not been specified') ;
}
$this->_fileName = $fileName;
if (!file_exists($this->_fileName)) {
throw new Exception($this->_fileName.' does not exist') ;
} elseif (!is_readable($this->_fileName)) {
throw new Exception($this->_fileName.' is not a readable file') ;
}
return $this->readFontAttributes();
} // function constructor()
} /* end of class fontAttributes */
Why reinvent the wheel when the fine people at DOMPDF project has already done the work for you? Take a look at php-font-lib # https://github.com/PhenX/php-font-lib. This has all the features that you have asked for and supports other font formats as well. Look at the demo UI # http://pxd.me/php-font-lib/www/font_explorer.html to get an idea about what kind of information you can get from this library.
Related
I would like to find a way to use image magick in the following class to convert the source to jpg (the code come from phpWord library):
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* #see https://github.com/PHPOffice/PHPWord
* #copyright 2010-2018 PHPWord contributors
* #license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\InvalidImageException;
use PhpOffice\PhpWord\Exception\UnsupportedImageTypeException;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\ZipArchive;
use PhpOffice\PhpWord\Style\Image as ImageStyle;
/**
* Image element
*/
class Image extends AbstractElement
{
/**
* Image source type constants
*/
const SOURCE_LOCAL = 'local'; // Local images
const SOURCE_GD = 'gd'; // Generated using GD
const SOURCE_ARCHIVE = 'archive'; // Image in archives zip://$archive#$image
const SOURCE_STRING = 'string'; // Image from string
/**
* Image source
*
* #var string
*/
private $source;
/**
* Source type: local|gd|archive
*
* #var string
*/
private $sourceType;
/**
* Image style
*
* #var ImageStyle
*/
private $style;
/**
* Is watermark
*
* #var bool
*/
private $watermark;
/**
* Name of image
*
* #var string
*/
private $name;
/**
* Image type
*
* #var string
*/
private $imageType;
/**
* Image create function
*
* #var string
*/
private $imageCreateFunc;
/**
* Image function
*
* #var string
*/
private $imageFunc;
/**
* Image extension
*
* #var string
*/
private $imageExtension;
/**
* Is memory image
*
* #var bool
*/
private $memoryImage;
/**
* Image target file name
*
* #var string
*/
private $target;
/**
* Image media index
*
* #var int
*/
private $mediaIndex;
/**
* Has media relation flag; true for Link, Image, and Object
*
* #var bool
*/
protected $mediaRelation = true;
/**
* Create new image element
*
* #param string $source
* #param mixed $style
* #param bool $watermark
* #param string $name
*
* #throws \PhpOffice\PhpWord\Exception\InvalidImageException
* #throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException
*/
public function __construct($source, $style = null, $watermark = false, $name = null)
{
$this->source = $source;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->setIsWatermark($watermark);
$this->setName($name);
$this->checkImage();
}
/**
* Get Image style
*
* #return ImageStyle
*/
public function getStyle()
{
return $this->style;
}
/**
* Get image source
*
* #return string
*/
public function getSource()
{
return $this->source;
}
/**
* Get image source type
*
* #return string
*/
public function getSourceType()
{
return $this->sourceType;
}
/**
* Sets the image name
*
* #param string $value
*/
public function setName($value)
{
$this->name = $value;
}
/**
* Get image name
*
* #return null|string
*/
public function getName()
{
return $this->name;
}
/**
* Get image media ID
*
* #return string
*/
public function getMediaId()
{
return md5($this->source);
}
/**
* Get is watermark
*
* #return bool
*/
public function isWatermark()
{
return $this->watermark;
}
/**
* Set is watermark
*
* #param bool $value
*/
public function setIsWatermark($value)
{
$this->watermark = $value;
}
/**
* Get image type
*
* #return string
*/
public function getImageType()
{
return $this->imageType;
}
/**
* Get image create function
*
* #return string
*/
public function getImageCreateFunction()
{
return $this->imageCreateFunc;
}
/**
* Get image function
*
* #return string
*/
public function getImageFunction()
{
return $this->imageFunc;
}
/**
* Get image extension
*
* #return string
*/
public function getImageExtension()
{
return $this->imageExtension;
}
/**
* Get is memory image
*
* #return bool
*/
public function isMemImage()
{
return $this->memoryImage;
}
/**
* Get target file name
*
* #return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set target file name.
*
* #param string $value
*/
public function setTarget($value)
{
$this->target = $value;
}
/**
* Get media index
*
* #return int
*/
public function getMediaIndex()
{
return $this->mediaIndex;
}
/**
* Set media index.
*
* #param int $value
*/
public function setMediaIndex($value)
{
$this->mediaIndex = $value;
}
/**
* Get image string data
*
* #param bool $base64
* #return string|null
* #since 0.11.0
*/
public function getImageStringData($base64 = false)
{
$source = $this->source;
$actualSource = null;
$imageBinary = null;
$imageData = null;
$isTemp = false;
// Get actual source from archive image or other source
// Return null if not found
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$source = substr($source, 6);
list($zipFilename, $imageFilename) = explode('#', $source);
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$isTemp = true;
$zip->extractTo(Settings::getTempDir(), $imageFilename);
$actualSource = Settings::getTempDir() . DIRECTORY_SEPARATOR . $imageFilename;
}
}
$zip->close();
} else {
$actualSource = $source;
}
// Can't find any case where $actualSource = null hasn't captured by
// preceding exceptions. Please uncomment when you find the case and
// put the case into Element\ImageTest.
// if ($actualSource === null) {
// return null;
// }
// Read image binary data and convert to hex/base64 string
if ($this->sourceType == self::SOURCE_GD) {
$imageResource = call_user_func($this->imageCreateFunc, $actualSource);
if ($this->imageType === 'image/png') {
// PNG images need to preserve alpha channel information
imagesavealpha($imageResource, true);
}
ob_start();
call_user_func($this->imageFunc, $imageResource);
$imageBinary = ob_get_contents();
ob_end_clean();
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageBinary = $this->source;
} else {
$fileHandle = fopen($actualSource, 'rb', false);
if ($fileHandle !== false) {
$imageBinary = fread($fileHandle, filesize($actualSource));
fclose($fileHandle);
}
}
if ($imageBinary !== null) {
if ($base64) {
$imageData = chunk_split(base64_encode($imageBinary));
} else {
$imageData = chunk_split(bin2hex($imageBinary));
}
}
// Delete temporary file if necessary
if ($isTemp === true) {
#unlink($actualSource);
}
return $imageData;
}
/**
* Check memory image, supported type, image functions, and proportional width/height.
*
* #throws \PhpOffice\PhpWord\Exception\InvalidImageException
* #throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException
*/
private function checkImage()
{
$this->setSourceType();
// Check image data
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$imageData = $this->getArchiveImageSize($this->source);
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageData = $this->getStringImageSize($this->source);
} else {
$imageData = #getimagesize($this->source);
}
if (!is_array($imageData)) {
throw new InvalidImageException(sprintf('Invalid image: %s', $this->source));
}
list($actualWidth, $actualHeight, $imageType) = $imageData;
// Check image type support
$supportedTypes = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG);
if ($this->sourceType != self::SOURCE_GD && $this->sourceType != self::SOURCE_STRING) {
$supportedTypes = array_merge($supportedTypes, array(IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM));
}
if (!in_array($imageType, $supportedTypes)) {
throw new UnsupportedImageTypeException();
}
// Define image functions
$this->imageType = image_type_to_mime_type($imageType);
$this->setFunctions();
$this->setProportionalSize($actualWidth, $actualHeight);
}
/**
* Set source type.
*/
private function setSourceType()
{
if (stripos(strrev($this->source), strrev('.php')) === 0) {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_GD;
} elseif (strpos($this->source, 'zip://') !== false) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_ARCHIVE;
} elseif (filter_var($this->source, FILTER_VALIDATE_URL) !== false) {
$this->memoryImage = true;
if (strpos($this->source, 'https') === 0) {
$fileContent = file_get_contents($this->source);
$this->source = $fileContent;
$this->sourceType = self::SOURCE_STRING;
} else {
$this->sourceType = self::SOURCE_GD;
}
} elseif ((strpos($this->source, chr(0)) === false) && #file_exists($this->source)) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_LOCAL;
} else {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_STRING;
}
}
/**
* Get image size from archive
*
* #since 0.12.0 Throws CreateTemporaryFileException.
*
* #param string $source
*
* #throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException
*
* #return array|null
*/
private function getArchiveImageSize($source)
{
$imageData = null;
$source = substr($source, 6);
list($zipFilename, $imageFilename) = explode('#', $source);
$tempFilename = tempnam(Settings::getTempDir(), 'PHPWordImage');
if (false === $tempFilename) {
throw new CreateTemporaryFileException(); // #codeCoverageIgnore
}
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$imageContent = $zip->getFromName($imageFilename);
if ($imageContent !== false) {
file_put_contents($tempFilename, $imageContent);
$imageData = getimagesize($tempFilename);
unlink($tempFilename);
}
}
$zip->close();
}
return $imageData;
}
/**
* get image size from string
*
* #param string $source
*
* #codeCoverageIgnore this method is just a replacement for getimagesizefromstring which exists only as of PHP 5.4
*/
private function getStringImageSize($source)
{
$result = false;
if (!function_exists('getimagesizefromstring')) {
$uri = 'data://application/octet-stream;base64,' . base64_encode($source);
$result = #getimagesize($uri);
} else {
$result = #getimagesizefromstring($source);
}
return $result;
}
/**
* Set image functions and extensions.
*/
private function setFunctions()
{
switch ($this->imageType) {
case 'image/png':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefrompng';
$this->imageFunc = 'imagepng';
$this->imageExtension = 'png';
break;
case 'image/gif':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromgif';
$this->imageFunc = 'imagegif';
$this->imageExtension = 'gif';
break;
case 'image/jpeg':
case 'image/jpg':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromjpeg';
$this->imageFunc = 'imagejpeg';
$this->imageExtension = 'jpg';
break;
case 'image/bmp':
case 'image/x-ms-bmp':
$this->imageType = 'image/bmp';
$this->imageExtension = 'bmp';
break;
case 'image/tiff':
$this->imageExtension = 'tif';
break;
}
}
/**
* Set proportional width/height if one dimension not available.
*
* #param int $actualWidth
* #param int $actualHeight
*/
private function setProportionalSize($actualWidth, $actualHeight)
{
$styleWidth = $this->style->getWidth();
$styleHeight = $this->style->getHeight();
if (!($styleWidth && $styleHeight)) {
if ($styleWidth == null && $styleHeight == null) {
$this->style->setWidth($actualWidth);
$this->style->setHeight($actualHeight);
} elseif ($styleWidth) {
$this->style->setHeight($actualHeight * ($styleWidth / $actualWidth));
} else {
$this->style->setWidth($actualWidth * ($styleHeight / $actualHeight));
}
}
}
/**
* Get is watermark
*
* #deprecated 0.10.0
*
* #codeCoverageIgnore
*/
public function getIsWatermark()
{
return $this->isWatermark();
}
/**
* Get is memory image
*
* #deprecated 0.10.0
*
* #codeCoverageIgnore
*/
public function getIsMemImage()
{
return $this->isMemImage();
}
}
As you can see from the private function checkImage(), the image source must be jpg, gif on png. Sometimes the format of the image is different. So I want to convert it first to jpg.
But I dont know where to implement the following:
$image =$source;
$img = new Imagick($image);
$img->setImageFormat('jpeg');
I tried to put it within the class as follow but I don't think thats how a class works:
public function __construct($source, $style = null, $watermark = false, $name = null)
{
$image =$source;
$img = new Imagick($image);
$img->setImageFormat('jpeg');
$this->source = $img;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->setIsWatermark($watermark);
$this->setName($name);
$this->checkImage();
}
I got the error:
Fatal error: Uncaught Error: Class "PhpOffice\PhpWord\Element\Imagick" not found in /var/www/websource/libraries/vendor/phpoffice/phpword/src/PhpWord/Element/Image.php:145 Stack trace: #0
FYI imagick is installed and work properly when i want to convert an img.
Thank you
I already had a question regarding "importing" records and there data of different plugins/extensions. I got it working after adding the pid and implemented a query builder to get the data of a different plugin (or table in this case). But now I got the problem that the images of the "foreign" table/records or whatever is not included.. when I debug the var the image is only set to int 1. But they are not correctly included. What do I need to do to get this s*** working? :)
//MY CONTROLLER
<?php
namespace Formschoen\Mitarbeiterajax\Controller;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* MitarbeiterController
*/
class MitarbeiterController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* mitarbeiterRepository
*
* #var \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository
*/
protected $mitarbeiterRepository = null;
/**
* #param \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository
*/
public function injectMitarbeiterRepository(\Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository)
{
$this->mitarbeiterRepository = $mitarbeiterRepository;
}
/**
* optionRecordRepository
*
* #var \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
protected $optionRecordRepository;
/**
* #param \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
public function injectOptionRecordRepository(\Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository $optionRecordRepository) {
$this->optionRecordRepository = $optionRecordRepository;
}
/**
* action list
*
* #return void
*/
public function listAction()
{
$mitarbeiters = $this->mitarbeiterRepository->findAll();
$this->view->assign('mitarbeiters', $mitarbeiters);
$this->view->assign("currentPageID", $GLOBALS['TSFE']->id);
$options['autohaus'] = array(
1 => 'some strings'
);
$options['abteilung'] = array(
1 => 'some strings'
);
$this->view->assign('options', $options);
}
/**
* action callAjax
*
* #param \Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter
* #return void
*/
public function callAjaxAction(\Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter)
{
$optionRecords = $this->optionRecordRepository->findAll();
$arguments = $this->request->getArguments();
$selectedAutohaus = $arguments['autohaus'];
$selectedAbteilung = $arguments['abteilung'];
if ($selectedAbteilung == null && $selectedAutohaus == null) {
echo("Bitte ein Autohaus auswählen / eine Abteilung.");
} else if ($selectedAbteilung == null) {
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
$this->view->assign('autohausResult', $autohausResult);
} else {
$mitarbeiterResult = $this->mitarbeiterRepository->findByFilter($selectedAutohaus, $selectedAbteilung);
$this->view->assign('mitarbeiterResult', $mitarbeiterResult);
}
$this->contentObj = $this->configurationManager->getContentObject();
$images=$this->getFileReferences($this->contentObj->data['uid']);
$this->view->assign('images', $images);
}
}
//MY REPOSITORY
<?php
namespace Formschoen\Mitarbeiterajax\Domain\Repository;
/**
* The repository for Mitarbeiters
*/
class MitarbeiterRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
/**
* #param $selectedAutohaus
* #param $selectedAbteilung
*/
public function findByFilter($selectedAutohaus,$selectedAbteilung){
$query = $this->createQuery();
$result = $query->matching($query->logicalAnd(
$query->equals('autohausName', $selectedAutohaus),
$query->equals('abteilung', $selectedAbteilung)
))
->execute();
return $result;
}
/**
* #param $uid
*/
public function findAutohaus($uid)
{
$queryBuilder = $this->objectManager->get(\TYPO3\CMS\Core\Database\ConnectionPool::class)
->getConnectionForTable('tx_ajaxselectlist_domain_model_optionrecord')->createQueryBuilder();
$queryBuilder
->select('*')
->from('tx_ajaxselectlist_domain_model_optionrecord')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid))
);
$result = $queryBuilder->execute()->fetchAll();
if ($returnRawQueryResult) {
$dataMapper = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::class);
return $dataMapper->map($this->objectType, $result);
}
return $result;
}
}
Why dont you just replace this
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
with this
$autohausResult = $this->optionRecordRepository->findByUid($selectedAutohaus);
This way TYPO3 will construct the Models and you will get the image they way you want it
I've setup my server with Yii2 and Humhub ext,
What i'm trying to do is set a rest api to it , but I get 500 Internal server error :
"message": "Cannot declare class humhub\modules\content\models\Content, because the name is already in use",
"file": "***\content\models\Content.php",
The first class is :
<?php
namespace app\models;
use Yii;
include '../humhub/modules/content/models/content.php';
class Content extends \humhub\modules\content\models\Content
{
public function getPosts()
{
return $this->hasMany(Post::className(), ['id' => 'object_id']);
}
}
The second class is (pretty big):
<?php
/**
* #link https://www.humhub.org/
* #copyright Copyright (c) 2017 HumHub GmbH & Co. KG
* #license https://www.humhub.com/licences
*/
namespace humhub\modules\content\models;
include __DIR__ .'/../../../modules\content\models\ContentDeprecated.php';
use Yii;
use humhub\modules\user\components\PermissionManager;
use yii\base\Exception;
use yii\helpers\Url;
use humhub\modules\user\models\User;
use humhub\modules\space\models\Space;
use humhub\modules\content\components\ContentActiveRecord;
use humhub\modules\content\components\ContentContainerActiveRecord;
use humhub\modules\content\permissions\ManageContent;
use yii\rbac\Permission;
/**
* This is the model class for table "content".
*
*
* The followings are the available columns in table 'content':
* #property integer $id
* #property string $guid
* #property string $object_model
* #property integer $object_id
* #property integer $visibility
* #property integer $pinned
* #property string $archived
* #property string $created_at
* #property integer $created_by
* #property string $updated_at
* #property integer $updated_by
* #property ContentContainer $contentContainer
*
* #since 0.5
*/
class Content extends ContentDeprecated
{
/**
* A array of user objects which should informed about this new content.
*
* #var array User
*/
public $notifyUsersOfNewContent = [];
/**
* #var int The private visibility mode (e.g. for space member content or user profile posts for friends)
*/
const VISIBILITY_PRIVATE = 0;
/**
* #var int Public visibility mode, e.g. content which are visibile for followers
*/
const VISIBILITY_PUBLIC = 1;
/**
* #var int Owner visibility mode, only visible for contentContainer + content owner
*/
const VISIBILITY_OWNER = 2;
/**
* #var ContentContainerActiveRecord the Container (e.g. Space or User) where this content belongs to.
*/
protected $_container = null;
/**
* #inheritdoc
*/
public function behaviors()
{
return [
[
'class' => \humhub\components\behaviors\PolymorphicRelation::className(),
'mustBeInstanceOf' => array(ContentActiveRecord::className()),
],
[
'class' => \humhub\components\behaviors\GUID::className(),
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'content';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['object_id', 'visibility', 'pinned'], 'integer'],
[['archived'], 'safe'],
[['guid'], 'string', 'max' => 45],
[['object_model'], 'string', 'max' => 100],
[['object_model', 'object_id'], 'unique', 'targetAttribute' => ['object_model', 'object_id'], 'message' => 'The combination of Object Model and Object ID has already been taken.'],
[['guid'], 'unique']
];
}
/**
* Returns a Content Object by given Class and ID
*
* #param string $className Class Name of the Content
* #param int $id Primary Key
*/
public static function Get($className, $id)
{
$content = self::findOne(['object_model' => $className, 'object_id' => $id]);
if ($content != null) {
return $className::findOne(['id' => $id]);
}
return null;
}
/**
* #inheritdoc
*/
public function beforeSave($insert)
{
if ($this->object_model == "" || $this->object_id == "") {
throw new Exception("Could not save content with object_model or object_id!");
}
// Set some default values
if (!$this->archived) {
$this->archived = 0;
}
if (!$this->visibility) {
$this->visibility = self::VISIBILITY_PRIVATE;
}
if (!$this->pinned) {
$this->pinned = 0;
}
if ($insert) {
if ($this->created_by == "") {
$this->created_by = Yii::$app->user->id;
}
}
$this->stream_sort_date = new \yii\db\Expression('NOW()');
if ($this->created_by == "") {
throw new Exception("Could not save content without created_by!");
}
return parent::beforeSave($insert);
}
/**
* #inheritdoc
*/
public function afterSave($insert, $changedAttributes)
{
$contentSource = $this->getPolymorphicRelation();
foreach ($this->notifyUsersOfNewContent as $user) {
$contentSource->follow($user->id);
}
if ($insert && !$contentSource instanceof \humhub\modules\activity\models\Activity) {
if ($this->container !== null) {
$notifyUsers = array_merge($this->notifyUsersOfNewContent, Yii::$app->notification->getFollowers($this));
\humhub\modules\content\notifications\ContentCreated::instance()
->from($this->user)
->about($contentSource)
->sendBulk($notifyUsers);
\humhub\modules\content\activities\ContentCreated::instance()
->about($contentSource)->save();
Yii::$app->live->send(new \humhub\modules\content\live\NewContent([
'sguid' => ($this->container instanceof Space) ? $this->container->guid : null,
'uguid' => ($this->container instanceof User) ? $this->container->guid : null,
'originator' => $this->user->guid,
'contentContainerId' => $this->container->contentContainerRecord->id,
'visibility' => $this->visibility,
'contentId' => $this->id
]));
}
}
return parent::afterSave($insert, $changedAttributes);
}
/**
* #inheritdoc
*/
public function afterDelete()
{
// Try delete the underlying object (Post, Question, Task, ...)
$this->resetPolymorphicRelation();
if ($this->getPolymorphicRelation() !== null) {
$this->getPolymorphicRelation()->delete();
}
parent::afterDelete();
}
/**
* Returns the visibility of the content object
*
* #return Integer
*/
public function getVisibility()
{
return $this->visibility;
}
/**
* Checks if the content visiblity is set to public.
*
* #return boolean
*/
public function isPublic()
{
return $this->visibility == self::VISIBILITY_PUBLIC;
}
/**
* Checks if the content visiblity is set to private.
*
* #return boolean
*/
public function isPrivate()
{
return $this->visibility == self::VISIBILITY_PRIVATE;
}
/**
* Checks if the content object is pinned
*
* #return Boolean
*/
public function isPinned()
{
return ($this->pinned);
}
/**
* Pins the content object
*/
public function pin()
{
$this->pinned = 1;
//This prevents the call of beforesave, and the setting of update_at
$this->updateAttributes(['pinned']);
}
/**
* Unpins the content object
*/
public function unpin()
{
$this->pinned = 0;
$this->updateAttributes(['pinned']);
}
/**
* Checks if the user can pin this content.
* This is only allowed for workspace owner.
*
* #return boolean
*/
public function canPin()
{
if ($this->isArchived()) {
return false;
}
return $this->getContainer()->permissionManager->can(new ManageContent());
}
/**
* Creates a list of pinned content objects of the wall
*
* #return Int
*/
public function countPinnedItems()
{
return Content::find()->where(['content.contentcontainer_id' => $this->contentcontainer_id, 'content.pinned' => 1])->count();
}
/**
* Checks if current content object is archived
*
* #return boolean
*/
public function isArchived()
{
return $this->archived || ($this->getContainer() !== null && $this->getContainer()->isArchived());
}
/**
* Checks if the current user can archive this content.
* The content owner and the workspace admin can archive contents.
*
* #return boolean
*/
public function canArchive()
{
// Disabled on user profiles, there is no stream filter available yet.
if ($this->getContainer() instanceof User) {
return false;
}
return $this->getContainer()->permissionManager->can(new ManageContent());
}
/**
* Archives the content object
*/
public function archive()
{
if ($this->canArchive()) {
if ($this->isPinned()) {
$this->unpin();
}
$this->archived = 1;
if (!$this->save()) {
throw new Exception("Could not archive content!" . print_r($this->getErrors(), 1));
}
}
}
/**
* Unarchives the content object
*/
public function unarchive()
{
if ($this->canArchive()) {
$this->archived = 0;
$this->save();
}
}
/**
* Returns the url of this content.
*
* By default is returns the url of the wall entry.
*
* Optionally it's possible to create an own getUrl method in the underlying
* HActiveRecordContent (e.g. Post) to overwrite this behavior.
* e.g. in case there is no wall entry available for this content.
*
* #since 0.11.1
*/
public function getUrl()
{
if (method_exists($this->getPolymorphicRelation(), 'getUrl')) {
return $this->getPolymorphicRelation()->getUrl();
}
return Url::toRoute(['/content/perma', 'id' => $this->id]);
}
/**
* Sets container (e.g. space or user record) for this content.
*
* #param ContentContainerActiveRecord $container
* #throws Exception
*/
public function setContainer(ContentContainerActiveRecord $container)
{
$this->contentcontainer_id = $container->contentContainerRecord->id;
$this->_container = $container;
}
/**
* Returns the content container (e.g. space or user record) of this content
*
* #return ContentContainerActiveRecord
* #throws Exception
*/
public function getContainer()
{
if ($this->_container != null) {
return $this->_container;
}
if ($this->contentContainer !== null) {
$this->_container = $this->contentContainer->getPolymorphicRelation();
}
return $this->_container;
}
/**
* Relation to ContentContainer model
* Note: this is not a Space or User instance!
*
* #since 1.1
* #return \yii\db\ActiveQuery
*/
public function getContentContainer()
{
return $this->hasOne(ContentContainer::className(), ['id' => 'contentcontainer_id']);
}
/**
* Checks if the given user can edit this content.
*
* A user can edit a content if one of the following conditions are met:
*
* - User is the owner of the content
* - User is system administrator and the content module setting `adminCanEditAllContent` is set to true (default)
* - The user is granted the managePermission set by the model record class
* - The user meets the additional condition implemented by the model records class own `canEdit()` function.
*
* #since 1.1
* #param User $user
* #return bool can edit this content
*/
public function canEdit($user = null)
{
if (Yii::$app->user->isGuest) {
return false;
}
if ($user === null) {
$user = Yii::$app->user->getIdentity();
}
// Only owner can edit his content
if ($user !== null && $this->created_by == $user->id) {
return true;
}
// Global Admin can edit/delete arbitrarily content
if (Yii::$app->getModule('content')->adminCanEditAllContent && $user->isSystemAdmin()) {
return true;
}
/* #var $model ContentActiveRecord */
$model = $this->getPolymorphicRelation();
// Check additional manage permission for the given container
if ($model->hasManagePermission() && $this->getContainer() && $this->getContainer()->getPermissionManager($user)->can($model->getManagePermission())) {
return true;
}
// Check if underlying models canEdit implementation
// ToDo: Implement this as interface
if (method_exists($model, 'canEdit') && $model->canEdit($user)) {
return true;
}
return false;
}
/**
* Checks the given $permission of the current user in the contents content container.
* This is short for `$this->getContainer()->getPermissionManager()->can()`.
*
* #param $permission
* #param array $params
* #param bool $allowCaching
* #see PermissionManager::can()
* #since 1.2.1
* #return bool
*/
public function can($permission, $params = [], $allowCaching = true)
{
return $this->getContainer()->getPermissionManager()->can($permission, $params, $allowCaching);
}
/**
* Checks if user can view this content.
*
* #since 1.1
* #param User $user
* #return boolean can view this content
*/
public function canView($user = null)
{
if (!$user && !Yii::$app->user->isGuest) {
$user = Yii::$app->user->getIdentity();
}
// Check Guest Visibility
if (!$user) {
return $this->checkGuestAccess();
}
// Public visible content
if ($this->isPublic()) {
return true;
}
// Check system admin can see all content module configuration
if ($user->isSystemAdmin() && Yii::$app->getModule('content')->adminCanViewAllContent) {
return true;
}
if ($this->isPrivate() && $this->getContainer()->canAccessPrivateContent($user)) {
return true;
}
return false;
}
/**
* Determines if a guest user is able to read this content.
* This is the case if all of the following conditions are met:
*
* - The content is public
* - The `auth.allowGuestAccess` module setting is enabled
* - The space or profile visibility is set to VISIBILITY_ALL
*
* #return bool
*/
public function checkGuestAccess()
{
if(!$this->isPublic() || !Yii::$app->getModule('user')->settings->get('auth.allowGuestAccess')) {
return false;
}
// Check container visibility for guests
return ($this->container instanceof Space && $this->container->visibility == Space::VISIBILITY_ALL)
|| ($this->container instanceof User && $this->container->visibility == User::VISIBILITY_ALL);
}
/**
* Updates the wall/stream sorting time of this content for "updated at" sorting
*/
public function updateStreamSortTime()
{
$this->updateAttributes(['stream_sort_date' => new \yii\db\Expression('NOW()')]);
}
}
As you can see the first class extends the second one , I'm rather new to php but i'm guessing that's the issue
UPDATE : I tried using the "use class as " and still the same error , I also tried changing the name of the first class to Content1 just to check and still the same .
The problem occours in the second class from the error report
This is a recurring error in a few places in the server I figure I will solve it here and the rest will be the same ,
Many Thanks!
You included file with exacly same class name, so you have 2 class declarations with name Content in this file. Easiest ways to fix it:
Change one of class name
Start using Yii2 autloader, if you need to include something - there's something wrong in your code. You should be able to access
class only by using namespace. There's small conditions you have to
met:
Each class must be under a namespace (e.g. foo\bar\MyClass)
Each class must be saved in an individual file whose path is determined by the following algorithm:
// $className is a fully qualified class name without the leading backslash
$classFile = Yii::getAlias('#' . str_replace('\\', '/', $className) . '.php');
More about Yii2 autloading: Class Autoloading
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
WAMP Stack PHP “Fatal error: Class ‘SoapClient’ not found”
I downloaded a library from this site library and when I tried to use it's examples it says : "Fatal error: Class 'SoapClient' not found in C:\wamp\www\Amazon-ECS\Exeu-Amazon-ECS-PHP-Library-9030053\lib\AmazonECS.class.php on line 231" How should I able to fix this?
<?php
/**
* Amazon ECS Class
* http://www.amazon.com
* =====================
*
* This class fetchs productinformation via the Product Advertising API by Amazon (formerly ECS).
* It supports three basic operations: ItemSearch, ItemLookup and BrowseNodeLookup.
* These operations could be expanded with extra prarmeters to specialize the query.
*
* Requirement is the PHP extension SOAP.
*
* #package AmazonECS
* #license http://www.gnu.org/licenses/gpl.txt GPL
* #version 1.3.4-DEV
* #author Exeu <exeu65#googlemail.com>
* #contributor Julien Chaumond <chaumond#gmail.com>
* #link http://github.com/Exeu/Amazon-ECS-PHP-Library/wiki Wiki
* #link http://github.com/Exeu/Amazon-ECS-PHP-Library Source
*/
class AmazonECS
{
const RETURN_TYPE_ARRAY = 1;
const RETURN_TYPE_OBJECT = 2;
/**
* Baseconfigurationstorage
*
* #var array
*/
private $requestConfig = array(
'requestDelay' => false
);
/**
* Responseconfigurationstorage
*
* #var array
*/
private $responseConfig = array(
'returnType' => self::RETURN_TYPE_OBJECT,
'responseGroup' => 'Small',
'optionalParameters' => array()
);
/**
* All possible locations
*
* #var array
*/
private $possibleLocations = array('de', 'com', 'co.uk', 'ca', 'fr', 'co.jp', 'it', 'cn', 'es');
/**
* The WSDL File
*
* #var string
*/
protected $webserviceWsdl = 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl';
/**
* The SOAP Endpoint
*
* #var string
*/
protected $webserviceEndpoint = 'https://webservices.amazon.%%COUNTRY%%/onca/soap?Service=AWSECommerceService';
/**
* #param string $accessKey
* #param string $secretKey
* #param string $country
* #param string $associateTag
*/
public function __construct($accessKey, $secretKey, $country, $associateTag)
{
if (empty($accessKey) || empty($secretKey))
{
throw new Exception('No Access Key or Secret Key has been set');
}
$this->requestConfig['accessKey'] = $accessKey;
$this->requestConfig['secretKey'] = $secretKey;
$this->associateTag($associateTag);
$this->country($country);
}
/**
* execute search
*
* #param string $pattern
*
* #return array|object return type depends on setting
*
* #see returnType()
*/
public function search($pattern, $nodeId = null)
{
if (false === isset($this->requestConfig['category']))
{
throw new Exception('No Category given: Please set it up before');
}
$browseNode = array();
if (null !== $nodeId && true === $this->validateNodeId($nodeId))
{
$browseNode = array('BrowseNode' => $nodeId);
}
$params = $this->buildRequestParams('ItemSearch', array_merge(
array(
'Keywords' => $pattern,
'SearchIndex' => $this->requestConfig['category']
),
$browseNode
));
return $this->returnData(
$this->performSoapRequest("ItemSearch", $params)
);
}
/**
* execute ItemLookup request
*
* #param string $asin
*
* #return array|object return type depends on setting
*
* #see returnType()
*/
public function lookup($asin)
{
$params = $this->buildRequestParams('ItemLookup', array(
'ItemId' => $asin,
));
return $this->returnData(
$this->performSoapRequest("ItemLookup", $params)
);
}
/**
* Implementation of BrowseNodeLookup
* This allows to fetch information about nodes (children anchestors, etc.)
*
* #param integer $nodeId
*/
public function browseNodeLookup($nodeId)
{
$this->validateNodeId($nodeId);
$params = $this->buildRequestParams('BrowseNodeLookup', array(
'BrowseNodeId' => $nodeId
));
return $this->returnData(
$this->performSoapRequest("BrowseNodeLookup", $params)
);
}
/**
* Implementation of SimilarityLookup
* This allows to fetch information about product related to the parameter product
*
* #param string $asin
*/
public function similarityLookup($asin)
{
$params = $this->buildRequestParams('SimilarityLookup', array(
'ItemId' => $asin
));
return $this->returnData(
$this->performSoapRequest("SimilarityLookup", $params)
);
}
/**
* Builds the request parameters
*
* #param string $function
* #param array $params
*
* #return array
*/
protected function buildRequestParams($function, array $params)
{
$associateTag = array();
if(false === empty($this->requestConfig['associateTag']))
{
$associateTag = array('AssociateTag' => $this->requestConfig['associateTag']);
}
return array_merge(
$associateTag,
array(
'AWSAccessKeyId' => $this->requestConfig['accessKey'],
'Request' => array_merge(
array('Operation' => $function),
$params,
$this->responseConfig['optionalParameters'],
array('ResponseGroup' => $this->prepareResponseGroup())
)));
}
/**
* Prepares the responsegroups and returns them as array
*
* #return array|prepared responsegroups
*/
protected function prepareResponseGroup()
{
if (false === strstr($this->responseConfig['responseGroup'], ','))
return $this->responseConfig['responseGroup'];
return explode(',', $this->responseConfig['responseGroup']);
}
/**
* #param string $function Name of the function which should be called
* #param array $params Requestparameters 'ParameterName' => 'ParameterValue'
*
* #return array The response as an array with stdClass objects
*/
protected function performSoapRequest($function, $params)
{
if (true === $this->requestConfig['requestDelay']) {
sleep(1);
}
$soapClient = new SoapClient(
$this->webserviceWsdl,
array('exceptions' => 1)
);
$soapClient->__setLocation(str_replace(
'%%COUNTRY%%',
$this->responseConfig['country'],
$this->webserviceEndpoint
));
$soapClient->__setSoapHeaders($this->buildSoapHeader($function));
return $soapClient->__soapCall($function, array($params));
}
/**
* Provides some necessary soap headers
*
* #param string $function
*
* #return array Each element is a concrete SoapHeader object
*/
protected function buildSoapHeader($function)
{
$timeStamp = $this->getTimestamp();
$signature = $this->buildSignature($function . $timeStamp);
return array(
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'AWSAccessKeyId',
$this->requestConfig['accessKey']
),
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Timestamp',
$timeStamp
),
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Signature',
$signature
)
);
}
/**
* provides current gm date
*
* primary needed for the signature
*
* #return string
*/
final protected function getTimestamp()
{
return gmdate("Y-m-d\TH:i:s\Z");
}
/**
* provides the signature
*
* #return string
*/
final protected function buildSignature($request)
{
return base64_encode(hash_hmac("sha256", $request, $this->requestConfig['secretKey'], true));
}
/**
* Basic validation of the nodeId
*
* #param integer $nodeId
*
* #return boolean
*/
final protected function validateNodeId($nodeId)
{
if (false === is_numeric($nodeId) || $nodeId <= 0)
{
throw new InvalidArgumentException(sprintf('Node has to be a positive Integer.'));
}
return true;
}
/**
* Returns the response either as Array or Array/Object
*
* #param object $object
*
* #return mixed
*/
protected function returnData($object)
{
switch ($this->responseConfig['returnType'])
{
case self::RETURN_TYPE_OBJECT:
return $object;
break;
case self::RETURN_TYPE_ARRAY:
return $this->objectToArray($object);
break;
default:
throw new InvalidArgumentException(sprintf(
"Unknwon return type %s", $this->responseConfig['returnType']
));
break;
}
}
/**
* Transforms the responseobject to an array
*
* #param object $object
*
* #return array An arrayrepresentation of the given object
*/
protected function objectToArray($object)
{
$out = array();
foreach ($object as $key => $value)
{
switch (true)
{
case is_object($value):
$out[$key] = $this->objectToArray($value);
break;
case is_array($value):
$out[$key] = $this->objectToArray($value);
break;
default:
$out[$key] = $value;
break;
}
}
return $out;
}
/**
* set or get optional parameters
*
* if the argument params is null it will reutrn the current parameters,
* otherwise it will set the params and return itself.
*
* #param array $params the optional parameters
*
* #return array|AmazonECS depends on params argument
*/
public function optionalParameters($params = null)
{
if (null === $params)
{
return $this->responseConfig['optionalParameters'];
}
if (false === is_array($params))
{
throw new InvalidArgumentException(sprintf(
"%s is no valid parameter: Use an array with Key => Value Pairs", $params
));
}
$this->responseConfig['optionalParameters'] = $params;
return $this;
}
/**
* Set or get the country
*
* if the country argument is null it will return the current
* country, otherwise it will set the country and return itself.
*
* #param string|null $country
*
* #return string|AmazonECS depends on country argument
*/
public function country($country = null)
{
if (null === $country)
{
return $this->responseConfig['country'];
}
if (false === in_array(strtolower($country), $this->possibleLocations))
{
throw new InvalidArgumentException(sprintf(
"Invalid Country-Code: %s! Possible Country-Codes: %s",
$country,
implode(', ', $this->possibleLocations)
));
}
$this->responseConfig['country'] = strtolower($country);
return $this;
}
/**
* Setting/Getting the amazon category
*
* #param string $category
*
* #return string|AmazonECS depends on category argument
*/
public function category($category = null)
{
if (null === $category)
{
return isset($this->requestConfig['category']) ? $this->requestConfig['category'] : null;
}
$this->requestConfig['category'] = $category;
return $this;
}
/**
* Setting/Getting the responsegroup
*
* #param string $responseGroup Comma separated groups
*
* #return string|AmazonECS depends on responseGroup argument
*/
public function responseGroup($responseGroup = null)
{
if (null === $responseGroup)
{
return $this->responseConfig['responseGroup'];
}
$this->responseConfig['responseGroup'] = $responseGroup;
return $this;
}
/**
* Setting/Getting the returntype
* It can be an object or an array
*
* #param integer $type Use the constants RETURN_TYPE_ARRAY or RETURN_TYPE_OBJECT
*
* #return integer|AmazonECS depends on type argument
*/
public function returnType($type = null)
{
if (null === $type)
{
return $this->responseConfig['returnType'];
}
$this->responseConfig['returnType'] = $type;
return $this;
}
/**
* Setter/Getter of the AssociateTag.
* This could be used for late bindings of this attribute
*
* #param string $associateTag
*
* #return string|AmazonECS depends on associateTag argument
*/
public function associateTag($associateTag = null)
{
if (null === $associateTag)
{
return $this->requestConfig['associateTag'];
}
$this->requestConfig['associateTag'] = $associateTag;
return $this;
}
/**
* #deprecated use returnType() instead
*/
public function setReturnType($type)
{
return $this->returnType($type);
}
/**
* Setting the resultpage to a specified value.
* Allows to browse resultsets which have more than one page.
*
* #param integer $page
*
* #return AmazonECS
*/
public function page($page)
{
if (false === is_numeric($page) || $page <= 0)
{
throw new InvalidArgumentException(sprintf(
'%s is an invalid page value. It has to be numeric and positive',
$page
));
}
$this->responseConfig['optionalParameters'] = array_merge(
$this->responseConfig['optionalParameters'],
array("ItemPage" => $page)
);
return $this;
}
/**
* Enables or disables the request delay.
* If it is enabled (true) every request is delayed one second to get rid of the api request limit.
*
* Reasons for this you can read on this site:
* https://affiliate-program.amazon.com/gp/advertising/api/detail/faq.html
*
* By default the requestdelay is disabled
*
* #param boolean $enable true = enabled, false = disabled
*
* #return boolean|AmazonECS depends on enable argument
*/
public function requestDelay($enable = null)
{
if (false === is_null($enable) && true === is_bool($enable))
{
$this->requestConfig['requestDelay'] = $enable;
return $this;
}
return $this->requestConfig['requestDelay'];
}
}
The error appears to be caused by the version of PHP that you have does not have the SOAP extension enabled.
To resolve this simply start wamp, click on the wamp system tray icon. Within this screen select PHP then PHP extensions. This will display a list of extensions. Ensure that php_soap is ticked.
If you intend to access soap servers that use HTTPs then you will also ensure php_openssl is ticked.
I'm trying to use PHPExcel with Codeigniter, but I'm running into issues. I extracted the class files from the PHPExcel download and placed them in the 'application/libraries' folder for Codeigniter.
However when I try to load the necessary libraries:
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');
I get the error "Non-existent class: IOFactory".
I've checked that iofactory file is in the PHPExcel file, and it is there. Am I supposed to have the classes located somewhere else? What else am I doing wrong?
Try something like this:
$this->load->library('PHPExcel');
$xl_obj = new PHPExcel();
$reader = PHPExcel_IOFactory::createReader('Excel5');
$reader->setReadDataOnly(true);
$file = $reader->load('/PATH/FILENAME.EXT');
It works!
My method for this was to put the PHPExcel folder in /application/libraries folder, then create a wrapper file in the libraries folder;
PHPExcel.php
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2011 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* #category PHPExcel
* #package PHPExcel
* #copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
* #license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* #version 1.7.6, 2011-02-27
*/
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* PHPExcel
*
* #category PHPExcel
* #package PHPExcel
* #copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel
{
/**
* Document properties
*
* #var PHPExcel_DocumentProperties
*/
private $_properties;
/**
* Document security
*
* #var PHPExcel_DocumentSecurity
*/
private $_security;
/**
* Collection of Worksheet objects
*
* #var PHPExcel_Worksheet[]
*/
private $_workSheetCollection = array();
/**
* Active sheet index
*
* #var int
*/
private $_activeSheetIndex = 0;
/**
* Named ranges
*
* #var PHPExcel_NamedRange[]
*/
private $_namedRanges = array();
/**
* CellXf supervisor
*
* #var PHPExcel_Style
*/
private $_cellXfSupervisor;
/**
* CellXf collection
*
* #var PHPExcel_Style[]
*/
private $_cellXfCollection = array();
/**
* CellStyleXf collection
*
* #var PHPExcel_Style[]
*/
private $_cellStyleXfCollection = array();
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct()
{
// Initialise worksheet collection and add one worksheet
$this->_workSheetCollection = array();
$this->_workSheetCollection[] = new PHPExcel_Worksheet($this);
$this->_activeSheetIndex = 0;
// Create document properties
$this->_properties = new PHPExcel_DocumentProperties();
// Create document security
$this->_security = new PHPExcel_DocumentSecurity();
// Set named ranges
$this->_namedRanges = array();
// Create the cellXf supervisor
$this->_cellXfSupervisor = new PHPExcel_Style(true);
$this->_cellXfSupervisor->bindParent($this);
// Create the default style
$this->addCellXf(new PHPExcel_Style);
$this->addCellStyleXf(new PHPExcel_Style);
}
public function disconnectWorksheets() {
foreach($this->_workSheetCollection as $k => &$worksheet) {
$worksheet->disconnectCells();
$this->_workSheetCollection[$k] = null;
}
unset($worksheet);
$this->_workSheetCollection = array();
}
/**
* Get properties
*
* #return PHPExcel_DocumentProperties
*/
public function getProperties()
{
return $this->_properties;
}
/**
* Set properties
*
* #param PHPExcel_DocumentProperties $pValue
*/
public function setProperties(PHPExcel_DocumentProperties $pValue)
{
$this->_properties = $pValue;
}
/**
* Get security
*
* #return PHPExcel_DocumentSecurity
*/
public function getSecurity()
{
return $this->_security;
}
/**
* Set security
*
* #param PHPExcel_DocumentSecurity $pValue
*/
public function setSecurity(PHPExcel_DocumentSecurity $pValue)
{
$this->_security = $pValue;
}
/**
* Get active sheet
*
* #return PHPExcel_Worksheet
*/
public function getActiveSheet()
{
return $this->_workSheetCollection[$this->_activeSheetIndex];
}
/**
* Create sheet and add it to this workbook
*
* #return PHPExcel_Worksheet
*/
public function createSheet($iSheetIndex = null)
{
$newSheet = new PHPExcel_Worksheet($this);
$this->addSheet($newSheet, $iSheetIndex);
return $newSheet;
}
/**
* Add sheet
*
* #param PHPExcel_Worksheet $pSheet
* #param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
* #return PHPExcel_Worksheet
* #throws Exception
*/
public function addSheet(PHPExcel_Worksheet $pSheet = null, $iSheetIndex = null)
{
if(is_null($iSheetIndex))
{
$this->_workSheetCollection[] = $pSheet;
}
else
{
// Insert the sheet at the requested index
array_splice(
$this->_workSheetCollection,
$iSheetIndex,
0,
array($pSheet)
);
// Adjust active sheet index if necessary
if ($this->_activeSheetIndex >= $iSheetIndex) {
++$this->_activeSheetIndex;
}
}
return $pSheet;
}
/**
* Remove sheet by index
*
* #param int $pIndex Active sheet index
* #throws Exception
*/
public function removeSheetByIndex($pIndex = 0)
{
if ($pIndex > count($this->_workSheetCollection) - 1) {
throw new Exception("Sheet index is out of bounds.");
} else {
array_splice($this->_workSheetCollection, $pIndex, 1);
}
}
/**
* Get sheet by index
*
* #param int $pIndex Sheet index
* #return PHPExcel_Worksheet
* #throws Exception
*/
public function getSheet($pIndex = 0)
{
if ($pIndex > count($this->_workSheetCollection) - 1) {
throw new Exception("Sheet index is out of bounds.");
} else {
return $this->_workSheetCollection[$pIndex];
}
}
/**
* Get all sheets
*
* #return PHPExcel_Worksheet[]
*/
public function getAllSheets()
{
return $this->_workSheetCollection;
}
/**
* Get sheet by name
*
* #param string $pName Sheet name
* #return PHPExcel_Worksheet
* #throws Exception
*/
public function getSheetByName($pName = '')
{
$worksheetCount = count($this->_workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) {
if ($this->_workSheetCollection[$i]->getTitle() == $pName) {
return $this->_workSheetCollection[$i];
}
}
return null;
}
/**
* Get index for sheet
*
* #param PHPExcel_Worksheet $pSheet
* #return Sheet index
* #throws Exception
*/
public function getIndex(PHPExcel_Worksheet $pSheet)
{
foreach ($this->_workSheetCollection as $key => $value) {
if ($value->getHashCode() == $pSheet->getHashCode()) {
return $key;
}
}
}
/**
* Set index for sheet by sheet name.
*
* #param string $sheetName Sheet name to modify index for
* #param int $newIndex New index for the sheet
* #return New sheet index
* #throws Exception
*/
public function setIndexByName($sheetName, $newIndex)
{
$oldIndex = $this->getIndex($this->getSheetByName($sheetName));
$pSheet = array_splice(
$this->_workSheetCollection,
$oldIndex,
1
);
array_splice(
$this->_workSheetCollection,
$newIndex,
0,
$pSheet
);
return $newIndex;
}
/**
* Get sheet count
*
* #return int
*/
public function getSheetCount()
{
return count($this->_workSheetCollection);
}
/**
* Get active sheet index
*
* #return int Active sheet index
*/
public function getActiveSheetIndex()
{
return $this->_activeSheetIndex;
}
/**
* Set active sheet index
*
* #param int $pIndex Active sheet index
* #throws Exception
* #return PHPExcel_Worksheet
*/
public function setActiveSheetIndex($pIndex = 0)
{
if ($pIndex > count($this->_workSheetCollection) - 1) {
throw new Exception("Active sheet index is out of bounds.");
} else {
$this->_activeSheetIndex = $pIndex;
}
return $this->getActiveSheet();
}
/**
* Set active sheet index by name
*
* #param string $pValue Sheet title
* #return PHPExcel_Worksheet
* #throws Exception
*/
public function setActiveSheetIndexByName($pValue = '')
{
if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) {
$this->setActiveSheetIndex($worksheet->getParent()->getIndex($worksheet));
return $worksheet;
}
throw new Exception('Workbook does not contain sheet:' . $pValue);
}
/**
* Get sheet names
*
* #return string[]
*/
public function getSheetNames()
{
$returnValue = array();
$worksheetCount = $this->getSheetCount();
for ($i = 0; $i < $worksheetCount; ++$i) {
array_push($returnValue, $this->getSheet($i)->getTitle());
}
return $returnValue;
}
/**
* Add external sheet
*
* #param PHPExcel_Worksheet $pSheet External sheet to add
* #param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
* #throws Exception
* #return PHPExcel_Worksheet
*/
public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) {
if (!is_null($this->getSheetByName($pSheet->getTitle()))) {
throw new Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.");
}
// count how many cellXfs there are in this workbook currently, we will need this below
$countCellXfs = count($this->_cellXfCollection);
// copy all the shared cellXfs from the external workbook and append them to the current
foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) {
$this->addCellXf(clone $cellXf);
}
// move sheet to this workbook
$pSheet->rebindParent($this);
// update the cellXfs
foreach ($pSheet->getCellCollection(false) as $cellID) {
$cell = $pSheet->getCell($cellID);
$cell->setXfIndex( $cell->getXfIndex() + $countCellXfs );
}
return $this->addSheet($pSheet, $iSheetIndex);
}
/**
* Get named ranges
*
* #return PHPExcel_NamedRange[]
*/
public function getNamedRanges() {
return $this->_namedRanges;
}
/**
* Add named range
*
* #param PHPExcel_NamedRange $namedRange
* #return PHPExcel
*/
public function addNamedRange(PHPExcel_NamedRange $namedRange) {
if ($namedRange->getScope() == null) {
// global scope
$this->_namedRanges[$namedRange->getName()] = $namedRange;
} else {
// local scope
$this->_namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange;
}
return true;
}
/**
* Get named range
*
* #param string $namedRange
* #param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope
* #return PHPExcel_NamedRange|null
*/
public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) {
$returnValue = null;
if ($namedRange != '' && !is_null($namedRange)) {
// first look for global defined name
if (isset($this->_namedRanges[$namedRange])) {
$returnValue = $this->_namedRanges[$namedRange];
}
// then look for local defined name (has priority over global defined name if both names exist)
if (!is_null($pSheet) && isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
$returnValue = $this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange];
}
}
return $returnValue;
}
/**
* Remove named range
*
* #param string $namedRange
* #param PHPExcel_Worksheet|null $pSheet. Scope. Use null for global scope.
* #return PHPExcel
*/
public function removeNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) {
if (is_null($pSheet)) {
if (isset($this->_namedRanges[$namedRange])) {
unset($this->_namedRanges[$namedRange]);
}
} else {
if (isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
unset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange]);
}
}
return $this;
}
/**
* Get worksheet iterator
*
* #return PHPExcel_WorksheetIterator
*/
public function getWorksheetIterator() {
return new PHPExcel_WorksheetIterator($this);
}
/**
* Copy workbook (!= clone!)
*
* #return PHPExcel
*/
public function copy() {
$copied = clone $this;
$worksheetCount = count($this->_workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) {
$this->_workSheetCollection[$i] = $this->_workSheetCollection[$i]->copy();
$this->_workSheetCollection[$i]->rebindParent($this);
}
return $copied;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone() {
foreach($this as $key => $val) {
if (is_object($val) || (is_array($val))) {
$this->{$key} = unserialize(serialize($val));
}
}
}
/**
* Get the workbook collection of cellXfs
*
* #return PHPExcel_Style[]
*/
public function getCellXfCollection()
{
return $this->_cellXfCollection;
}
/**
* Get cellXf by index
*
* #param int $index
* #return PHPExcel_Style
*/
public function getCellXfByIndex($pIndex = 0)
{
return $this->_cellXfCollection[$pIndex];
}
/**
* Get cellXf by hash code
*
* #param string $pValue
* #return PHPExcel_Style|false
*/
public function getCellXfByHashCode($pValue = '')
{
foreach ($this->_cellXfCollection as $cellXf) {
if ($cellXf->getHashCode() == $pValue) {
return $cellXf;
}
}
return false;
}
/**
* Get default style
*
* #return PHPExcel_Style
* #throws Exception
*/
public function getDefaultStyle()
{
if (isset($this->_cellXfCollection[0])) {
return $this->_cellXfCollection[0];
}
throw new Exception('No default style found for this workbook');
}
/**
* Add a cellXf to the workbook
*
* #param PHPExcel_Style
*/
public function addCellXf(PHPExcel_Style $style)
{
$this->_cellXfCollection[] = $style;
$style->setIndex(count($this->_cellXfCollection) - 1);
}
/**
* Remove cellXf by index. It is ensured that all cells get their xf index updated.
*
* #param int $pIndex Index to cellXf
* #throws Exception
*/
public function removeCellXfByIndex($pIndex = 0)
{
if ($pIndex > count($this->_cellXfCollection) - 1) {
throw new Exception("CellXf index is out of bounds.");
} else {
// first remove the cellXf
array_splice($this->_cellXfCollection, $pIndex, 1);
// then update cellXf indexes for cells
foreach ($this->_workSheetCollection as $worksheet) {
foreach ($worksheet->getCellCollection(false) as $cellID) {
$cell = $worksheet->getCell($cellID);
$xfIndex = $cell->getXfIndex();
if ($xfIndex > $pIndex ) {
// decrease xf index by 1
$cell->setXfIndex($xfIndex - 1);
} else if ($xfIndex == $pIndex) {
// set to default xf index 0
$cell->setXfIndex(0);
}
}
}
}
}
/**
* Get the cellXf supervisor
*
* #return PHPExcel_Style
*/
public function getCellXfSupervisor()
{
return $this->_cellXfSupervisor;
}
/**
* Get the workbook collection of cellStyleXfs
*
* #return PHPExcel_Style[]
*/
public function getCellStyleXfCollection()
{
return $this->_cellStyleXfCollection;
}
/**
* Get cellStyleXf by index
*
* #param int $pIndex
* #return PHPExcel_Style
*/
public function getCellStyleXfByIndex($pIndex = 0)
{
return $this->_cellStyleXfCollection[$pIndex];
}
/**
* Get cellStyleXf by hash code
*
* #param string $pValue
* #return PHPExcel_Style|false
*/
public function getCellStyleXfByHashCode($pValue = '')
{
foreach ($this->_cellXfStyleCollection as $cellStyleXf) {
if ($cellStyleXf->getHashCode() == $pValue) {
return $cellStyleXf;
}
}
return false;
}
/**
* Add a cellStyleXf to the workbook
*
* #param PHPExcel_Style $pStyle
*/
public function addCellStyleXf(PHPExcel_Style $pStyle)
{
$this->_cellStyleXfCollection[] = $pStyle;
$pStyle->setIndex(count($this->_cellStyleXfCollection) - 1);
}
/**
* Remove cellStyleXf by index
*
* #param int $pIndex
* #throws Exception
*/
public function removeCellStyleXfByIndex($pIndex = 0)
{
if ($pIndex > count($this->_cellStyleXfCollection) - 1) {
throw new Exception("CellStyleXf index is out of bounds.");
} else {
array_splice($this->_cellStyleXfCollection, $pIndex, 1);
}
}
/**
* Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
* and columns in the workbook
*/
public function garbageCollect()
{
// how many references are there to each cellXf ?
$countReferencesCellXf = array();
foreach ($this->_cellXfCollection as $index => $cellXf) {
$countReferencesCellXf[$index] = 0;
}
foreach ($this->getWorksheetIterator() as $sheet) {
// from cells
foreach ($sheet->getCellCollection(false) as $cellID) {
$cell = $sheet->getCell($cellID);
++$countReferencesCellXf[$cell->getXfIndex()];
}
// from row dimensions
foreach ($sheet->getRowDimensions() as $rowDimension) {
if ($rowDimension->getXfIndex() !== null) {
++$countReferencesCellXf[$rowDimension->getXfIndex()];
}
}
// from column dimensions
foreach ($sheet->getColumnDimensions() as $columnDimension) {
++$countReferencesCellXf[$columnDimension->getXfIndex()];
}
}
// remove cellXfs without references and create mapping so we can update xfIndex
// for all cells and columns
$countNeededCellXfs = 0;
foreach ($this->_cellXfCollection as $index => $cellXf) {
if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
++$countNeededCellXfs;
} else {
unset($this->_cellXfCollection[$index]);
}
$map[$index] = $countNeededCellXfs - 1;
}
$this->_cellXfCollection = array_values($this->_cellXfCollection);
// update the index for all cellXfs
foreach ($this->_cellXfCollection as $i => $cellXf) {
$cellXf->setIndex($i);
}
// make sure there is always at least one cellXf (there should be)
if (count($this->_cellXfCollection) == 0) {
$this->_cellXfCollection[] = new PHPExcel_Style();
}
// update the xfIndex for all cells, row dimensions, column dimensions
foreach ($this->getWorksheetIterator() as $sheet) {
// for all cells
foreach ($sheet->getCellCollection(false) as $cellID) {
$cell = $sheet->getCell($cellID);
$cell->setXfIndex( $map[$cell->getXfIndex()] );
}
// for all row dimensions
foreach ($sheet->getRowDimensions() as $rowDimension) {
if ($rowDimension->getXfIndex() !== null) {
$rowDimension->setXfIndex( $map[$rowDimension->getXfIndex()] );
}
}
// for all column dimensions
foreach ($sheet->getColumnDimensions() as $columnDimension) {
$columnDimension->setXfIndex( $map[$columnDimension->getXfIndex()] );
}
}
// also do garbage collection for all the sheets
foreach ($this->getWorksheetIterator() as $sheet) {
$sheet->garbageCollect();
}
}
}
Then in my contoller;
$this->load->library('PHPExcel');
// Create new PHPExcel object
$excel_obj = new PHPExcel();
// Set properties
$excel_obj->getProperties()->setCreator($params['author'])
->setLastModifiedBy($params['author'])
->setTitle($params['title'])
->setSubject($params['subject'])
->setDescription($params['description']);