sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function _getContents($path) {
$contents = '';
if (($fp = $this->_fopen($path))) {
while (!feof($fp)) {
$contents .= fread($fp, 8192);
}
$this->_fclose($fp, $path);
return $contents;
}
return false;
}
|
Get file contents
@param string $path file path
@return string|false
@author Dmitry (dio) Levashov
|
entailment
|
protected function _filePutContents($path, $content) {
$res = false;
if ($this->tmp) {
$local = $this->getTempFile();
if (@file_put_contents($local, $content, LOCK_EX) !== false
&& ($fp = @fopen($local, 'rb'))) {
clearstatcache();
$res = ftp_fput($this->connect, $path, $fp, $this->ftpMode($path));
@fclose($fp);
}
file_exists($local) && @unlink($local);
}
return $res;
}
|
Write a string to a file
@param string $path file path
@param string $content new file content
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _extract($path, $arc)
{
// get current directory
$cwd = getcwd();
$tmpDir = $this->tempDir();
if (!$tmpDir) {
return false;
}
$basename = $this->_basename($path);
$localPath = $tmpDir . DIRECTORY_SEPARATOR . $basename;
if (!ftp_get($this->connect, $localPath, $path, FTP_BINARY)) {
//cleanup
$this->deleteDir($tmpDir);
return false;
}
$remoteDirectory = dirname($path);
chdir($tmpDir);
$command = escapeshellcmd($arc['cmd'] . ' ' . $arc['argc'] . ' "' . $basename . '"');
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a file to write to
);
$process = proc_open($command, $descriptorspec, $pipes, $cwd);
if (is_resource($process)) {
fclose($pipes[0]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
unlink($basename);
$filesToProcess = elFinderVolumeFTP::listFilesInDirectory($tmpDir, true);
if(!$filesToProcess) {
$this->setError(elFinder::ERROR_EXTRACT_EXEC, $tmpDir." is not a directory");
$this->deleteDir($tmpDir); //cleanup
return false;
}
if (count($filesToProcess) > 1) {
// for several files - create new directory
// create unique name for directory
$name = basename($path);
if (preg_match('/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i', $name, $m)) {
$name = substr($name, 0, strlen($name) - strlen($m[0]));
}
$test = dirname($path) . DIRECTORY_SEPARATOR . $name;
if ($this->stat($test)) {
$name = $this->uniqueName(dirname($path), $name, '-', false);
}
$newPath = dirname($path) . DIRECTORY_SEPARATOR . $name;
$success = $this->_mkdir(dirname($path), $name);
foreach ($filesToProcess as $filename) {
if (!$success) {
break;
}
$targetPath = $newPath . DIRECTORY_SEPARATOR . $filename;
if (is_dir($filename)) {
$success = $this->_mkdir($newPath, $filename);
} else {
$success = ftp_put($this->connect, $targetPath, $filename, FTP_BINARY);
}
}
unset($filename);
} else {
$filename = $filesToProcess[0];
$newPath = $remoteDirectory . DIRECTORY_SEPARATOR . $filename;
$success = ftp_put($this->connect, $newPath, $filename, FTP_BINARY);
}
// return to initial directory
chdir($cwd);
//cleanup
if(!$this->deleteDir($tmpDir)) {
return false;
}
if (!$success) {
$this->setError(elFinder::ERROR_FTP_UPLOAD_FILE, $newPath);
return false;
}
$this->clearcache();
return $newPath;
}
|
Extract files from archive
@param string $path archive path
@param array $arc archiver command and arguments (same as in $this->archivers)
@return true
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _archive($dir, $files, $name, $arc)
{
// get current directory
$cwd = getcwd();
$tmpDir = $this->tempDir();
if (!$tmpDir) {
return false;
}
//download data
if (!$this->ftp_download_files($dir, $files, $tmpDir)) {
//cleanup
$this->deleteDir($tmpDir);
return false;
}
// go to the temporary directory
chdir($tmpDir);
// path to local copy of archive
$path = $tmpDir . DIRECTORY_SEPARATOR . $name;
$file_names_string = "";
foreach (scandir($tmpDir) as $filename) {
if ('.' == $filename) {
continue;
}
if ('..' == $filename) {
continue;
}
$file_names_string = $file_names_string . '"' . $filename . '" ';
}
$command = escapeshellcmd($arc['cmd'] . ' ' . $arc['argc'] . ' "' . $name . '" ' . $file_names_string);
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a file to write to
);
$process = proc_open($command, $descriptorspec, $pipes, $cwd);
if (is_resource($process)) {
fclose($pipes[0]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
$remoteArchiveFile = $dir . DIRECTORY_SEPARATOR . $name;
// upload archive
if (!ftp_put($this->connect, $remoteArchiveFile, $path, FTP_BINARY)) {
$this->setError(elFinder::ERROR_FTP_UPLOAD_FILE, $remoteArchiveFile);
$this->deleteDir($tmpDir); //cleanup
return false;
}
// return to initial work directory
chdir($cwd);
//cleanup
if(!$this->deleteDir($tmpDir)) {
return false;
}
return $remoteArchiveFile;
}
|
Create archive and return its path
@param string $dir target dir
@param array $files files names list
@param string $name archive name
@param array $arc archiver options
@return string|bool
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
private function tempDir()
{
$tempPath = tempnam($this->tmp, 'elFinder');
if (!$tempPath) {
$this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
return false;
}
$success = unlink($tempPath);
if (!$success) {
$this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
return false;
}
$success = mkdir($tempPath, 0700, true);
if (!$success) {
$this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
return false;
}
return $tempPath;
}
|
Create writable temporary directory and return path to it.
@return string path to the new temporary directory or false in case of error.
|
entailment
|
protected function ftp_scan_dir($remote_directory)
{
$buff = ftp_rawlist($this->connect, $remote_directory, true);
$next_folder = false;
$items = array();
foreach ($buff as $str) {
if ('' == $str) {
$next_folder = true;
continue;
}
if ($next_folder) {
$remote_directory = preg_replace('/\:/', '', $str);
$next_folder = false;
$item = array();
$item['path'] = $remote_directory;
$item['type'] = 'd'; // directory
$items[] = $item;
continue;
}
$info = preg_split("/\s+/", $str, 9);
$type = substr($info[0], 0, 1);
switch ($type) {
case 'l' : //omit symbolic links
case 'd' :
break;
default:
$remote_file_path = $remote_directory . DIRECTORY_SEPARATOR . $info[8];
$item = array();
$item['path'] = $remote_file_path;
$item['type'] = 'f'; // normal file
$items[] = $item;
}
}
return $items;
}
|
Gets in a single FTP request an array of absolute remote FTP paths of files and
folders in $remote_directory omitting symbolic links.
@param $remote_directory string remote FTP path to scan for file and folders recursively
@return array of elements each of which is an array of two elements:
<ul>
<li>$item['path'] - absolute remote FTP path</li>
<li>$item['type'] - either 'f' for file or 'd' for directory</li>
</ul>
|
entailment
|
private function ftp_download_files($remote_directory, array $files, $dest_local_directory)
{
$contents = $this->ftp_scan_dir($remote_directory);
if (!isset($contents)) {
$this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
return false;
}
foreach ($contents as $item) {
$drop = true;
foreach ($files as $file) {
if ($remote_directory . DIRECTORY_SEPARATOR . $file == $item['path'] || strstr($item['path'], $remote_directory . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR)) {
$drop = false;
break;
}
}
if ($drop) continue;
$relative_path = str_replace($remote_directory, '', $item['path']);
$local_path = $dest_local_directory . DIRECTORY_SEPARATOR . $relative_path;
switch ($item['type']) {
case 'd':
$success = mkdir($local_path);
break;
case 'f':
$success = ftp_get($this->connect, $local_path, $item['path'], FTP_BINARY);
break;
default:
$success = true;
}
if (!$success) {
$this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
return false;
}
}
return true;
}
|
Downloads specified files from remote directory
if there is a directory among files it is downloaded recursively (omitting symbolic links).
@param $remote_directory string remote FTP path to a source directory to download from.
@param array $files list of files to download from remote directory.
@param $dest_local_directory string destination folder to store downloaded files.
@return bool true on success and false on failure.
|
entailment
|
private function deleteDir($dirPath)
{
if (!is_dir($dirPath)) {
$success = unlink($dirPath);
} else {
$success = true;
foreach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {
$path = $dirPath . DIRECTORY_SEPARATOR . $path;
if(is_link($path)) {
unlink($path);
} else if (is_dir($path)) {
$success = rmdir($path);
} else {
$success = unlink($path);
}
if (!$success) {
break;
}
}
if($success) {
$success = rmdir($dirPath);
}
}
if(!$success) {
$this->setError(elFinder::ERROR_RM, $dirPath);
return false;
}
return $success;
}
|
Delete local directory recursively.
@param $dirPath string to directory to be erased.
@return bool true on success and false on failure.
|
entailment
|
private static function listFilesInDirectory($dir, $omitSymlinks, $prefix = '')
{
if (!is_dir($dir)) {
return false;
}
$excludes = array(".","..");
$result = array();
$files = scandir($dir);
if(!$files) {
return array();
}
foreach($files as $file) {
if(!in_array($file, $excludes)) {
$path = $dir.DIRECTORY_SEPARATOR.$file;
if(is_link($path)) {
if($omitSymlinks) {
continue;
} else {
$result[] = $prefix.$file;
}
} else if(is_dir($path)) {
$result[] = $prefix.$file.DIRECTORY_SEPARATOR;
$subs = elFinderVolumeFTP::listFilesInDirectory($path, $omitSymlinks, $prefix.$file.DIRECTORY_SEPARATOR);
if($subs) {
$result = array_merge($result, $subs);
}
} else {
$result[] = $prefix.$file;
}
}
}
return $result;
}
|
Returns array of strings containing all files and folders in the specified local directory.
@param $dir
@param string $prefix
@internal param string $path path to directory to scan.
@return array array of files and folders names relative to the $path
or an empty array if the directory $path is empty,
<br />
false if $path is not a directory or does not exist.
|
entailment
|
public function patchEntity(EntityInterface $type, array $data, array $options = [])
{
$return = parent::patchEntity($type, $data);
if (!empty($data['permissions'])) {
$roles = [];
foreach ($data['permissions'] as $rule => $ids) {
foreach ($ids as $roleId) {
if (!empty($roleId)) {
$role = $this->Roles->get($roleId);
$role->set('_joinData', $this->ContentTypePermissions->newEntity(['action' => $rule]));
$roles[] = $role;
}
}
}
$return->set('permissions', $roles);
}
return $return;
}
|
{@inheritDoc}
|
entailment
|
public function validationDefault(Validator $validator)
{
$validator
->requirePresence('name')
->add('name', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('content', 'You need to provide a content type name.'),
],
'length' => [
'rule' => ['minLength', 3],
'message' => __d('content', 'Name need to be at least 3 characters long.'),
],
])
->requirePresence('slug', 'create')
->notEmpty('slug', __d('content', 'Machine-name cannot be left empty.'), 'create')
->add('slug', 'checkSlug', [
'rule' => function ($value, $context) {
return (preg_match('/^[a-z0-9\-]{3,}$/', $value) === 1);
},
'message' => __d('content', 'Invalid machine-name.'),
])
->requirePresence('title_label')
->add('title_label', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('content', 'You need to provide a "Title Label".'),
],
'length' => [
'rule' => ['minLength', 3],
'message' => __d('content', '"Title Label" need to be at least 3 characters long.'),
],
]);
return $validator;
}
|
Default validation rules set.
@param \Cake\Validation\Validator $validator The validator object
@return \Cake\Validation\Validator
|
entailment
|
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options = null)
{
if ($entity->isNew()) {
snapshot();
}
}
|
Regenerates snapshot after new content type is created.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\Datasource\EntityInterface $entity The entity that was saved
@param \ArrayObject $options Array of options
@return void
|
entailment
|
public function userAllowed($action)
{
if (user()->isAdmin()) {
return true;
}
$this->_loadPermissions();
$allowedRoles = $this->_permissions
->filter(function ($rule) use ($action) {
return $rule->get('action') == $action;
})
->extract('role_id')
->toArray();
$intersect = array_intersect($allowedRoles, user()->get('role_ids'));
return !empty($intersect);
}
|
Checks if current user is allowed to perform the given $action (create, edit,
delete, publish).
@param string $action The action to check: create, edit, delete or
publish
@return bool
|
entailment
|
public function checkPermission($roleId, $action)
{
if ($roleId == ROLE_ID_ADMINISTRATOR) {
return true;
}
$this->_loadPermissions();
$rule = $this->_permissions
->filter(function ($rule) use ($roleId, $action) {
return $rule->get('role_id') == $roleId && $rule->get('action') == $action;
})
->first();
return !empty($rule);
}
|
Checks if the provided $roleId is allowed to perform the given $action.
@param int $roleId Role ID
@param string $action Action to check: create, edit, delete or publish
@return bool
|
entailment
|
protected function _loadPermissions()
{
if (empty($this->_permissions)) {
$permissions = TableRegistry::get('Content.ContentTypePermissions')
->find()
->where(['content_type_id' => $this->get('id')])
->toArray();
$this->_permissions = collection($permissions);
}
}
|
Loads ll permissions rules for this content type.
@return void
|
entailment
|
public function index()
{
$this->loadModel('Locale.Languages');
$languages = $this->Languages
->find()
->order(['ordering' => 'ASC'])
->all();
$this->title(__d('locale', 'Languages List'));
$this->set('languages', $languages);
$this->Breadcrumb->push('/admin/locale');
}
|
Shows a list of languages.
@return void
|
entailment
|
public function add()
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->newEntity();
$languages = LocaleToolbox::languagesList(true);
$icons = LocaleToolbox::flagsList();
if (!empty($this->request->data['code'])) {
$info = LocaleToolbox::info($this->request->data['code']);
$language = $this->Languages->patchEntity($language, [
'code' => normalizeLocale($this->request->data['code']),
'name' => $info['language'],
'direction' => $info['direction'],
'status' => (isset($this->request->data['status']) ? $this->request->data['status'] : false),
'icon' => (!empty($this->request->data['icon']) ? $this->request->data['icon'] : null)
]);
if ($this->Languages->save($language)) {
$this->Flash->success(__d('locale', 'Language was successfully registered!'));
$this->redirect(['plugin' => 'Locale', 'controller' => 'manage', 'action' => 'index']);
} else {
$this->Flash->danger(__d('locale', 'Language could not be registered, please check your information'));
}
}
$this->title(__d('locale', 'Register New Language'));
$this->set(compact('language', 'languages', 'icons'));
$this->Breadcrumb
->push('/admin/locale')
->push(__d('locale', 'Add new language'), '');
}
|
Registers a new language in the system.
@return void
|
entailment
|
public function edit($id)
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->get($id);
$languages = LocaleToolbox::languagesList(true);
$icons = LocaleToolbox::flagsList();
if ($this->request->data()) {
$language = $this->Languages->patchEntity($language, $this->request->data, [
'fieldList' => [
'name',
'direction',
'icon',
]
]);
if ($this->Languages->save($language)) {
$this->Flash->success(__d('locale', 'Language was successfully saved!'));
$this->redirect($this->referer());
} else {
$this->Flash->success(__d('locale', 'Language could not be saved, please check your information.'));
}
}
$this->title(__d('locale', 'Editing Language'));
$this->set(compact('language', 'languages', 'icons'));
$this->Breadcrumb
->push('/admin/locale')
->push(__d('locale', 'Editing language'), '');
}
|
Edits language.
@param int $id Language's ID
@return void
|
entailment
|
public function setDefault($id)
{
$this->loadModel('Locale.Languages');
$this->loadModel('System.Options');
$language = $this->Languages->get($id);
if ($language->status) {
if ($this->Options->update('default_language', $language->code)) {
$this->Flash->success(__d('locale', 'Default language changed!'));
} else {
$this->Flash->danger(__d('locale', 'Default language could not be changed.'));
}
} else {
$this->Flash->danger(__d('locale', 'You cannot set as default a disabled language.'));
}
$this->title(__d('locale', 'Set Default Language'));
$this->redirect($this->referer());
}
|
Sets the given language as site's default language.
@param int $id Language's ID
@return void Redirects to previous page
|
entailment
|
public function move($id, $direction)
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->get($id);
$unordered = $this->Languages->find()
->select(['id', 'ordering'])
->order(['ordering' => 'ASC'])
->all()
->extract('id')
->toArray();
$position = array_search($language->id, $unordered);
if (!is_integer($position)) {
$this->redirect($this->referer());
}
$direction = $direction === 'up' ? 'down' : 'up'; // fix orientation, top-down to left-right
$ordered = array_move($unordered, $position, $direction);
if (md5(serialize($ordered)) != md5(serialize($unordered))) {
foreach ($ordered as $ordering => $id) {
$this->Languages->updateAll(compact('ordering'), compact('id'));
}
}
$this->title(__d('locale', 'Reorder Language'));
$this->Flash->success(__d('locale', 'Language successfully reordered!'));
$this->redirect($this->referer());
}
|
Moves language up or down.
@param int $id Language's ID
@param string $direction Direction, 'up' or 'down'
@return void Redirects to previous page
|
entailment
|
public function enable($id)
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->get($id);
$language->set('status', true);
if ($this->Languages->save($language)) {
$this->Flash->success(__d('locale', 'Language successfully enabled!'));
} else {
$this->Flash->danger(__d('locale', 'Language could not be enabled, please try again.'));
}
$this->title(__d('locale', 'Enable Language'));
$this->redirect($this->referer());
}
|
Enables the given language.
@param int $id Language's ID
@return void Redirects to previous page
|
entailment
|
public function disable($id)
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->get($id);
if (!in_array($language->code, [CORE_LOCALE, option('default_language')])) {
$language->set('status', false);
if ($this->Languages->save($language)) {
$this->Flash->success(__d('locale', 'Language successfully disabled!'));
} else {
$this->Flash->danger(__d('locale', 'Language could not be disabled, please try again.'));
}
} else {
$this->Flash->danger(__d('locale', 'You cannot disable this language as it still in use.'));
}
$this->title(__d('locale', 'Disable Language'));
$this->redirect($this->referer());
}
|
Disables the given language.
@param int $id Language's ID
@return void Redirects to previous page
|
entailment
|
public function delete($id)
{
$this->loadModel('Locale.Languages');
$language = $this->Languages->get($id);
if (!in_array($language->code, [CORE_LOCALE, option('default_language')])) {
if ($this->Languages->delete($language)) {
$this->Flash->success(__d('locale', 'Language successfully removed!'));
} else {
$this->Flash->danger(__d('locale', 'Language could not be removed, please try again.'));
}
} else {
$this->Flash->danger(__d('locale', 'You cannot remove this language as it still in use.'));
}
$this->title(__d('locale', 'Delete Language'));
$this->redirect($this->referer());
}
|
Unregisters the given language.
@param int $id Language's ID
@return void Redirects to previous page
|
entailment
|
protected function _inResponseTo(Comment $comment)
{
$this->loadModel('Content.Contents');
$this->Contents->fieldable(false);
$content = $this->Contents->get($comment->entity_id);
if ($content) {
$out = __d('content', '<a href="{0}" target="_blank">{1}</a>', Router::url(['plugin' => 'Content', 'controller' => 'manage', 'action' => 'edit', $content->id]), $content->title);
$out .= '<br />';
$out .= __d('content', '<a href="{0}" target="_blank">{1}</a>', Router::url($content->url), 'View content');
return $out;
}
return __d('content', '-- Unknow --');
}
|
Renders the description of the entity to which comment is attached to.
@param \Comment\Model\Entity\Comment $comment Comment entity
@return string
|
entailment
|
public function render($options = [])
{
$items = $this->getStack();
$options = Hash::merge([
'breadcrumbGuessing' => false,
'class' => 'breadcrumb',
'templates' => [
'root' => '<ol{{attrs}}>{{content}}</ol>',
],
'formatter' => function ($entity, $info) {
$options = [];
if ($info['index'] === $info['total']) {
$options['childAttrs'] = ['class' => 'active'];
$options['templates']['link'] = '{{content}}';
}
return $this->Menu->formatter($entity, $info, $options);
}
], $options);
return $this->Menu->render($items, $options);
}
|
Renders a breadcrumb menu list.
This methods renders an `<ol>` HTML menu using `MenuHelper` class, check this
class for more information about valid options.
@param array $options Array of options for `MenuHelper::render()` method
@return string HTML
@see \Menu\View\Helper\MenuHelper::render()
|
entailment
|
public function check()
{
$pass = true;
foreach ($this->_rules as $rule) {
if ($rule->lhs() instanceof BasePackage) {
$package = $rule->lhs();
} else {
$package = PackageFactory::create((string)$rule->lhs());
}
if (!$package->versionMatch($rule->rhs())) {
$this->_fail($rule);
$pass = false;
} else {
$this->_pass($rule);
}
}
$this->_checked = true;
return $pass;
}
|
Checks all the rules of this class.
@return bool True if all rules are meet
|
entailment
|
public function pass($asString = false)
{
if (!$this->_checked) {
$this->check();
}
if (!$asString) {
return $this->_pass;
}
$items = [];
foreach ($this->_pass as $rule) {
$items[] = "{$rule}";
}
return implode(', ', $items);
}
|
Gets all rules marked as PASS.
@param bool $asString True will returns a comma separated string of rules
@return array|string
|
entailment
|
public function fail($asString = false)
{
if (!$this->_checked) {
$this->check();
}
if (!$asString) {
return $this->_fail;
}
$items = [];
foreach ($this->_fail as $rule) {
$items[] = "{$rule}";
}
return implode(', ', $items);
}
|
Gets all rules marked as FAIL.
@param bool $asString True will returns a comma separated string of rules
@return array|string
|
entailment
|
public function render(array $data, ContextInterface $context)
{
$data += [
'name' => '',
'val' => null,
'type' => 'text',
'escape' => true,
];
$data['value'] = $data['val'];
$data['readonly'] = 'readonly';
unset($data['val']);
$this->_loadAssets();
$data['class'] = !empty($data['class']) ? "{$data['class']} fontselector" : 'fontselector';
return $this->_templates->format('input', [
'name' => $data['name'],
'type' => 'text',
'attrs' => $this->_templates->formatAttributes(
$data,
['name', 'type']
),
]) . '<p id="' . $data['id'] . '-preview" style="font:' . $data['value'] . ';">Example text</p>';
}
|
Render a color picker widget.
@param array $data The data to build an input with.
@param \Cake\View\Form\ContextInterface $context The current form context.
@return string
|
entailment
|
protected function _loadAssets()
{
$this->_View->Html->css('System./font-panel/fontpanel.css', ['block' => true]);
$this->_View->Html->script('System./font-panel/fontpanel.js', ['block' => true]);
$this->_View->Html->script('System./font-panel/font-panel-init.js', ['block' => true]);
}
|
Load all CSS and JS assets required for this widget.
@return void
|
entailment
|
public function scope(Query $query, TokenInterface $token)
{
if ($token->negated()) {
return $query;
}
$value = intval($token->value());
if ($value > 0) {
$query->limit($value);
}
return $query;
}
|
{@inheritDoc}
|
entailment
|
public function check(User $user, $path)
{
$acoPath = $this->Acos->node($path);
if (empty($acoPath)) {
return false;
}
if (!$user->role_ids) {
return false;
}
$acoIDs = $acoPath->extract('id')->toArray();
$acoIDs = empty($acoIDs) ? [-1] : $acoIDs;
foreach ($user->role_ids as $roleId) {
$permission = $this->find()
->where([
'role_id' => $roleId,
'aco_id IN' => $acoIDs,
])
->first();
if ($permission) {
return true;
}
}
return false;
}
|
Checks if the given $user has access to the given $path
@param \User\Model\Entity\User $user An user entity
@param string $path An ACO path. e.g. `/Plugin/Controller/action`
@return bool true if user has access to action in ACO, false otherwise
|
entailment
|
public function index()
{
$plugins = plugin()->filter(function ($plugin) {
return $plugin->status && $plugin->hasHelp;
});
$this->title(__d('system', 'Help'));
$this->set('plugins', $plugins);
$this->Breadcrumb->push('/admin/system/help');
}
|
Main action.
Here is where we render all available documents. Plugins are able to define
their own `help document` just by creating an view-element named `help.ctp`.
Example:
Album plugin may create its own `help document` by creating this file:
/plugins/Album/src/Template/Element/Help/help.ctp
Optionally, plugins are able to define translated versions of help documents.
To do this, you must simply define a view element as `help_[code].ctp`, where
`[code]` is a two-character language code. For example:
help_en_US.ctp
help_es.ctp
help_fr.ctp
@return void
|
entailment
|
public function about($pluginName)
{
$about = false;
if (Plugin::loaded($pluginName)) {
$locale = I18n::locale();
$templatePath = App::path('Template', $pluginName)[0] . 'Element/Help/';
$lookFor = ["help_{$locale}", 'help'];
foreach ($lookFor as $ctp) {
if (is_readable($templatePath . "{$ctp}.ctp")) {
$about = "{$pluginName}.Help/{$ctp}";
break;
}
}
}
if ($about) {
$this->set('about', $about);
} else {
throw new NotFoundException(__d('system', 'No help was found.'));
}
$this->title(__d('system', 'About "{0}"', $pluginName));
$this->Breadcrumb
->push('/admin/system/help')
->push(__d('system', 'About {0}', $pluginName), '#');
}
|
Renders the help document of the given plugin.
@param string $pluginName The plugin name
@return void
@throws \Cake\Network\Exception\NotFoundException When no help document was found
|
entailment
|
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
$dataArray = Hash::expand((array)$data, ':');
foreach ($this->config('columns') as $column) {
if (isset($dataArray[$column])) {
$data[$column] = $dataArray[$column];
if ($options['validate']) {
$eventName = $this->_table->alias() . ".{$column}.validate";
$columnData = (array)$dataArray[$column];
$this->_table->dispatchEvent($eventName, compact('columnData', 'options'));
}
}
}
}
|
Triggered before data is converted into entities.
Moves multi-value POST data into its corresponding column, for instance given
the following POST array:
```php
[
'settings:max_time' => 10,
'settings:color' => '#005599',
'my_column:other_option' => 'some value',
]
```
It becomes:
```php
[
'settings' => [
'max_time' => 10,
'color' => '#005599',
],
'my_column' => [
'other_option' => 'some value',
]
]
```
@param \Cake\Event\Event $event The event that was triggered
@param \ArrayObject $data The POST data to be merged with entity
@param \ArrayObject $options The options passed to the marshaller
@return void
|
entailment
|
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
$query->formatResults(function ($results) use ($options) {
return $results->map(function ($entity) use ($options) {
if (!($entity instanceof EntityInterface)) {
return $entity;
}
foreach ($this->config('columns') as $column) {
if ($entity->has($column)) {
$eventName = $this->_table->alias() . ".{$column}.defaultValues";
$defaultValue = $this->_table->dispatchEvent($eventName, compact('entity'))->result;
$currentValue = $entity->get($column);
$newValue = $currentValue;
if (is_array($currentValue) && is_array($defaultValue)) {
$newValue = Hash::merge($defaultValue, $currentValue);
} elseif (is_string($currentValue) && $currentValue === '') {
$newValue = $defaultValue;
} elseif (empty($currentValue) && !empty($defaultValue)) {
$newValue = $defaultValue;
}
$entity->set($column, $newValue);
if (!empty($options['flatten']) && is_array($entity->get($column))) {
foreach ($entity->get($column) as $key => $value) {
$entity->set("{$column}:{$key}", $value);
}
}
}
}
return $entity;
});
});
}
|
Here we set default values for serializable columns.
This method triggers the `<TableAlias>.<columnName>.defaultValues` event, for
example "Plugins.settings.defaultValues" for the "settings" columns of the
"Plugins" table. Event listeners should catch this event and provides the
desired values.
### Options:
- flatten: Flattens serialized information into plain entity properties, for
example `settings:some_option` => `value`, where `settings` is the
serialized column and `some_option` a key of the serialized array value.
Valid only for column that stores array values. Example:
Consider the following entity:
```php
object(Cake\Datasource\EntityInterface) {
'settings' => [
'option_1' => 'Lorem ipsum',
'option_2' => [1, 2, 3, 4],
'option_3' => object,
],
}
```
Once `settings` column is flattened the entity will look as follow:
```php
object(Cake\Datasource\EntityInterface) {
'settings' => [
'option_1' => 'Lorem ipsum',
'option_2' => [1, 2, 3, 4],
'option_3' => object,
],
'settings:option_1' => 'Lorem ipsum',
'settings:option_2' => [1, 2, 3, 4],
'settings:option_3' => object,
}
```
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Query $query Query object
@param \ArrayObject $options Additional options as an array
@param bool $primary Whether is find is a primary query or not
@return void
|
entailment
|
protected function _message(\Exception $exception, $code)
{
if ($code === 503) {
return $this->error->getMessage();
}
return parent::_message($exception, $code);
}
|
{@inheritDoc}
|
entailment
|
protected function _template(\Exception $exception, $method, $code)
{
if ($code === 503) {
return 'maintenance';
}
return parent::_template($exception, $method, $code);
}
|
{@inheritDoc}
|
entailment
|
public function beforeSave(Event $event, $entity, $options = [])
{
if (!$this->_enabled) {
return true;
}
$config = $this->config();
$isNew = $entity->isNew();
if (($isNew && in_array($config['on'], ['create', 'both'])) ||
(!$isNew && in_array($config['on'], ['update', 'both']))
) {
if (!is_array($config['label'])) {
$config['label'] = [$config['label']];
}
foreach ($config['label'] as $field) {
if (!$entity->has($field)) {
throw new FatalErrorException(__d('cms', 'SluggableBehavior was not able to generate a slug reason: entity\'s property "{0}" not found', $field));
}
}
$label = '';
foreach ($config['label'] as $field) {
$val = $entity->get($field);
$label .= !empty($val) ? " {$val}" : '';
}
if (!empty($label)) {
$slug = $this->_slug($label, $entity);
$entity->set($config['slug'], $slug);
}
}
return true;
}
|
Run before a model is saved, used to set up slug for model.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Entity $entity The entity being saved
@param array $options Array of options for the save operation
@return bool True if save should proceed, false otherwise
@throws \Cake\Error\FatalErrorException When some of the specified columns
in config's "label" is not present in the entity being saved
|
entailment
|
protected function _slug($string, $entity)
{
$string = $this->_mbTrim(mb_strtolower($string));
$config = $this->config();
$slug = Inflector::slug($string, $config['separator']);
$pk = $this->_table->primaryKey();
if (mb_strlen($slug) > $config['length']) {
$slug = mb_substr($slug, 0, $config['length']);
}
$conditions = ["{$config['slug']} LIKE" => "{$slug}%"];
if ($entity->has($pk)) {
$conditions["{$pk} NOT IN"] = [$entity->{$pk}];
}
$same = $this->_table->find()
->where($conditions)
->all()
->extract($config['slug'])
->toArray();
if (!empty($same)) {
$initialSlug = $slug;
$index = 1;
while ($index > 0) {
$nextSlug = "{$initialSlug}{$config['separator']}{$index}";
if (!in_array($nextSlug, $same)) {
$slug = $nextSlug;
$index = -1;
}
$index++;
}
}
return $slug;
}
|
Generate a slug for the given string and entity. The generated slug is
unique across the entire table.
@param string $string String from where to generate slug
@param \Cake\ORM\Entity $entity The entity for which generate the slug
@return string Slug for given string
|
entailment
|
public function render(Field $field, View $view)
{
if ($field->metadata->settings['multi'] === 'custom') {
$settings = $field->metadata->settings;
$settings['multi'] = $field->metadata->settings['multi_custom'];
$field->metadata->set('settings', $settings);
}
return $view->element('Field.ImageField/display', compact('field'));
}
|
{@inheritDoc}
|
entailment
|
public function fieldAttached(Field $field)
{
$extra = (array)$field->extra;
if (!empty($extra)) {
$newExtra = [];
foreach ($extra as $file) {
$newExtra[] = array_merge([
'mime_icon' => '',
'file_name' => '',
'file_size' => '',
'title' => '',
'alt' => '',
], (array)$file);
}
$field->set('extra', $newExtra);
}
}
|
{@inheritDoc}
|
entailment
|
public function beforeDelete(Field $field)
{
foreach ((array)$field->extra as $image) {
if (!empty($image['file_name'])) {
ImageToolbox::delete(WWW_ROOT . "/files/{$field->settings['upload_folder']}/{$image['file_name']}");
}
}
}
|
{@inheritDoc}
|
entailment
|
public function beforeFind(Event $event, $query, $options, $primary)
{
if ($this->_enabled && $query->count() > 0) {
$pk = $this->_table->primaryKey();
$tableAlias = Inflector::underscore($this->_table->alias());
$query->contain([
'Comments' => function ($query) {
return $query->find('threaded')
->contain(['Users'])
->order($this->config('order'));
},
]);
if ($this->config('count') ||
(isset($options['comments_count']) && $options['comments_count'] === true)
) {
$query->formatResults(function ($results) use ($pk, $tableAlias) {
return $results->map(function ($entity) use ($pk, $tableAlias) {
$entityId = $entity->{$pk};
$count = TableRegistry::get('Comment.Comments')->find()
->where(['entity_id' => $entityId, 'table_alias' => $tableAlias])
->count();
$entity->set('comments_count', $count);
return $entity;
});
});
}
}
}
|
Attaches comments to each entity on find operation.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Query $query The query object
@param array $options Additional options as an array
@param bool $primary Whether is find is a primary query or not
@return void
|
entailment
|
public function findComments(Query $query, $options)
{
$tableAlias = Inflector::underscore($this->_table->alias());
if (empty($options['for'])) {
throw new \InvalidArgumentException("The 'for' key is required for find('children')");
}
$comments = $this->_table->Comments
->find('threaded')
->where(['table_alias' => $tableAlias, 'entity_id' => $options['for']])
->order($this->config('order'))
->all();
return $comments;
}
|
Get comments for the given entity.
Allows you to get all comments even when this behavior was disabled
using `unbindComments()`.
### Usage:
// in your controller, gets comments for post which id equals 2
$postComments = $this->Posts->find('comments', ['for' => 2]);
@param \Cake\ORM\Query $query The query object
@param array $options Additional options as an array
@return \Cake\Datasource\ResultSetDecorator Comments collection
@throws \InvalidArgumentException When the 'for' key is not passed in $options
|
entailment
|
public function viewMode($slug = null)
{
if ($slug === null) {
return ViewModeRegistry::current();
}
return ViewModeRegistry::uses($slug);
}
|
Sets a view mode or get current view mode.
@param string|null $slug Slug name of the view mode
@return void
@see \CMS\View\ViewModeRegistry::uses()
|
entailment
|
public static function addViewMode($slug, $name = null, $description = null)
{
return ViewModeRegistry::add($slug, $name, $description);
}
|
Registers a new view mode. Or overwrite if already exists.
@param string|array $slug Slug name of your view mode. e.g.: `my-view mode`.
Or an array of view modes to register indexed by slug name
@param string|null $name Human readable name. e.g.: `My View Mode`
@param string|null $description A brief description about for what is this view mode
@return void
@see \CMS\View\ViewModeRegistry::add()
|
entailment
|
public function onViewMode($viewMode, callable $method)
{
$viewMode = !is_array($viewMode) ? [$viewMode] : $viewMode;
if (in_array($this->viewMode(), $viewMode)) {
return $method();
}
}
|
Runs the given callable when the in-use view mode matches.
You can provide multiple view modes, in that case callable method will be
executed if current view mode matches any in the given array.
### Usage
```php
// run this only on `teaser` view mode
echo $this->onViewMode('teaser', function () use ($someVar) {
return $this->element('teaser_element', compact('someVar'));
});
// run this on "teaser" view mode, or "search-result" view mode
echo $this->onViewMode(['teaser', 'search-result'], function () use ($someVar) {
return $this->element('teaser_or_search_result', compact('someVar'));
});
```
@param string|array $viewMode View Mode slug, or an array of slugs
@param callable $method A callable function to run, it receives `$this` as
only argument
@return mixed Callable return
|
entailment
|
public function asViewMode($viewMode, callable $method)
{
$prevViewMode = $this->viewMode();
$this->viewMode($viewMode);
$method();
$this->viewMode($prevViewMode);
}
|
Runs the given callable as it were under the given view mode.
### Usage
```php
$this->viewMode('full');
echo 'before: ' . $this->viewMode();
echo $this->asViewMode('teaser', function () {
echo 'callable: ' . $this->viewMode();
});
echo 'after: ' . $this->viewMode();
// output:
// before: full
// callable: teaser
// after: full
```
@param string|array $viewMode View Mode slug, or an array of slugs
@param callable $method A callable function to run, it receives `$this` as
only argument
@return mixed Callable return
|
entailment
|
public function validate(Request $request)
{
if ($request->is('post')) {
// The (User's) Remote Address
$whatRemoteIP = env('REMOTE_ADDR') ? '&remoteip=' . env('REMOTE_ADDR') : '';
// The reCAPTCHA data is extracted from Request
$gRecaptchaResponse = $request->data('g-recaptcha-response');
// Verify reCAPTCHA data
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $this->config('secretKey') . '&response=' . $gRecaptchaResponse . $whatRemoteIP);
$response = json_decode($response, true);
// We return the Google server's response 'success' value
return (bool)$response['success'];
}
return false;
}
|
{@inheritDoc}
|
entailment
|
public function validationDefault(Validator $validator)
{
$validator
->allowEmpty('url')
->add('url', 'checkUrl', [
'rule' => function ($url, $context) {
$plainString = (
strpos($url, 'javascript:') === 0 ||
strpos($url, 'mailto:') === 0 ||
strpos($url, 'tel:') === 0 ||
strpos($url, 'sms:') === 0 ||
strpos($url, '#') === 0 ||
strpos($url, '?') === 0 ||
strpos($url, '//') === 0 ||
strpos($url, '://') !== false
);
if ($plainString) {
return true;
} else {
$full = Validation::url($url);
$internal = str_starts_with($url, '/');
return $full || $internal;
}
},
'message' => __d('menu', 'Invalid URL. Internal links must start with "/", e.g. "/article-my-first-article{0}"', CONTENT_EXTENSION),
'provider' => 'table',
])
->requirePresence('title')
->add('title', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('menu', 'You need to provide a title.'),
],
'length' => [
'rule' => ['minLength', 3],
'message' => __d('menu', 'Title need to be at least 3 characters long.'),
],
])
->add('activation', 'validActivation', [
'rule' => function ($value, $context) {
return in_array($value, ['auto', 'any', 'none', 'php']);
},
'message' => __d('menu', 'Please select an activation method.'),
'provider' => 'table',
])
->allowEmpty('active')
->add('active', 'validPHP', [
'rule' => function ($value, $context) {
if (!empty($context['data']['activation']) && $context['data']['activation'] === 'php') {
return strpos($value, '<?php') !== false && strpos($value, '?>') !== false;
}
return true;
},
'message' => __d('menu', 'Invalid PHP code, make sure that tags "<?php" & "?>" are present.')
]);
return $validator;
}
|
Default validation rules set.
@param \Cake\Validation\Validator $validator The validator object
@return \Cake\Validation\Validator
|
entailment
|
public function afterSave(Event $event, MenuLink $link, ArrayObject $options = null)
{
$this->clearCache();
}
|
Triggered after menu link was persisted in DB.
@param \Cake\Event\Event $event The event that was triggered
@param \Menu\Model\Entity\MenuLink $link The menu link entity that was saved
@param \ArrayObject $options Options given as an array
@return void
|
entailment
|
public function alterCreate(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($model, $options) = array_pad($invocation->getArguments(), 2, null);
$options = (array)$options;
$bootstrap = isset($options['bootstrap']) ? (bool)$options['bootstrap'] : true;
if ($bootstrap) {
$this->_addTemplates($helper);
}
if (isset($options['bootstrap'])) {
unset($options['bootstrap']);
}
$this->setProperty($invocation, 'arguments', [$model, $options]);
return $invocation->proceed();
}
|
Adds custom templates on Form::create().
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->create(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
public function alterInput(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($fieldName, $options) = array_pad($invocation->getArguments(), 2, null);
$options = (array)$options;
if (empty($options['type']) ||
!in_array($options['type'], ['textarea', 'select', 'button', 'submit', 'checkbox'])
) {
$options = $this->_addClass($helper, $options, 'form-control');
}
$this->_addTemplates($helper);
$this->setProperty($invocation, 'arguments', [$fieldName, $options]);
return $invocation->proceed();
}
|
Appends some CSS classes to generic input (text, textarea, select) elements.
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->input(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
public function alterTextarea(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($fieldName, $options) = array_pad($invocation->getArguments(), 2, null);
$options = (array)$options;
$options = $this->_addClass($helper, $options, 'form-control');
$this->_addTemplates($helper);
$this->setProperty($invocation, 'arguments', [$fieldName, $options]);
return $invocation->proceed();
}
|
Appends some CSS classes to textarea elements.
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->textarea(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
public function alterSelectbox(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($fieldName, $options, $attributes) = array_pad($invocation->getArguments(), 3, null);
$options = $options === null ? [] : $options;
$attributes = (array)$attributes;
$attributes = $this->_addClass($helper, $attributes, 'form-control');
$this->setProperty($invocation, 'arguments', [$fieldName, $options, $attributes]);
return $invocation->proceed();
}
|
Appends some CSS classes to select elements.
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->select(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
public function alterButton(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($title, $options) = array_pad($invocation->getArguments(), 2, null);
$options = (array)$options;
$options = $this->_addClass($helper, $options, 'btn btn-default');
$this->_addTemplates($helper);
$this->setProperty($invocation, 'arguments', [$title, $options]);
return $invocation->proceed();
}
|
Appends some CSS classes to generic buttons.
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->button(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
public function alterSubmit(MethodInvocation $invocation)
{
$helper = $invocation->getThis();
list($caption, $options) = array_pad($invocation->getArguments(), 2, null);
$options = (array)$options;
$options = $this->_addClass($helper, $options, 'btn btn-primary');
$this->_addTemplates($helper);
$this->setProperty($invocation, 'arguments', [$caption, $options]);
return $invocation->proceed();
}
|
Appends some CSS classes to submit buttons.
@param \Go\Aop\Intercept\MethodInvocation $invocation Invocation
@Around("execution(public Cake\View\Helper\FormHelper->submit(*))")
@return bool Whether object invocation should proceed or not
|
entailment
|
protected function _addClass(FormHelper $formHelper, $options, $class)
{
$bootstrap = isset($options['bootstrap']) ? (bool)$options['bootstrap'] : true;
if ($bootstrap) {
$options = $formHelper->addClass((array)$options, $class);
}
if (isset($options['bootstrap'])) {
unset($options['bootstrap']);
}
return $options;
}
|
Add custom CSS classes to array of options.
@param \Cake\View\Helper\FormHelper $formHelper Instance of FormHelper
@param null|array $options Input's options
@param string $class CSS classes to add
@return array
|
entailment
|
protected function _addTemplates(FormHelper $formHelper)
{
if (!static::cache('bootstrapTemplates')) {
$formHelper->templates($this->_templates);
static::cache('bootstrapTemplates', true);
}
}
|
Add custom set of templates to FormHelper.
@param \Cake\View\Helper\FormHelper $formHelper Instance of FormHelper
@return void
|
entailment
|
public function thumbnail($name)
{
$this->loadModel('Field.FieldInstances');
$instance = $this->_getInstance($name);
if (!$instance) {
throw new NotFoundException(__d('field', 'Invalid field instance.'), 400);
}
if (empty($this->request->query['file'])) {
throw new NotFoundException(__d('field', 'Invalid file name.'), 400);
}
if (empty($this->request->query['size'])) {
throw new NotFoundException(__d('field', 'Invalid image size.'), 400);
}
$imagePath = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/{$this->request->query['file']}");
$tmb = ImageToolbox::thumbnail($imagePath, $this->request->query['size']);
if ($tmb !== false) {
$this->response->file($tmb);
return $this->response;
}
throw new NotFoundException(__d('field', 'Thumbnail could not be found, check write permissions?'), 500);
}
|
Returns an scaled version of the given file image.
The following GET variables must be set on request:
- file: The image's file name to scale.
- size: A preview size name, sett `ImageToolbox::getPreviews()`
If any of these variables is not present an exception will be throw.
@param string $name EAV attribute name
@return \Cake\Network\Response
@throws \Cake\Network\Exception\NotFoundException When field instance
is not found.
|
entailment
|
public function render(Field $field, View $view)
{
$extra = array_merge([
'from' => ['string' => null, 'timestamp' => null],
'to' => ['string' => null, 'timestamp' => null],
], (array)$field->extra);
$field->set('extra', $extra);
return $view->element('Field.PublishDateField/display', compact('field'));
}
|
{@inheritDoc}
|
entailment
|
public function beforeFind(Field $field, array $options, $primary)
{
if ($primary &&
!Router::getRequest()->isAdmin() &&
!empty($field->extra['from']['timestamp']) &&
!empty($field->extra['to']['timestamp'])
) {
$now = time();
if ($field->extra['from']['timestamp'] > $now ||
$now > $field->extra['to']['timestamp']
) {
return null; // remove entity from result set
}
}
return true;
}
|
{@inheritDoc}
The entity to which this instance is attached to will be removed from
resulting result set if its publishing date does not match current date, this
constraint is not applied on the backend section of the site.
|
entailment
|
public function validate(Field $field, Validator $validator)
{
if ($field->metadata->required) {
$validator->notEmpty($field->name, __d('field', 'You must select a date/time range.'));
}
$validator
->add($field->name, [
'validRange' => [
'rule' => function ($value, $context) {
if (!empty($value['from']['string']) &&
!empty($value['from']['format']) &&
!empty($value['to']['string']) &&
!empty($value['to']['format'])
) {
$from = DateToolbox::createFromFormat($value['from']['format'], $value['from']['string']);
$to = DateToolbox::createFromFormat($value['to']['format'], $value['to']['string']);
return date_timestamp_get($from) < date_timestamp_get($to);
;
}
return false;
},
'message' => __d('field', 'Invalid date/time range, "Start" date must be before "Finish" date.')
]
]);
return true;
}
|
{@inheritDoc}
|
entailment
|
public function beforeSave(Field $field, $post)
{
$values = [];
$extra = [
'from' => ['string' => null, 'timestamp' => null],
'to' => ['string' => null, 'timestamp' => null],
];
foreach (['from', 'to'] as $type) {
if (!empty($post[$type]['string']) &&
!empty($post[$type]['format'])
) {
$date = $post[$type]['string'];
$format = $post[$type]['format'];
if ($date = DateToolbox::createFromFormat($format, $date)) {
$extra[$type]['string'] = $post[$type]['string'];
$extra[$type]['timestamp'] = date_timestamp_get($date);
$values[] = $extra[$type]['timestamp'] . ' ' . $post[$type]['string'];
} else {
$typeLabel = $type == 'from' ? __d('field', 'Start') : __d('field', 'Finish');
$field->metadata->entity->errors($field->name, __d('field', 'Invalid date/time range, "{0}" date must match the the pattern: {1}', $typeLabel, $format));
return false;
}
}
}
$field->set('value', implode(' ', $values));
$field->set('extra', $extra);
return true;
}
|
{@inheritDoc}
|
entailment
|
public function validateSettings(FieldInstance $instance, array $settings, Validator $validator)
{
$validator
->allowEmpty('time_format')
->add('time_format', 'validTimeFormat', [
'rule' => function ($value, $context) use ($settings) {
if (empty($settings['timepicker'])) {
return true;
}
return DateToolbox::validateTimeFormat($value);
},
'message' => __d('field', 'Invalid time format.')
])
->allowEmpty('format')
->add('format', 'validDateFormat', [
'rule' => function ($value, $context) {
return DateToolbox::validateDateFormat($value);
},
'message' => __d('field', 'Invalid date format.')
]);
}
|
{@inheritDoc}
|
entailment
|
public function validate(Field $field, Validator $validator)
{
if ($field->metadata->required) {
$validator
->requirePresence($field->name)
->notEmpty($field->name, __d('field', 'Field required.'));
} else {
$validator->allowEmpty($field->name);
}
return true;
}
|
{@inheritDoc}
|
entailment
|
public function beforeSave(Field $field, $post)
{
$value = $post;
if (is_array($value)) {
$value = implode(' ', array_values($value));
}
$field->set('value', $value);
$field->set('extra', $post);
}
|
{@inheritDoc}
|
entailment
|
public function index()
{
$this->loadModel('Menu.Menus');
$menus = $this->Menus->find()->all();
$this->title(__d('menu', 'Menus List'));
$this->set('menus', $menus);
$this->Breadcrumb->push('/admin/menu/manage');
}
|
Shows a list of all the menus.
@return void
|
entailment
|
public function add()
{
$this->loadModel('Menu.Menus');
$menu = $this->Menus->newEntity();
if ($this->request->data()) {
$data = $this->request->data();
$data['handler'] = 'Menu';
$menu = $this->Menus->patchEntity($menu, $data, [
'fieldList' => [
'title',
'handler',
'description',
'settings',
],
]);
if ($this->Menus->save($menu, ['atomic' => true])) {
$this->Flash->success(__d('menu', 'Menu has been created, now you can start adding links!'));
$this->redirect(['plugin' => 'Menu', 'controller' => 'links', 'action' => 'add', $menu->id]);
} else {
$this->Flash->danger(__d('menu', 'Menu could not be created, please check your information'));
}
}
$this->title(__d('menu', 'Create New Menu'));
$this->set('menu', $menu);
$this->Breadcrumb
->push('/admin/menu/manage')
->push(__d('menu', 'Creating new menu'), '#');
}
|
Adds a new menu.
@return void
|
entailment
|
public function edit($id)
{
$this->loadModel('Menu.Menus');
$menu = $this->Menus->get($id);
if ($this->request->data()) {
$menu = $this->Menus->patchEntity($menu, $this->request->data(), [
'fieldList' => [
'title',
'description',
'settings',
],
'validate' => false
]);
if ($this->Menus->save($menu, ['atomic' => true])) {
$this->Flash->success(__d('menu', 'Menu has been saved!'));
$this->redirect($this->referer());
} else {
$this->Flash->danger(__d('menu', 'Menu could not be saved, please check your information'));
}
}
$this->title(__d('menu', 'Editing Menu'));
$this->set('menu', $menu);
$this->Breadcrumb
->push('/admin/menu/manage')
->push(__d('menu', 'Editing menu {0}', $menu->title), '#');
}
|
Edits the given menu by ID.
@param int $id Menu's ID
@return void
|
entailment
|
public function delete($id)
{
$this->loadModel('Menu.Menus');
$menu = $this->Menus->get($id);
if ($menu->handler === 'Menu' && $this->Menus->delete($menu)) {
$this->Flash->success(__d('menu', 'Menu has been successfully deleted!'));
} else {
$this->Flash->danger(__d('menu', 'Menu could not be deleted, please try again'));
}
$this->title(__d('menu', 'Delete Menu'));
$this->redirect($this->referer());
}
|
Removes the given menu by ID.
Only custom menus (those created using administration page) can be removed.
@param int $id Menu's ID
@return void Redirects to previous page
|
entailment
|
public function scope(Query $query, $bundle = null)
{
$this->getVirtualColumns($query, $bundle);
return $query;
}
|
{@inheritDoc}
If "SELECT *" is performed
this behavior will fetch all virtual columns its values.
Column aliasing are fully supported, allowing to create alias for virtual
columns. For instance:
```php
$article = $this->Articles->find()
->select(['aliased_virtual' => 'some_eav_column', 'body'])
->where(['Articles.id' => $id])
->limit(1)
->first();
echo $article->get('aliased_virtual');
```
|
entailment
|
public function getVirtualColumns(Query $query, $bundle = null)
{
$selectClause = (array)$query->clause('select');
$isSelectAllFromJoin = true;
foreach (array_keys($selectClause) as $name) {
$isSelectAllFromJoin = $isSelectAllFromJoin && (strpos($name, 'Join__') !== false);
}
$selectClause = $isSelectAllFromJoin ? [] : $selectClause;
if (empty($selectClause)) {
return array_keys($this->_toolbox->attributes($bundle));
}
$selectedVirtual = [];
$virtualColumns = array_keys($this->_toolbox->attributes($bundle));
foreach ($selectClause as $index => $column) {
list($table, $column) = pluginSplit($column);
if ((empty($table) || $table == $this->_table->alias()) &&
in_array($column, $virtualColumns)
) {
$selectedVirtual[$index] = $column;
unset($selectClause[$index]);
}
}
if (empty($selectClause) && !empty($selectedVirtual)) {
$selectClause[] = $this->_table->primaryKey();
}
$query->select($selectClause, true);
return $selectedVirtual;
}
|
Gets a list of all virtual columns present in given $query's SELECT clause.
This method will alter the given Query object removing any virtual column
present in its SELECT clause in order to avoid incorrect SQL statements.
Selected virtual columns should be fetched after query is executed using
mapReduce or similar.
@param \Cake\ORM\Query $query The query object to be scoped
@param string|null $bundle Consider attributes only for a specific bundle
@return array List of virtual columns names
|
entailment
|
public function url($url)
{
if (is_string($url)) {
$url = $this->localePrefix($url);
}
try {
$url = Router::url($url, true);
} catch (\Exception $ex) {
$url = '';
}
return $url;
}
|
Returns a safe URL string for later use with HtmlHelper.
@param string|array $url URL given as string or an array compatible
with `Router::url()`
@return string
|
entailment
|
public function isActive(EntityInterface $item)
{
if ($item->has('activation') && is_callable($item->get('activation'))) {
$callable = $item->get('activation');
return $callable($this->_View->request, $item);
}
$itemUrl = $this->sanitize($item->get('url'));
if (!str_starts_with($itemUrl, '/')) {
return false;
}
switch ($item->get('activation')) {
case 'any':
return $this->_requestMatches($item->get('active'));
case 'none':
return !$this->_requestMatches($item->get('active'));
case 'php':
return php_eval($item->get('active'), [
'view', &$this->_View,
'item', &$item,
]) === true;
case 'auto':
default:
static $requestUri = null;
static $requestUrl = null;
if ($requestUri === null) {
$requestUri = urldecode(env('REQUEST_URI'));
$requestUrl = str_replace('//', '/', '/' . urldecode($this->_View->request->url) . '/');
}
$isInternal =
$itemUrl !== '/' &&
str_ends_with($itemUrl, str_replace_once($this->baseUrl(), '', $requestUri));
$isIndex =
$itemUrl === '/' &&
$this->_View->request->isHome();
$isExact =
str_replace('//', '/', "{$itemUrl}/") === $requestUrl ||
$itemUrl == $requestUri;
if ($this->config('breadcrumbGuessing')) {
return ($isInternal || $isIndex || $isExact || in_array($itemUrl, $this->_crumbs()));
}
return ($isInternal || $isIndex || $isExact);
}
}
|
Checks if the given menu link should be marked as active.
If `$item->activation` is a callable function it will be used to determinate
if the link should be active or not, returning true from callable indicates
link should be active, false indicates it should not be marked as active.
Callable receives current request object as first argument and $item as second.
`$item->url` property MUST exists if "activation" is not a callable, and can
be either:
- A string representing an external or internal URL (all internal links must
starts with "/"). e.g. `/user/login`
- An array compatible with \Cake\Routing\Router::url(). e.g. `['controller'
=> 'users', 'action' => 'login']`
Both examples are equivalent.
@param \Cake\Datasource\EntityInterface $item A menu's item
@return bool
|
entailment
|
public function sanitize($url)
{
try {
$url = Router::url($url);
} catch (\Exception $ex) {
return '';
}
if (!str_starts_with($url, '/')) {
return $url;
}
if (str_starts_with($url, $this->baseUrl())) {
$url = str_replace_once($this->baseUrl(), '', $url);
}
return $this->localePrefix($url);
}
|
Sanitizes the given URL by making sure it's suitable for menu links.
@param string $url Item's URL to sanitize
@return string Valid URL, empty string on error
|
entailment
|
public function localePrefix($url)
{
if (option('url_locale_prefix') &&
str_starts_with($url, '/') &&
!preg_match('/^\/' . $this->_localesPattern() . '/', $url)
) {
$url = '/' . I18n::locale() . $url;
}
return $url;
}
|
Prepends language code to the given URL if the "url_locale_prefix" directive
is enabled.
@param string $url The URL to fix
@return string Locale prefixed URL
|
entailment
|
public function baseUrl()
{
static $base = null;
if ($base === null) {
$base = $this->_View->request->base;
}
return $base;
}
|
Calculates site's base URL.
@return string Site's base URL
|
entailment
|
protected function _crumbs()
{
static $crumbs = null;
if ($crumbs === null) {
$crumbs = BreadcrumbRegistry::getUrls();
foreach ($crumbs as &$crumb) {
$crumb = $this->sanitize($crumb);
}
}
return $crumbs;
}
|
Gets a list of all URLs present in current crumbs stack.
@return array List of URLs
|
entailment
|
protected function _requestMatches($patterns)
{
if (empty($patterns)) {
return false;
}
$request = $this->_View->request;
$path = '/' . urldecode($request->url);
$patterns = explode("\n", $patterns);
foreach ($patterns as &$p) {
$p = $this->_View->Url->build('/') . $p;
$p = str_replace('//', '/', $p);
$p = str_replace($request->base, '', $p);
$p = $this->localePrefix($p);
}
$patterns = implode("\n", $patterns);
// Convert path settings to a regular expression.
// Therefore replace newlines with a logical or, /* with asterisks and "/" with the front page.
$toReplace = [
'/(\r\n?|\n)/', // newlines
'/\\\\\*/', // asterisks
'/(^|\|)\/($|\|)/' // front '/'
];
$replacements = [
'|',
'.*',
'\1' . preg_quote($this->_View->Url->build('/'), '/') . '\2'
];
$patternsQuoted = preg_quote($patterns, '/');
$patterns = '/^(' . preg_replace($toReplace, $replacements, $patternsQuoted) . ')$/';
return (bool)preg_match($patterns, $path);
}
|
Check if current request path matches any pattern in a set of patterns.
@param string $patterns String containing a set of patterns separated by \n,
\r or \r\n
@return bool TRUE if the path matches a pattern, FALSE otherwise
|
entailment
|
protected function _localesPattern()
{
$cacheKey = '_localesPattern';
$cache = static::cache($cacheKey);
if ($cache) {
return $cache;
}
$pattern = '(' . implode(
'|',
array_map(
'preg_quote',
array_keys(
quickapps('languages')
)
)
) . ')';
return static::cache($cacheKey, $pattern);
}
|
Returns a regular expression that is used to verify if an URL starts
or not with a language prefix.
## Example:
```
(en\-us|fr|es|it)
```
@return string
|
entailment
|
public function composer($full = false)
{
$cacheKey = "composer({$this->_packageName}, {$full})";
if ($cache = static::cache($cacheKey)) {
return $cache;
}
$jsonPath = normalizePath($this->path() . '/composer.json');
if (!is_readable($jsonPath)) {
return [];
}
$json = json_decode(file_get_contents($jsonPath), true);
if (empty($json)) {
return [];
}
if ($full) {
$json = Hash::merge(JsonSchema::$schema, $json);
}
return static::cache($cacheKey, $json);
}
|
Gets composer json information for this package.
@param bool $full Whether to get full composer schema or not. Defaults to
false, only defined keys in JSON file will be fetched
@return array Package's "composer.json" file as an array, an empty array if
corrupt or not found
|
entailment
|
public static function formatter(Field $field)
{
$result = '';
$options = [];
if (!empty($field->metadata->settings['options'])) {
foreach (explode("\n", $field->metadata->settings['options']) as $option) {
$option = explode('|', $option);
$value = $option[0];
$label = isset($option[1]) ? $option[1] : $option[0];
$options[$value] = $label;
}
}
if (is_string($field->extra)) {
$selectedOptions = [$field->extra];
} else {
$selectedOptions = (array)$field->extra;
}
foreach ($selectedOptions as $key) {
switch ($field->viewModeSettings['formatter']) {
case 'key':
$result .= "{$key}<br />";
break;
case 'default':
default:
if (!empty($options[$key])) {
$result .= "{$options[$key]}<br />";
}
break;
}
}
return $result;
}
|
Formats the given field.
@param \Field\Model\Entity\Field $field The field being rendered
@return string
|
entailment
|
public function matches(LinkConstraintInterface $provider)
{
if ($provider instanceof MultiConstraint) {
// turn matching around to find a match
return $provider->matches($this);
} elseif ($provider instanceof $this) {
return $this->matchSpecific($provider);
}
return true;
}
|
{@inheritDoc}
|
entailment
|
function process($server_path = null) {
$this->error = '';
$this->processed = true;
$return_mode = false;
$return_content = null;
// clean up dst variables
$this->file_dst_path = '';
$this->file_dst_pathname = '';
$this->file_dst_name = '';
$this->file_dst_name_body = '';
$this->file_dst_name_ext = '';
// clean up some parameters
$this->file_max_size = $this->getsize($this->file_max_size);
$this->jpeg_size = $this->getsize($this->jpeg_size);
// copy some variables as we need to keep them clean
$file_src_name = $this->file_src_name;
$file_src_name_body = $this->file_src_name_body;
$file_src_name_ext = $this->file_src_name_ext;
if (!$this->uploaded) {
$this->error = $this->translate('file_not_uploaded');
$this->processed = false;
}
if ($this->processed) {
if (empty($server_path) || is_null($server_path)) {
$this->log .= '<b>process file and return the content</b><br />';
$return_mode = true;
} else {
if(strtolower(substr(PHP_OS, 0, 3)) === 'win') {
if (substr($server_path, -1, 1) != '\\') $server_path = $server_path . '\\';
} else {
if (substr($server_path, -1, 1) != '/') $server_path = $server_path . '/';
}
$this->log .= '<b>process file to ' . $server_path . '</b><br />';
}
}
if ($this->processed) {
// checks file max size
if ($this->file_src_size > $this->file_max_size) {
$this->processed = false;
$this->error = $this->translate('file_too_big') . ' : ' . $this->file_src_size . ' > ' . $this->file_max_size;
} else {
$this->log .= '- file size OK<br />';
}
}
if ($this->processed) {
// if we have an image without extension, set it
if ($this->file_force_extension && $this->file_is_image && !$this->file_src_name_ext) $file_src_name_ext = $this->image_src_type;
// turn dangerous scripts into text files
if ($this->no_script) {
// if the file has no extension, we try to guess it from the MIME type
if ($this->file_force_extension && empty($file_src_name_ext)) {
if ($key = array_search($this->file_src_mime, $this->mime_types)) {
$file_src_name_ext = $key;
$file_src_name = $file_src_name_body . '.' . $file_src_name_ext;
$this->log .= '- file renamed as ' . $file_src_name_body . '.' . $file_src_name_ext . '!<br />';
}
}
// if the file is text based, or has a dangerous extension, we rename it as .txt
if ((((substr($this->file_src_mime, 0, 5) == 'text/' && $this->file_src_mime != 'text/rtf') || strpos($this->file_src_mime, 'javascript') !== false) && (substr($file_src_name, -4) != '.txt'))
|| preg_match('/\.(php|php5|php4|php3|phtml|pl|py|cgi|asp|js)$/i', $this->file_src_name)
|| $this->file_force_extension && empty($file_src_name_ext)) {
$this->file_src_mime = 'text/plain';
if ($this->file_src_name_ext) $file_src_name_body = $file_src_name_body . '.' . $this->file_src_name_ext;
$file_src_name_ext = 'txt';
$file_src_name = $file_src_name_body . '.' . $file_src_name_ext;
$this->log .= '- script renamed as ' . $file_src_name_body . '.' . $file_src_name_ext . '!<br />';
}
}
if ($this->mime_check && empty($this->file_src_mime)) {
$this->processed = false;
$this->error = $this->translate('no_mime');
} else if ($this->mime_check && !empty($this->file_src_mime) && strpos($this->file_src_mime, '/') !== false) {
list($m1, $m2) = explode('/', $this->file_src_mime);
$allowed = false;
// check wether the mime type is allowed
if (!is_array($this->allowed)) $this->allowed = array($this->allowed);
foreach($this->allowed as $k => $v) {
list($v1, $v2) = explode('/', $v);
if (($v1 == '*' && $v2 == '*') || ($v1 == $m1 && ($v2 == $m2 || $v2 == '*'))) {
$allowed = true;
break;
}
}
// check wether the mime type is forbidden
if (!is_array($this->forbidden)) $this->forbidden = array($this->forbidden);
foreach($this->forbidden as $k => $v) {
list($v1, $v2) = explode('/', $v);
if (($v1 == '*' && $v2 == '*') || ($v1 == $m1 && ($v2 == $m2 || $v2 == '*'))) {
$allowed = false;
break;
}
}
if (!$allowed) {
$this->processed = false;
$this->error = $this->translate('incorrect_file');
} else {
$this->log .= '- file mime OK : ' . $this->file_src_mime . '<br />';
}
} else {
$this->log .= '- file mime (not checked) : ' . $this->file_src_mime . '<br />';
}
// if the file is an image, we can check on its dimensions
// these checks are not available if open_basedir restrictions are in place
if ($this->file_is_image) {
if (is_numeric($this->image_src_x) && is_numeric($this->image_src_y)) {
$ratio = $this->image_src_x / $this->image_src_y;
if (!is_null($this->image_max_width) && $this->image_src_x > $this->image_max_width) {
$this->processed = false;
$this->error = $this->translate('image_too_wide');
}
if (!is_null($this->image_min_width) && $this->image_src_x < $this->image_min_width) {
$this->processed = false;
$this->error = $this->translate('image_too_narrow');
}
if (!is_null($this->image_max_height) && $this->image_src_y > $this->image_max_height) {
$this->processed = false;
$this->error = $this->translate('image_too_high');
}
if (!is_null($this->image_min_height) && $this->image_src_y < $this->image_min_height) {
$this->processed = false;
$this->error = $this->translate('image_too_short');
}
if (!is_null($this->image_max_ratio) && $ratio > $this->image_max_ratio) {
$this->processed = false;
$this->error = $this->translate('ratio_too_high');
}
if (!is_null($this->image_min_ratio) && $ratio < $this->image_min_ratio) {
$this->processed = false;
$this->error = $this->translate('ratio_too_low');
}
if (!is_null($this->image_max_pixels) && $this->image_src_pixels > $this->image_max_pixels) {
$this->processed = false;
$this->error = $this->translate('too_many_pixels');
}
if (!is_null($this->image_min_pixels) && $this->image_src_pixels < $this->image_min_pixels) {
$this->processed = false;
$this->error = $this->translate('not_enough_pixels');
}
} else {
$this->log .= '- no image properties available, can\'t enforce dimension checks : ' . $this->file_src_mime . '<br />';
}
}
}
if ($this->processed) {
$this->file_dst_path = $server_path;
// repopulate dst variables from src
$this->file_dst_name = $file_src_name;
$this->file_dst_name_body = $file_src_name_body;
$this->file_dst_name_ext = $file_src_name_ext;
if ($this->file_overwrite) $this->file_auto_rename = false;
if ($this->image_convert && $this->file_is_image) { // if we convert as an image
if ($this->file_src_name_ext) $this->file_dst_name_ext = $this->image_convert;
$this->log .= '- new file name ext : ' . $this->image_convert . '<br />';
}
if (!is_null($this->file_new_name_body)) { // rename file body
$this->file_dst_name_body = $this->file_new_name_body;
$this->log .= '- new file name body : ' . $this->file_new_name_body . '<br />';
}
if (!is_null($this->file_new_name_ext)) { // rename file ext
$this->file_dst_name_ext = $this->file_new_name_ext;
$this->log .= '- new file name ext : ' . $this->file_new_name_ext . '<br />';
}
if (!is_null($this->file_name_body_add)) { // append a string to the name
$this->file_dst_name_body = $this->file_dst_name_body . $this->file_name_body_add;
$this->log .= '- file name body append : ' . $this->file_name_body_add . '<br />';
}
if (!is_null($this->file_name_body_pre)) { // prepend a string to the name
$this->file_dst_name_body = $this->file_name_body_pre . $this->file_dst_name_body;
$this->log .= '- file name body prepend : ' . $this->file_name_body_pre . '<br />';
}
if ($this->file_safe_name) { // formats the name
$this->file_dst_name_body = utf8_encode(strtr(utf8_decode($this->file_dst_name_body), utf8_decode('ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ'), 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'));
$this->file_dst_name_body = strtr($this->file_dst_name_body, array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
$this->file_dst_name_body = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $this->file_dst_name_body);
$this->log .= '- file name safe format<br />';
}
$this->log .= '- destination variables<br />';
if (empty($this->file_dst_path) || is_null($this->file_dst_path)) {
$this->log .= ' file_dst_path : n/a<br />';
} else {
$this->log .= ' file_dst_path : ' . $this->file_dst_path . '<br />';
}
$this->log .= ' file_dst_name_body : ' . $this->file_dst_name_body . '<br />';
$this->log .= ' file_dst_name_ext : ' . $this->file_dst_name_ext . '<br />';
// set the destination file name
$this->file_dst_name = $this->file_dst_name_body . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : '');
if (!$return_mode) {
if (!$this->file_auto_rename) {
$this->log .= '- no auto_rename if same filename exists<br />';
$this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name;
} else {
$this->log .= '- checking for auto_rename<br />';
$this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name;
$body = $this->file_dst_name_body;
$ext = '';
// if we have changed the extension, then we add our increment before
if ($file_src_name_ext != $this->file_src_name_ext) {
if (substr($this->file_dst_name_body, -1 - strlen($this->file_src_name_ext)) == '.' . $this->file_src_name_ext) {
$body = substr($this->file_dst_name_body, 0, strlen($this->file_dst_name_body) - 1 - strlen($this->file_src_name_ext));
$ext = '.' . $this->file_src_name_ext;
}
}
$cpt = 1;
while (@file_exists($this->file_dst_pathname)) {
$this->file_dst_name_body = $body . '_' . $cpt . $ext;
$this->file_dst_name = $this->file_dst_name_body . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : '');
$cpt++;
$this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name;
}
if ($cpt>1) $this->log .= ' auto_rename to ' . $this->file_dst_name . '<br />';
}
$this->log .= '- destination file details<br />';
$this->log .= ' file_dst_name : ' . $this->file_dst_name . '<br />';
$this->log .= ' file_dst_pathname : ' . $this->file_dst_pathname . '<br />';
if ($this->file_overwrite) {
$this->log .= '- no overwrite checking<br />';
} else {
if (@file_exists($this->file_dst_pathname)) {
$this->processed = false;
$this->error = $this->translate('already_exists', array($this->file_dst_name));
} else {
$this->log .= '- ' . $this->file_dst_name . ' doesn\'t exist already<br />';
}
}
}
}
if ($this->processed) {
// if we have already moved the uploaded file, we use the temporary copy as source file, and check if it exists
if (!empty($this->file_src_temp)) {
$this->log .= '- use the temp file instead of the original file since it is a second process<br />';
$this->file_src_pathname = $this->file_src_temp;
if (!file_exists($this->file_src_pathname)) {
$this->processed = false;
$this->error = $this->translate('temp_file_missing');
}
// if we haven't a temp file, and that we do check on uploads, we use is_uploaded_file()
} else if (!$this->no_upload_check) {
if (!is_uploaded_file($this->file_src_pathname)) {
$this->processed = false;
$this->error = $this->translate('source_missing');
}
// otherwise, if we don't check on uploaded files (local file for instance), we use file_exists()
} else {
if (!file_exists($this->file_src_pathname)) {
$this->processed = false;
$this->error = $this->translate('source_missing');
}
}
// checks if the destination directory exists, and attempt to create it
if (!$return_mode) {
if ($this->processed && !file_exists($this->file_dst_path)) {
if ($this->dir_auto_create) {
$this->log .= '- ' . $this->file_dst_path . ' doesn\'t exist. Attempting creation:';
if (!$this->rmkdir($this->file_dst_path, $this->dir_chmod)) {
$this->log .= ' failed<br />';
$this->processed = false;
$this->error = $this->translate('destination_dir');
} else {
$this->log .= ' success<br />';
}
} else {
$this->error = $this->translate('destination_dir_missing');
}
}
if ($this->processed && !is_dir($this->file_dst_path)) {
$this->processed = false;
$this->error = $this->translate('destination_path_not_dir');
}
// checks if the destination directory is writeable, and attempt to make it writeable
$hash = md5($this->file_dst_name_body . rand(1, 1000));
if ($this->processed && !($f = @fopen($this->file_dst_path . $hash . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''), 'a+'))) {
if ($this->dir_auto_chmod) {
$this->log .= '- ' . $this->file_dst_path . ' is not writeable. Attempting chmod:';
if (!@chmod($this->file_dst_path, $this->dir_chmod)) {
$this->log .= ' failed<br />';
$this->processed = false;
$this->error = $this->translate('destination_dir_write');
} else {
$this->log .= ' success<br />';
if (!($f = @fopen($this->file_dst_path . $hash . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''), 'a+'))) { // we re-check
$this->processed = false;
$this->error = $this->translate('destination_dir_write');
} else {
@fclose($f);
}
}
} else {
$this->processed = false;
$this->error = $this->translate('destination_path_write');
}
} else {
if ($this->processed) @fclose($f);
@unlink($this->file_dst_path . $hash . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''));
}
// if we have an uploaded file, and if it is the first process, and if we can't access the file directly (open_basedir restriction)
// then we create a temp file that will be used as the source file in subsequent processes
// the third condition is there to check if the file is not accessible *directly* (it already has positively gone through is_uploaded_file(), so it exists)
if (!$this->no_upload_check && empty($this->file_src_temp) && !@file_exists($this->file_src_pathname)) {
$this->log .= '- attempting to use a temp file:';
$hash = md5($this->file_dst_name_body . rand(1, 1000));
if (move_uploaded_file($this->file_src_pathname, $this->file_dst_path . $hash . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''))) {
$this->file_src_pathname = $this->file_dst_path . $hash . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : '');
$this->file_src_temp = $this->file_src_pathname;
$this->log .= ' file created<br />';
$this->log .= ' temp file is: ' . $this->file_src_temp . '<br />';
} else {
$this->log .= ' failed<br />';
$this->processed = false;
$this->error = $this->translate('temp_file');
}
}
}
}
if ($this->processed) {
// check if we need to autorotate, to automatically pre-rotates the image according to EXIF data (JPEG only)
$auto_flip = false;
$auto_rotate = 0;
if ($this->file_is_image && $this->image_auto_rotate && $this->image_src_type == 'jpg' && $this->function_enabled('exif_read_data')) {
$exif = @exif_read_data($this->file_src_pathname);
if (is_array($exif) && isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
switch($orientation) {
case 1:
$this->log .= '- EXIF orientation = 1 : default<br />';
break;
case 2:
$auto_flip = 'v';
$this->log .= '- EXIF orientation = 2 : vertical flip<br />';
break;
case 3:
$auto_rotate = 180;
$this->log .= '- EXIF orientation = 3 : 180 rotate left<br />';
break;
case 4:
$auto_flip = 'h';
$this->log .= '- EXIF orientation = 4 : horizontal flip<br />';
break;
case 5:
$auto_flip = 'h';
$auto_rotate = 90;
$this->log .= '- EXIF orientation = 5 : horizontal flip + 90 rotate right<br />';
break;
case 6:
$auto_rotate = 90;
$this->log .= '- EXIF orientation = 6 : 90 rotate right<br />';
break;
case 7:
$auto_flip = 'v';
$auto_rotate = 90;
$this->log .= '- EXIF orientation = 7 : vertical flip + 90 rotate right<br />';
break;
case 8:
$auto_rotate = 270;
$this->log .= '- EXIF orientation = 8 : 90 rotate left<br />';
break;
default:
$this->log .= '- EXIF orientation = '.$orientation.' : unknown<br />';
break;
}
} else {
$this->log .= '- EXIF data is invalid or missing<br />';
}
} else {
if (!$this->image_auto_rotate) {
$this->log .= '- auto-rotate deactivated<br />';
} else if (!$this->image_src_type == 'jpg') {
$this->log .= '- auto-rotate applies only to JPEG images<br />';
} else if (!$this->function_enabled('exif_read_data')) {
$this->log .= '- auto-rotate requires function exif_read_data to be enabled<br />';
}
}
// do we do some image manipulation?
$image_manipulation = ($this->file_is_image && (
$this->image_resize
|| $this->image_convert != ''
|| is_numeric($this->image_brightness)
|| is_numeric($this->image_contrast)
|| is_numeric($this->image_opacity)
|| is_numeric($this->image_threshold)
|| !empty($this->image_tint_color)
|| !empty($this->image_overlay_color)
|| $this->image_pixelate
|| $this->image_unsharp
|| !empty($this->image_text)
|| $this->image_greyscale
|| $this->image_negative
|| !empty($this->image_watermark)
|| $auto_rotate || $auto_flip
|| is_numeric($this->image_rotate)
|| is_numeric($this->jpeg_size)
|| !empty($this->image_flip)
|| !empty($this->image_crop)
|| !empty($this->image_precrop)
|| !empty($this->image_border)
|| !empty($this->image_border_transparent)
|| $this->image_frame > 0
|| $this->image_bevel > 0
|| $this->image_reflection_height));
// we do a quick check to ensure the file is really an image
// we can do this only now, as it would have failed before in case of open_basedir
if ($image_manipulation && !@getimagesize($this->file_src_pathname)) {
$this->log .= '- the file is not an image!<br />';
$image_manipulation = false;
}
if ($image_manipulation) {
// make sure GD doesn't complain too much
@ini_set("gd.jpeg_ignore_warning", 1);
// checks if the source file is readable
if ($this->processed && !($f = @fopen($this->file_src_pathname, 'r'))) {
$this->processed = false;
$this->error = $this->translate('source_not_readable');
} else {
@fclose($f);
}
// we now do all the image manipulations
$this->log .= '- image resizing or conversion wanted<br />';
if ($this->gdversion()) {
switch($this->image_src_type) {
case 'jpg':
if (!$this->function_enabled('imagecreatefromjpeg')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('JPEG'));
} else {
$image_src = @imagecreatefromjpeg($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('JPEG'));
} else {
$this->log .= '- source image is JPEG<br />';
}
}
break;
case 'png':
if (!$this->function_enabled('imagecreatefrompng')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('PNG'));
} else {
$image_src = @imagecreatefrompng($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('PNG'));
} else {
$this->log .= '- source image is PNG<br />';
}
}
break;
case 'gif':
if (!$this->function_enabled('imagecreatefromgif')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('GIF'));
} else {
$image_src = @imagecreatefromgif($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('GIF'));
} else {
$this->log .= '- source image is GIF<br />';
}
}
break;
case 'bmp':
if (!method_exists($this, 'imagecreatefrombmp')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('BMP'));
} else {
$image_src = @$this->imagecreatefrombmp($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('BMP'));
} else {
$this->log .= '- source image is BMP<br />';
}
}
break;
default:
$this->processed = false;
$this->error = $this->translate('source_invalid');
}
} else {
$this->processed = false;
$this->error = $this->translate('gd_missing');
}
if ($this->processed && $image_src) {
// we have to set image_convert if it is not already
if (empty($this->image_convert)) {
$this->log .= '- setting destination file type to ' . $this->image_src_type . '<br />';
$this->image_convert = $this->image_src_type;
}
if (!in_array($this->image_convert, $this->image_supported)) {
$this->image_convert = 'jpg';
}
// we set the default color to be the background color if we don't output in a transparent format
if ($this->image_convert != 'png' && $this->image_convert != 'gif' && !empty($this->image_default_color) && empty($this->image_background_color)) $this->image_background_color = $this->image_default_color;
if (!empty($this->image_background_color)) $this->image_default_color = $this->image_background_color;
if (empty($this->image_default_color)) $this->image_default_color = '#FFFFFF';
$this->image_src_x = imagesx($image_src);
$this->image_src_y = imagesy($image_src);
$gd_version = $this->gdversion();
$ratio_crop = null;
if (!imageistruecolor($image_src)) { // $this->image_src_type == 'gif'
$this->log .= '- image is detected as having a palette<br />';
$this->image_is_palette = true;
$this->image_transparent_color = imagecolortransparent($image_src);
if ($this->image_transparent_color >= 0 && imagecolorstotal($image_src) > $this->image_transparent_color) {
$this->image_is_transparent = true;
$this->log .= ' palette image is detected as transparent<br />';
}
// if the image has a palette (GIF), we convert it to true color, preserving transparency
$this->log .= ' convert palette image to true color<br />';
$true_color = imagecreatetruecolor($this->image_src_x, $this->image_src_y);
imagealphablending($true_color, false);
imagesavealpha($true_color, true);
for ($x = 0; $x < $this->image_src_x; $x++) {
for ($y = 0; $y < $this->image_src_y; $y++) {
if ($this->image_transparent_color >= 0 && imagecolorat($image_src, $x, $y) == $this->image_transparent_color) {
imagesetpixel($true_color, $x, $y, 127 << 24);
} else {
$rgb = imagecolorsforindex($image_src, imagecolorat($image_src, $x, $y));
imagesetpixel($true_color, $x, $y, ($rgb['alpha'] << 24) | ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue']);
}
}
}
$image_src = $this->imagetransfer($true_color, $image_src);
imagealphablending($image_src, false);
imagesavealpha($image_src, true);
$this->image_is_palette = false;
}
$image_dst = & $image_src;
// auto-flip image, according to EXIF data (JPEG only)
if ($gd_version >= 2 && !empty($auto_flip)) {
$this->log .= '- auto-flip image : ' . ($auto_flip == 'v' ? 'vertical' : 'horizontal') . '<br />';
$tmp = $this->imagecreatenew($this->image_src_x, $this->image_src_y);
for ($x = 0; $x < $this->image_src_x; $x++) {
for ($y = 0; $y < $this->image_src_y; $y++){
if (strpos($auto_flip, 'v') !== false) {
imagecopy($tmp, $image_dst, $this->image_src_x - $x - 1, $y, $x, $y, 1, 1);
} else {
imagecopy($tmp, $image_dst, $x, $this->image_src_y - $y - 1, $x, $y, 1, 1);
}
}
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// auto-rotate image, according to EXIF data (JPEG only)
if ($gd_version >= 2 && is_numeric($auto_rotate)) {
if (!in_array($auto_rotate, array(0, 90, 180, 270))) $auto_rotate = 0;
if ($auto_rotate != 0) {
if ($auto_rotate == 90 || $auto_rotate == 270) {
$tmp = $this->imagecreatenew($this->image_src_y, $this->image_src_x);
} else {
$tmp = $this->imagecreatenew($this->image_src_x, $this->image_src_y);
}
$this->log .= '- auto-rotate image : ' . $auto_rotate . '<br />';
for ($x = 0; $x < $this->image_src_x; $x++) {
for ($y = 0; $y < $this->image_src_y; $y++){
if ($auto_rotate == 90) {
imagecopy($tmp, $image_dst, $y, $x, $x, $this->image_src_y - $y - 1, 1, 1);
} else if ($auto_rotate == 180) {
imagecopy($tmp, $image_dst, $x, $y, $this->image_src_x - $x - 1, $this->image_src_y - $y - 1, 1, 1);
} else if ($auto_rotate == 270) {
imagecopy($tmp, $image_dst, $y, $x, $this->image_src_x - $x - 1, $y, 1, 1);
} else {
imagecopy($tmp, $image_dst, $x, $y, $x, $y, 1, 1);
}
}
}
if ($auto_rotate == 90 || $auto_rotate == 270) {
$t = $this->image_src_y;
$this->image_src_y = $this->image_src_x;
$this->image_src_x = $t;
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
}
// pre-crop image, before resizing
if ((!empty($this->image_precrop))) {
list($ct, $cr, $cb, $cl) = $this->getoffsets($this->image_precrop, $this->image_src_x, $this->image_src_y, true, true);
$this->log .= '- pre-crop image : ' . $ct . ' ' . $cr . ' ' . $cb . ' ' . $cl . ' <br />';
$this->image_src_x = $this->image_src_x - $cl - $cr;
$this->image_src_y = $this->image_src_y - $ct - $cb;
if ($this->image_src_x < 1) $this->image_src_x = 1;
if ($this->image_src_y < 1) $this->image_src_y = 1;
$tmp = $this->imagecreatenew($this->image_src_x, $this->image_src_y);
// we copy the image into the recieving image
imagecopy($tmp, $image_dst, 0, 0, $cl, $ct, $this->image_src_x, $this->image_src_y);
// if we crop with negative margins, we have to make sure the extra bits are the right color, or transparent
if ($ct < 0 || $cr < 0 || $cb < 0 || $cl < 0 ) {
// use the background color if present
if (!empty($this->image_background_color)) {
list($red, $green, $blue) = $this->getcolors($this->image_background_color);
$fill = imagecolorallocate($tmp, $red, $green, $blue);
} else {
$fill = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
}
// fills eventual negative margins
if ($ct < 0) imagefilledrectangle($tmp, 0, 0, $this->image_src_x, -$ct, $fill);
if ($cr < 0) imagefilledrectangle($tmp, $this->image_src_x + $cr, 0, $this->image_src_x, $this->image_src_y, $fill);
if ($cb < 0) imagefilledrectangle($tmp, 0, $this->image_src_y + $cb, $this->image_src_x, $this->image_src_y, $fill);
if ($cl < 0) imagefilledrectangle($tmp, 0, 0, -$cl, $this->image_src_y, $fill);
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// resize image (and move image_src_x, image_src_y dimensions into image_dst_x, image_dst_y)
if ($this->image_resize) {
$this->log .= '- resizing...<br />';
$this->image_dst_x = $this->image_x;
$this->image_dst_y = $this->image_y;
// backward compatibility for soon to be deprecated settings
if ($this->image_ratio_no_zoom_in) {
$this->image_ratio = true;
$this->image_no_enlarging = true;
} else if ($this->image_ratio_no_zoom_out) {
$this->image_ratio = true;
$this->image_no_shrinking = true;
}
// keeps aspect ratio with x calculated from y
if ($this->image_ratio_x) {
$this->log .= ' calculate x size<br />';
$this->image_dst_x = round(($this->image_src_x * $this->image_y) / $this->image_src_y);
$this->image_dst_y = $this->image_y;
// keeps aspect ratio with y calculated from x
} else if ($this->image_ratio_y) {
$this->log .= ' calculate y size<br />';
$this->image_dst_x = $this->image_x;
$this->image_dst_y = round(($this->image_src_y * $this->image_x) / $this->image_src_x);
// keeps aspect ratio, calculating x and y so that the image is approx the set number of pixels
} else if (is_numeric($this->image_ratio_pixels)) {
$this->log .= ' calculate x/y size to match a number of pixels<br />';
$pixels = $this->image_src_y * $this->image_src_x;
$diff = sqrt($this->image_ratio_pixels / $pixels);
$this->image_dst_x = round($this->image_src_x * $diff);
$this->image_dst_y = round($this->image_src_y * $diff);
// keeps aspect ratio with x and y dimensions, filling the space
} else if ($this->image_ratio_crop) {
if (!is_string($this->image_ratio_crop)) $this->image_ratio_crop = '';
$this->image_ratio_crop = strtolower($this->image_ratio_crop);
if (($this->image_src_x/$this->image_x) > ($this->image_src_y/$this->image_y)) {
$this->image_dst_y = $this->image_y;
$this->image_dst_x = intval($this->image_src_x*($this->image_y / $this->image_src_y));
$ratio_crop = array();
$ratio_crop['x'] = $this->image_dst_x - $this->image_x;
if (strpos($this->image_ratio_crop, 'l') !== false) {
$ratio_crop['l'] = 0;
$ratio_crop['r'] = $ratio_crop['x'];
} else if (strpos($this->image_ratio_crop, 'r') !== false) {
$ratio_crop['l'] = $ratio_crop['x'];
$ratio_crop['r'] = 0;
} else {
$ratio_crop['l'] = round($ratio_crop['x']/2);
$ratio_crop['r'] = $ratio_crop['x'] - $ratio_crop['l'];
}
$this->log .= ' ratio_crop_x : ' . $ratio_crop['x'] . ' (' . $ratio_crop['l'] . ';' . $ratio_crop['r'] . ')<br />';
if (is_null($this->image_crop)) $this->image_crop = array(0, 0, 0, 0);
} else {
$this->image_dst_x = $this->image_x;
$this->image_dst_y = intval($this->image_src_y*($this->image_x / $this->image_src_x));
$ratio_crop = array();
$ratio_crop['y'] = $this->image_dst_y - $this->image_y;
if (strpos($this->image_ratio_crop, 't') !== false) {
$ratio_crop['t'] = 0;
$ratio_crop['b'] = $ratio_crop['y'];
} else if (strpos($this->image_ratio_crop, 'b') !== false) {
$ratio_crop['t'] = $ratio_crop['y'];
$ratio_crop['b'] = 0;
} else {
$ratio_crop['t'] = round($ratio_crop['y']/2);
$ratio_crop['b'] = $ratio_crop['y'] - $ratio_crop['t'];
}
$this->log .= ' ratio_crop_y : ' . $ratio_crop['y'] . ' (' . $ratio_crop['t'] . ';' . $ratio_crop['b'] . ')<br />';
if (is_null($this->image_crop)) $this->image_crop = array(0, 0, 0, 0);
}
// keeps aspect ratio with x and y dimensions, fitting the image in the space, and coloring the rest
} else if ($this->image_ratio_fill) {
if (!is_string($this->image_ratio_fill)) $this->image_ratio_fill = '';
$this->image_ratio_fill = strtolower($this->image_ratio_fill);
if (($this->image_src_x/$this->image_x) < ($this->image_src_y/$this->image_y)) {
$this->image_dst_y = $this->image_y;
$this->image_dst_x = intval($this->image_src_x*($this->image_y / $this->image_src_y));
$ratio_crop = array();
$ratio_crop['x'] = $this->image_dst_x - $this->image_x;
if (strpos($this->image_ratio_fill, 'l') !== false) {
$ratio_crop['l'] = 0;
$ratio_crop['r'] = $ratio_crop['x'];
} else if (strpos($this->image_ratio_fill, 'r') !== false) {
$ratio_crop['l'] = $ratio_crop['x'];
$ratio_crop['r'] = 0;
} else {
$ratio_crop['l'] = round($ratio_crop['x']/2);
$ratio_crop['r'] = $ratio_crop['x'] - $ratio_crop['l'];
}
$this->log .= ' ratio_fill_x : ' . $ratio_crop['x'] . ' (' . $ratio_crop['l'] . ';' . $ratio_crop['r'] . ')<br />';
if (is_null($this->image_crop)) $this->image_crop = array(0, 0, 0, 0);
} else {
$this->image_dst_x = $this->image_x;
$this->image_dst_y = intval($this->image_src_y*($this->image_x / $this->image_src_x));
$ratio_crop = array();
$ratio_crop['y'] = $this->image_dst_y - $this->image_y;
if (strpos($this->image_ratio_fill, 't') !== false) {
$ratio_crop['t'] = 0;
$ratio_crop['b'] = $ratio_crop['y'];
} else if (strpos($this->image_ratio_fill, 'b') !== false) {
$ratio_crop['t'] = $ratio_crop['y'];
$ratio_crop['b'] = 0;
} else {
$ratio_crop['t'] = round($ratio_crop['y']/2);
$ratio_crop['b'] = $ratio_crop['y'] - $ratio_crop['t'];
}
$this->log .= ' ratio_fill_y : ' . $ratio_crop['y'] . ' (' . $ratio_crop['t'] . ';' . $ratio_crop['b'] . ')<br />';
if (is_null($this->image_crop)) $this->image_crop = array(0, 0, 0, 0);
}
// keeps aspect ratio with x and y dimensions
} else if ($this->image_ratio) {
if (($this->image_src_x/$this->image_x) > ($this->image_src_y/$this->image_y)) {
$this->image_dst_x = $this->image_x;
$this->image_dst_y = intval($this->image_src_y*($this->image_x / $this->image_src_x));
} else {
$this->image_dst_y = $this->image_y;
$this->image_dst_x = intval($this->image_src_x*($this->image_y / $this->image_src_y));
}
// resize to provided exact dimensions
} else {
$this->log .= ' use plain sizes<br />';
$this->image_dst_x = $this->image_x;
$this->image_dst_y = $this->image_y;
}
if ($this->image_dst_x < 1) $this->image_dst_x = 1;
if ($this->image_dst_y < 1) $this->image_dst_y = 1;
$this->log .= ' image_src_x y : ' . $this->image_src_x . ' x ' . $this->image_src_y . '<br />';
$this->log .= ' image_dst_x y : ' . $this->image_dst_x . ' x ' . $this->image_dst_y . '<br />';
// make sure we don't enlarge the image if we don't want to
if ($this->image_no_enlarging && ($this->image_src_x < $this->image_dst_x || $this->image_src_y < $this->image_dst_y)) {
$this->log .= ' cancel resizing, as it would enlarge the image!<br />';
$this->image_dst_x = $this->image_src_x;
$this->image_dst_y = $this->image_src_y;
}
// make sure we don't shrink the image if we don't want to
if ($this->image_no_shrinking && ($this->image_src_x > $this->image_dst_x || $this->image_src_y > $this->image_dst_y)) {
$this->log .= ' cancel resizing, as it would shrink the image!<br />';
$this->image_dst_x = $this->image_src_x;
$this->image_dst_y = $this->image_src_y;
}
// resize the image
if ($this->image_dst_x != $this->image_src_x && $this->image_dst_y != $this->image_src_y) {
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
if ($gd_version >= 2) {
$res = imagecopyresampled($tmp, $image_src, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_src_x, $this->image_src_y);
} else {
$res = imagecopyresized($tmp, $image_src, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_src_x, $this->image_src_y);
}
$this->log .= ' resized image object created<br />';
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
} else {
$this->image_dst_x = $this->image_src_x;
$this->image_dst_y = $this->image_src_y;
}
// crop image (and also crops if image_ratio_crop is used)
if ((!empty($this->image_crop) || !is_null($ratio_crop))) {
list($ct, $cr, $cb, $cl) = $this->getoffsets($this->image_crop, $this->image_dst_x, $this->image_dst_y, true, true);
// we adjust the cropping if we use image_ratio_crop
if (!is_null($ratio_crop)) {
if (array_key_exists('t', $ratio_crop)) $ct += $ratio_crop['t'];
if (array_key_exists('r', $ratio_crop)) $cr += $ratio_crop['r'];
if (array_key_exists('b', $ratio_crop)) $cb += $ratio_crop['b'];
if (array_key_exists('l', $ratio_crop)) $cl += $ratio_crop['l'];
}
$this->log .= '- crop image : ' . $ct . ' ' . $cr . ' ' . $cb . ' ' . $cl . ' <br />';
$this->image_dst_x = $this->image_dst_x - $cl - $cr;
$this->image_dst_y = $this->image_dst_y - $ct - $cb;
if ($this->image_dst_x < 1) $this->image_dst_x = 1;
if ($this->image_dst_y < 1) $this->image_dst_y = 1;
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
// we copy the image into the recieving image
imagecopy($tmp, $image_dst, 0, 0, $cl, $ct, $this->image_dst_x, $this->image_dst_y);
// if we crop with negative margins, we have to make sure the extra bits are the right color, or transparent
if ($ct < 0 || $cr < 0 || $cb < 0 || $cl < 0 ) {
// use the background color if present
if (!empty($this->image_background_color)) {
list($red, $green, $blue) = $this->getcolors($this->image_background_color);
$fill = imagecolorallocate($tmp, $red, $green, $blue);
} else {
$fill = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
}
// fills eventual negative margins
if ($ct < 0) imagefilledrectangle($tmp, 0, 0, $this->image_dst_x, -$ct-1, $fill);
if ($cr < 0) imagefilledrectangle($tmp, $this->image_dst_x + $cr, 0, $this->image_dst_x, $this->image_dst_y, $fill);
if ($cb < 0) imagefilledrectangle($tmp, 0, $this->image_dst_y + $cb, $this->image_dst_x, $this->image_dst_y, $fill);
if ($cl < 0) imagefilledrectangle($tmp, 0, 0, -$cl-1, $this->image_dst_y, $fill);
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// flip image
if ($gd_version >= 2 && !empty($this->image_flip)) {
$this->image_flip = strtolower($this->image_flip);
$this->log .= '- flip image : ' . $this->image_flip . '<br />';
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++){
if (strpos($this->image_flip, 'v') !== false) {
imagecopy($tmp, $image_dst, $this->image_dst_x - $x - 1, $y, $x, $y, 1, 1);
} else {
imagecopy($tmp, $image_dst, $x, $this->image_dst_y - $y - 1, $x, $y, 1, 1);
}
}
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// rotate image
if ($gd_version >= 2 && is_numeric($this->image_rotate)) {
if (!in_array($this->image_rotate, array(0, 90, 180, 270))) $this->image_rotate = 0;
if ($this->image_rotate != 0) {
if ($this->image_rotate == 90 || $this->image_rotate == 270) {
$tmp = $this->imagecreatenew($this->image_dst_y, $this->image_dst_x);
} else {
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
}
$this->log .= '- rotate image : ' . $this->image_rotate . '<br />';
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++){
if ($this->image_rotate == 90) {
imagecopy($tmp, $image_dst, $y, $x, $x, $this->image_dst_y - $y - 1, 1, 1);
} else if ($this->image_rotate == 180) {
imagecopy($tmp, $image_dst, $x, $y, $this->image_dst_x - $x - 1, $this->image_dst_y - $y - 1, 1, 1);
} else if ($this->image_rotate == 270) {
imagecopy($tmp, $image_dst, $y, $x, $this->image_dst_x - $x - 1, $y, 1, 1);
} else {
imagecopy($tmp, $image_dst, $x, $y, $x, $y, 1, 1);
}
}
}
if ($this->image_rotate == 90 || $this->image_rotate == 270) {
$t = $this->image_dst_y;
$this->image_dst_y = $this->image_dst_x;
$this->image_dst_x = $t;
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
}
// pixelate image
if ((is_numeric($this->image_pixelate) && $this->image_pixelate > 0)) {
$this->log .= '- pixelate image (' . $this->image_pixelate . 'px)<br />';
$filter = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
if ($gd_version >= 2) {
imagecopyresampled($filter, $image_dst, 0, 0, 0, 0, round($this->image_dst_x / $this->image_pixelate), round($this->image_dst_y / $this->image_pixelate), $this->image_dst_x, $this->image_dst_y);
imagecopyresampled($image_dst, $filter, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, round($this->image_dst_x / $this->image_pixelate), round($this->image_dst_y / $this->image_pixelate));
} else {
imagecopyresized($filter, $image_dst, 0, 0, 0, 0, round($this->image_dst_x / $this->image_pixelate), round($this->image_dst_y / $this->image_pixelate), $this->image_dst_x, $this->image_dst_y);
imagecopyresized($image_dst, $filter, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, round($this->image_dst_x / $this->image_pixelate), round($this->image_dst_y / $this->image_pixelate));
}
imagedestroy($filter);
}
// unsharp mask
if ($gd_version >= 2 && $this->image_unsharp && is_numeric($this->image_unsharp_amount) && is_numeric($this->image_unsharp_radius) && is_numeric($this->image_unsharp_threshold)) {
// Unsharp Mask for PHP - version 2.1.1
// Unsharp mask algorithm by Torstein Hønsi 2003-07.
// Used with permission
// Modified to support alpha transparency
if ($this->image_unsharp_amount > 500) $this->image_unsharp_amount = 500;
$this->image_unsharp_amount = $this->image_unsharp_amount * 0.016;
if ($this->image_unsharp_radius > 50) $this->image_unsharp_radius = 50;
$this->image_unsharp_radius = $this->image_unsharp_radius * 2;
if ($this->image_unsharp_threshold > 255) $this->image_unsharp_threshold = 255;
$this->image_unsharp_radius = abs(round($this->image_unsharp_radius));
if ($this->image_unsharp_radius != 0) {
$this->image_dst_x = imagesx($image_dst); $this->image_dst_y = imagesy($image_dst);
$canvas = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y, false, true);
$blur = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y, false, true);
if ($this->function_enabled('imageconvolution')) { // PHP >= 5.1
$matrix = array(array( 1, 2, 1 ), array( 2, 4, 2 ), array( 1, 2, 1 ));
imagecopy($blur, $image_dst, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y);
imageconvolution($blur, $matrix, 16, 0);
} else {
for ($i = 0; $i < $this->image_unsharp_radius; $i++) {
imagecopy($blur, $image_dst, 0, 0, 1, 0, $this->image_dst_x - 1, $this->image_dst_y); // left
$this->imagecopymergealpha($blur, $image_dst, 1, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, 50); // right
$this->imagecopymergealpha($blur, $image_dst, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, 50); // center
imagecopy($canvas, $blur, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y);
$this->imagecopymergealpha($blur, $canvas, 0, 0, 0, 1, $this->image_dst_x, $this->image_dst_y - 1, 33.33333 ); // up
$this->imagecopymergealpha($blur, $canvas, 0, 1, 0, 0, $this->image_dst_x, $this->image_dst_y, 25); // down
}
}
$p_new = array();
if($this->image_unsharp_threshold>0) {
for ($x = 0; $x < $this->image_dst_x-1; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
$p_orig = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$p_blur = imagecolorsforindex($blur, imagecolorat($blur, $x, $y));
$p_new['red'] = (abs($p_orig['red'] - $p_blur['red']) >= $this->image_unsharp_threshold) ? max(0, min(255, ($this->image_unsharp_amount * ($p_orig['red'] - $p_blur['red'])) + $p_orig['red'])) : $p_orig['red'];
$p_new['green'] = (abs($p_orig['green'] - $p_blur['green']) >= $this->image_unsharp_threshold) ? max(0, min(255, ($this->image_unsharp_amount * ($p_orig['green'] - $p_blur['green'])) + $p_orig['green'])) : $p_orig['green'];
$p_new['blue'] = (abs($p_orig['blue'] - $p_blur['blue']) >= $this->image_unsharp_threshold) ? max(0, min(255, ($this->image_unsharp_amount * ($p_orig['blue'] - $p_blur['blue'])) + $p_orig['blue'])) : $p_orig['blue'];
if (($p_orig['red'] != $p_new['red']) || ($p_orig['green'] != $p_new['green']) || ($p_orig['blue'] != $p_new['blue'])) {
$color = imagecolorallocatealpha($image_dst, $p_new['red'], $p_new['green'], $p_new['blue'], $p_orig['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
}
}
}
} else {
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
$p_orig = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$p_blur = imagecolorsforindex($blur, imagecolorat($blur, $x, $y));
$p_new['red'] = ($this->image_unsharp_amount * ($p_orig['red'] - $p_blur['red'])) + $p_orig['red'];
if ($p_new['red']>255) { $p_new['red']=255; } elseif ($p_new['red']<0) { $p_new['red']=0; }
$p_new['green'] = ($this->image_unsharp_amount * ($p_orig['green'] - $p_blur['green'])) + $p_orig['green'];
if ($p_new['green']>255) { $p_new['green']=255; } elseif ($p_new['green']<0) { $p_new['green']=0; }
$p_new['blue'] = ($this->image_unsharp_amount * ($p_orig['blue'] - $p_blur['blue'])) + $p_orig['blue'];
if ($p_new['blue']>255) { $p_new['blue']=255; } elseif ($p_new['blue']<0) { $p_new['blue']=0; }
$color = imagecolorallocatealpha($image_dst, $p_new['red'], $p_new['green'], $p_new['blue'], $p_orig['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
}
}
}
imagedestroy($canvas);
imagedestroy($blur);
}
}
// add color overlay
if ($gd_version >= 2 && (is_numeric($this->image_overlay_opacity) && $this->image_overlay_opacity > 0 && !empty($this->image_overlay_color))) {
$this->log .= '- apply color overlay<br />';
list($red, $green, $blue) = $this->getcolors($this->image_overlay_color);
$filter = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y);
$color = imagecolorallocate($filter, $red, $green, $blue);
imagefilledrectangle($filter, 0, 0, $this->image_dst_x, $this->image_dst_y, $color);
$this->imagecopymergealpha($image_dst, $filter, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_overlay_opacity);
imagedestroy($filter);
}
// add brightness, contrast and tint, turns to greyscale and inverts colors
if ($gd_version >= 2 && ($this->image_negative || $this->image_greyscale || is_numeric($this->image_threshold)|| is_numeric($this->image_brightness) || is_numeric($this->image_contrast) || !empty($this->image_tint_color))) {
$this->log .= '- apply tint, light, contrast correction, negative, greyscale and threshold<br />';
if (!empty($this->image_tint_color)) list($tint_red, $tint_green, $tint_blue) = $this->getcolors($this->image_tint_color);
//imagealphablending($image_dst, true);
for($y=0; $y < $this->image_dst_y; $y++) {
for($x=0; $x < $this->image_dst_x; $x++) {
if ($this->image_greyscale) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$r = $g = $b = round((0.2125 * $pixel['red']) + (0.7154 * $pixel['green']) + (0.0721 * $pixel['blue']));
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
if (is_numeric($this->image_threshold)) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$c = (round($pixel['red'] + $pixel['green'] + $pixel['blue']) / 3) - 127;
$r = $g = $b = ($c > $this->image_threshold ? 255 : 0);
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
if (is_numeric($this->image_brightness)) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$r = max(min(round($pixel['red'] + (($this->image_brightness * 2))), 255), 0);
$g = max(min(round($pixel['green'] + (($this->image_brightness * 2))), 255), 0);
$b = max(min(round($pixel['blue'] + (($this->image_brightness * 2))), 255), 0);
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
if (is_numeric($this->image_contrast)) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$r = max(min(round(($this->image_contrast + 128) * $pixel['red'] / 128), 255), 0);
$g = max(min(round(($this->image_contrast + 128) * $pixel['green'] / 128), 255), 0);
$b = max(min(round(($this->image_contrast + 128) * $pixel['blue'] / 128), 255), 0);
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
if (!empty($this->image_tint_color)) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$r = min(round($tint_red * $pixel['red'] / 169), 255);
$g = min(round($tint_green * $pixel['green'] / 169), 255);
$b = min(round($tint_blue * $pixel['blue'] / 169), 255);
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
if (!empty($this->image_negative)) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$r = round(255 - $pixel['red']);
$g = round(255 - $pixel['green']);
$b = round(255 - $pixel['blue']);
$color = imagecolorallocatealpha($image_dst, $r, $g, $b, $pixel['alpha']);
imagesetpixel($image_dst, $x, $y, $color);
unset($color); unset($pixel);
}
}
}
}
// adds a border
if ($gd_version >= 2 && !empty($this->image_border)) {
list($ct, $cr, $cb, $cl) = $this->getoffsets($this->image_border, $this->image_dst_x, $this->image_dst_y, true, false);
$this->log .= '- add border : ' . $ct . ' ' . $cr . ' ' . $cb . ' ' . $cl . '<br />';
$this->image_dst_x = $this->image_dst_x + $cl + $cr;
$this->image_dst_y = $this->image_dst_y + $ct + $cb;
if (!empty($this->image_border_color)) list($red, $green, $blue) = $this->getcolors($this->image_border_color);
$opacity = (is_numeric($this->image_border_opacity) ? (int) (127 - $this->image_border_opacity / 100 * 127): 0);
// we now create an image, that we fill with the border color
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
$background = imagecolorallocatealpha($tmp, $red, $green, $blue, $opacity);
imagefilledrectangle($tmp, 0, 0, $this->image_dst_x, $this->image_dst_y, $background);
// we then copy the source image into the new image, without merging so that only the border is actually kept
imagecopy($tmp, $image_dst, $cl, $ct, 0, 0, $this->image_dst_x - $cr - $cl, $this->image_dst_y - $cb - $ct);
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// adds a fading-to-transparent border
if ($gd_version >= 2 && !empty($this->image_border_transparent)) {
list($ct, $cr, $cb, $cl) = $this->getoffsets($this->image_border_transparent, $this->image_dst_x, $this->image_dst_y, true, false);
$this->log .= '- add transparent border : ' . $ct . ' ' . $cr . ' ' . $cb . ' ' . $cl . '<br />';
// we now create an image, that we fill with the border color
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
// we then copy the source image into the new image, without the borders
imagecopy($tmp, $image_dst, $cl, $ct, $cl, $ct, $this->image_dst_x - $cr - $cl, $this->image_dst_y - $cb - $ct);
// we now add the top border
$opacity = 100;
for ($y = $ct - 1; $y >= 0; $y--) {
$il = (int) ($ct > 0 ? ($cl * ($y / $ct)) : 0);
$ir = (int) ($ct > 0 ? ($cr * ($y / $ct)) : 0);
for ($x = $il; $x < $this->image_dst_x - $ir; $x++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = (1 - ($pixel['alpha'] / 127)) * $opacity / 100;
if ($alpha > 0) {
if ($alpha > 1) $alpha = 1;
$color = imagecolorallocatealpha($tmp, $pixel['red'] , $pixel['green'], $pixel['blue'], round((1 - $alpha) * 127));
imagesetpixel($tmp, $x, $y, $color);
}
}
if ($opacity > 0) $opacity = $opacity - (100 / $ct);
}
// we now add the right border
$opacity = 100;
for ($x = $this->image_dst_x - $cr; $x < $this->image_dst_x; $x++) {
$it = (int) ($cr > 0 ? ($ct * (($this->image_dst_x - $x - 1) / $cr)) : 0);
$ib = (int) ($cr > 0 ? ($cb * (($this->image_dst_x - $x - 1) / $cr)) : 0);
for ($y = $it; $y < $this->image_dst_y - $ib; $y++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = (1 - ($pixel['alpha'] / 127)) * $opacity / 100;
if ($alpha > 0) {
if ($alpha > 1) $alpha = 1;
$color = imagecolorallocatealpha($tmp, $pixel['red'] , $pixel['green'], $pixel['blue'], round((1 - $alpha) * 127));
imagesetpixel($tmp, $x, $y, $color);
}
}
if ($opacity > 0) $opacity = $opacity - (100 / $cr);
}
// we now add the bottom border
$opacity = 100;
for ($y = $this->image_dst_y - $cb; $y < $this->image_dst_y; $y++) {
$il = (int) ($cb > 0 ? ($cl * (($this->image_dst_y - $y - 1) / $cb)) : 0);
$ir = (int) ($cb > 0 ? ($cr * (($this->image_dst_y - $y - 1) / $cb)) : 0);
for ($x = $il; $x < $this->image_dst_x - $ir; $x++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = (1 - ($pixel['alpha'] / 127)) * $opacity / 100;
if ($alpha > 0) {
if ($alpha > 1) $alpha = 1;
$color = imagecolorallocatealpha($tmp, $pixel['red'] , $pixel['green'], $pixel['blue'], round((1 - $alpha) * 127));
imagesetpixel($tmp, $x, $y, $color);
}
}
if ($opacity > 0) $opacity = $opacity - (100 / $cb);
}
// we now add the left border
$opacity = 100;
for ($x = $cl - 1; $x >= 0; $x--) {
$it = (int) ($cl > 0 ? ($ct * ($x / $cl)) : 0);
$ib = (int) ($cl > 0 ? ($cb * ($x / $cl)) : 0);
for ($y = $it; $y < $this->image_dst_y - $ib; $y++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = (1 - ($pixel['alpha'] / 127)) * $opacity / 100;
if ($alpha > 0) {
if ($alpha > 1) $alpha = 1;
$color = imagecolorallocatealpha($tmp, $pixel['red'] , $pixel['green'], $pixel['blue'], round((1 - $alpha) * 127));
imagesetpixel($tmp, $x, $y, $color);
}
}
if ($opacity > 0) $opacity = $opacity - (100 / $cl);
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// add frame border
if ($gd_version >= 2 && is_numeric($this->image_frame)) {
if (is_array($this->image_frame_colors)) {
$vars = $this->image_frame_colors;
$this->log .= '- add frame : ' . implode(' ', $this->image_frame_colors) . '<br />';
} else {
$this->log .= '- add frame : ' . $this->image_frame_colors . '<br />';
$vars = explode(' ', $this->image_frame_colors);
}
$nb = sizeof($vars);
$this->image_dst_x = $this->image_dst_x + ($nb * 2);
$this->image_dst_y = $this->image_dst_y + ($nb * 2);
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
imagecopy($tmp, $image_dst, $nb, $nb, 0, 0, $this->image_dst_x - ($nb * 2), $this->image_dst_y - ($nb * 2));
$opacity = (is_numeric($this->image_frame_opacity) ? (int) (127 - $this->image_frame_opacity / 100 * 127): 0);
for ($i=0; $i<$nb; $i++) {
list($red, $green, $blue) = $this->getcolors($vars[$i]);
$c = imagecolorallocatealpha($tmp, $red, $green, $blue, $opacity);
if ($this->image_frame == 1) {
imageline($tmp, $i, $i, $this->image_dst_x - $i -1, $i, $c);
imageline($tmp, $this->image_dst_x - $i -1, $this->image_dst_y - $i -1, $this->image_dst_x - $i -1, $i, $c);
imageline($tmp, $this->image_dst_x - $i -1, $this->image_dst_y - $i -1, $i, $this->image_dst_y - $i -1, $c);
imageline($tmp, $i, $i, $i, $this->image_dst_y - $i -1, $c);
} else {
imageline($tmp, $i, $i, $this->image_dst_x - $i -1, $i, $c);
imageline($tmp, $this->image_dst_x - $nb + $i, $this->image_dst_y - $nb + $i, $this->image_dst_x - $nb + $i, $nb - $i, $c);
imageline($tmp, $this->image_dst_x - $nb + $i, $this->image_dst_y - $nb + $i, $nb - $i, $this->image_dst_y - $nb + $i, $c);
imageline($tmp, $i, $i, $i, $this->image_dst_y - $i -1, $c);
}
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// add bevel border
if ($gd_version >= 2 && $this->image_bevel > 0) {
if (empty($this->image_bevel_color1)) $this->image_bevel_color1 = '#FFFFFF';
if (empty($this->image_bevel_color2)) $this->image_bevel_color2 = '#000000';
list($red1, $green1, $blue1) = $this->getcolors($this->image_bevel_color1);
list($red2, $green2, $blue2) = $this->getcolors($this->image_bevel_color2);
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y);
imagecopy($tmp, $image_dst, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y);
imagealphablending($tmp, true);
for ($i=0; $i<$this->image_bevel; $i++) {
$alpha = round(($i / $this->image_bevel) * 127);
$c1 = imagecolorallocatealpha($tmp, $red1, $green1, $blue1, $alpha);
$c2 = imagecolorallocatealpha($tmp, $red2, $green2, $blue2, $alpha);
imageline($tmp, $i, $i, $this->image_dst_x - $i -1, $i, $c1);
imageline($tmp, $this->image_dst_x - $i -1, $this->image_dst_y - $i, $this->image_dst_x - $i -1, $i, $c2);
imageline($tmp, $this->image_dst_x - $i -1, $this->image_dst_y - $i -1, $i, $this->image_dst_y - $i -1, $c2);
imageline($tmp, $i, $i, $i, $this->image_dst_y - $i -1, $c1);
}
// we transfert tmp into image_dst
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// add watermark image
if ($this->image_watermark!='' && file_exists($this->image_watermark)) {
$this->log .= '- add watermark<br />';
$this->image_watermark_position = strtolower($this->image_watermark_position);
$watermark_info = getimagesize($this->image_watermark);
$watermark_type = (array_key_exists(2, $watermark_info) ? $watermark_info[2] : null); // 1 = GIF, 2 = JPG, 3 = PNG
$watermark_checked = false;
if ($watermark_type == IMAGETYPE_GIF) {
if (!$this->function_enabled('imagecreatefromgif')) {
$this->error = $this->translate('watermark_no_create_support', array('GIF'));
} else {
$filter = @imagecreatefromgif($this->image_watermark);
if (!$filter) {
$this->error = $this->translate('watermark_create_error', array('GIF'));
} else {
$this->log .= ' watermark source image is GIF<br />';
$watermark_checked = true;
}
}
} else if ($watermark_type == IMAGETYPE_JPEG) {
if (!$this->function_enabled('imagecreatefromjpeg')) {
$this->error = $this->translate('watermark_no_create_support', array('JPEG'));
} else {
$filter = @imagecreatefromjpeg($this->image_watermark);
if (!$filter) {
$this->error = $this->translate('watermark_create_error', array('JPEG'));
} else {
$this->log .= ' watermark source image is JPEG<br />';
$watermark_checked = true;
}
}
} else if ($watermark_type == IMAGETYPE_PNG) {
if (!$this->function_enabled('imagecreatefrompng')) {
$this->error = $this->translate('watermark_no_create_support', array('PNG'));
} else {
$filter = @imagecreatefrompng($this->image_watermark);
if (!$filter) {
$this->error = $this->translate('watermark_create_error', array('PNG'));
} else {
$this->log .= ' watermark source image is PNG<br />';
$watermark_checked = true;
}
}
} else if ($watermark_type == IMAGETYPE_BMP) {
if (!method_exists($this, 'imagecreatefrombmp')) {
$this->error = $this->translate('watermark_no_create_support', array('BMP'));
} else {
$filter = @$this->imagecreatefrombmp($this->image_watermark);
if (!$filter) {
$this->error = $this->translate('watermark_create_error', array('BMP'));
} else {
$this->log .= ' watermark source image is BMP<br />';
$watermark_checked = true;
}
}
} else {
$this->error = $this->translate('watermark_invalid');
}
if ($watermark_checked) {
$watermark_dst_width = $watermark_src_width = imagesx($filter);
$watermark_dst_height = $watermark_src_height = imagesy($filter);
// if watermark is too large/tall, resize it first
if ((!$this->image_watermark_no_zoom_out && ($watermark_dst_width > $this->image_dst_x || $watermark_dst_height > $this->image_dst_y))
|| (!$this->image_watermark_no_zoom_in && $watermark_dst_width < $this->image_dst_x && $watermark_dst_height < $this->image_dst_y)) {
$canvas_width = $this->image_dst_x - abs($this->image_watermark_x);
$canvas_height = $this->image_dst_y - abs($this->image_watermark_y);
if (($watermark_src_width/$canvas_width) > ($watermark_src_height/$canvas_height)) {
$watermark_dst_width = $canvas_width;
$watermark_dst_height = intval($watermark_src_height*($canvas_width / $watermark_src_width));
} else {
$watermark_dst_height = $canvas_height;
$watermark_dst_width = intval($watermark_src_width*($canvas_height / $watermark_src_height));
}
$this->log .= ' watermark resized from '.$watermark_src_width.'x'.$watermark_src_height.' to '.$watermark_dst_width.'x'.$watermark_dst_height.'<br />';
}
// determine watermark position
$watermark_x = 0;
$watermark_y = 0;
if (is_numeric($this->image_watermark_x)) {
if ($this->image_watermark_x < 0) {
$watermark_x = $this->image_dst_x - $watermark_dst_width + $this->image_watermark_x;
} else {
$watermark_x = $this->image_watermark_x;
}
} else {
if (strpos($this->image_watermark_position, 'r') !== false) {
$watermark_x = $this->image_dst_x - $watermark_dst_width;
} else if (strpos($this->image_watermark_position, 'l') !== false) {
$watermark_x = 0;
} else {
$watermark_x = ($this->image_dst_x - $watermark_dst_width) / 2;
}
}
if (is_numeric($this->image_watermark_y)) {
if ($this->image_watermark_y < 0) {
$watermark_y = $this->image_dst_y - $watermark_dst_height + $this->image_watermark_y;
} else {
$watermark_y = $this->image_watermark_y;
}
} else {
if (strpos($this->image_watermark_position, 'b') !== false) {
$watermark_y = $this->image_dst_y - $watermark_dst_height;
} else if (strpos($this->image_watermark_position, 't') !== false) {
$watermark_y = 0;
} else {
$watermark_y = ($this->image_dst_y - $watermark_dst_height) / 2;
}
}
imagealphablending($image_dst, true);
imagecopyresampled($image_dst, $filter, $watermark_x, $watermark_y, 0, 0, $watermark_dst_width, $watermark_dst_height, $watermark_src_width, $watermark_src_height);
} else {
$this->error = $this->translate('watermark_invalid');
}
}
// add text
if (!empty($this->image_text)) {
$this->log .= '- add text<br />';
// calculate sizes in human readable format
$src_size = $this->file_src_size / 1024;
$src_size_mb = number_format($src_size / 1024, 1, ".", " ");
$src_size_kb = number_format($src_size, 1, ".", " ");
$src_size_human = ($src_size > 1024 ? $src_size_mb . " MB" : $src_size_kb . " kb");
$this->image_text = str_replace(
array('[src_name]',
'[src_name_body]',
'[src_name_ext]',
'[src_pathname]',
'[src_mime]',
'[src_size]',
'[src_size_kb]',
'[src_size_mb]',
'[src_size_human]',
'[src_x]',
'[src_y]',
'[src_pixels]',
'[src_type]',
'[src_bits]',
'[dst_path]',
'[dst_name_body]',
'[dst_name_ext]',
'[dst_name]',
'[dst_pathname]',
'[dst_x]',
'[dst_y]',
'[date]',
'[time]',
'[host]',
'[server]',
'[ip]',
'[gd_version]'),
array($this->file_src_name,
$this->file_src_name_body,
$this->file_src_name_ext,
$this->file_src_pathname,
$this->file_src_mime,
$this->file_src_size,
$src_size_kb,
$src_size_mb,
$src_size_human,
$this->image_src_x,
$this->image_src_y,
$this->image_src_pixels,
$this->image_src_type,
$this->image_src_bits,
$this->file_dst_path,
$this->file_dst_name_body,
$this->file_dst_name_ext,
$this->file_dst_name,
$this->file_dst_pathname,
$this->image_dst_x,
$this->image_dst_y,
date('Y-m-d'),
date('H:i:s'),
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'n/a'),
(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'n/a'),
(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'n/a'),
$this->gdversion(true)),
$this->image_text);
if (!is_numeric($this->image_text_padding)) $this->image_text_padding = 0;
if (!is_numeric($this->image_text_line_spacing)) $this->image_text_line_spacing = 0;
if (!is_numeric($this->image_text_padding_x)) $this->image_text_padding_x = $this->image_text_padding;
if (!is_numeric($this->image_text_padding_y)) $this->image_text_padding_y = $this->image_text_padding;
$this->image_text_position = strtolower($this->image_text_position);
$this->image_text_direction = strtolower($this->image_text_direction);
$this->image_text_alignment = strtolower($this->image_text_alignment);
$font_type = 'gd';
// if the font is a string with a GDF font path, we assume that we might want to load a font
if (!is_numeric($this->image_text_font) && strlen($this->image_text_font) > 4 && substr(strtolower($this->image_text_font), -4) == '.gdf') {
if (strpos($this->image_text_font, '/') === false) $this->image_text_font = "./" . $this->image_text_font;
$this->log .= ' try to load font ' . $this->image_text_font . '... ';
if ($this->image_text_font = @imageloadfont($this->image_text_font)) {
$this->log .= 'success<br />';
} else {
$this->log .= 'error<br />';
$this->image_text_font = 5;
}
}
// if the font is a string with a TTF font path, we check if we can access the font file
if (!is_numeric($this->image_text_font) && strlen($this->image_text_font) > 4 && substr(strtolower($this->image_text_font), -4) == '.ttf') {
$this->log .= ' try to load font ' . $this->image_text_font . '... ';
if (strpos($this->image_text_font, '/') === false) $this->image_text_font = "./" . $this->image_text_font;
if (file_exists($this->image_text_font) && is_readable($this->image_text_font)) {
$this->log .= 'success<br />';
$font_type = 'tt';
} else {
$this->log .= 'error<br />';
$this->image_text_font = 5;
}
}
// get the text bounding box (GD fonts)
if ($font_type == 'gd') {
$text = explode("\n", $this->image_text);
$char_width = imagefontwidth($this->image_text_font);
$char_height = imagefontheight($this->image_text_font);
$text_height = 0;
$text_width = 0;
$line_height = 0;
$line_width = 0;
foreach ($text as $k => $v) {
if ($this->image_text_direction == 'v') {
$h = ($char_width * strlen($v));
if ($h > $text_height) $text_height = $h;
$line_width = $char_height;
$text_width += $line_width + ($k < (sizeof($text)-1) ? $this->image_text_line_spacing : 0);
} else {
$w = ($char_width * strlen($v));
if ($w > $text_width) $text_width = $w;
$line_height = $char_height;
$text_height += $line_height + ($k < (sizeof($text)-1) ? $this->image_text_line_spacing : 0);
}
}
$text_width += (2 * $this->image_text_padding_x);
$text_height += (2 * $this->image_text_padding_y);
// get the text bounding box (TrueType fonts)
} else if ($font_type == 'tt') {
$text = $this->image_text;
if (!$this->image_text_angle) $this->image_text_angle = $this->image_text_direction == 'v' ? 90 : 0;
$text_height = 0;
$text_width = 0;
$text_offset_x = 0;
$text_offset_y = 0;
$rect = imagettfbbox($this->image_text_size, $this->image_text_angle, $this->image_text_font, $text );
if ($rect) {
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
$text_offset_x = abs($minX) - 1;
$text_offset_y = abs($minY) - 1;
$text_width = $maxX - $minX + (2 * $this->image_text_padding_x);
$text_height = $maxY - $minY + (2 * $this->image_text_padding_y);
}
}
// position the text block
$text_x = 0;
$text_y = 0;
if (is_numeric($this->image_text_x)) {
if ($this->image_text_x < 0) {
$text_x = $this->image_dst_x - $text_width + $this->image_text_x;
} else {
$text_x = $this->image_text_x;
}
} else {
if (strpos($this->image_text_position, 'r') !== false) {
$text_x = $this->image_dst_x - $text_width;
} else if (strpos($this->image_text_position, 'l') !== false) {
$text_x = 0;
} else {
$text_x = ($this->image_dst_x - $text_width) / 2;
}
}
if (is_numeric($this->image_text_y)) {
if ($this->image_text_y < 0) {
$text_y = $this->image_dst_y - $text_height + $this->image_text_y;
} else {
$text_y = $this->image_text_y;
}
} else {
if (strpos($this->image_text_position, 'b') !== false) {
$text_y = $this->image_dst_y - $text_height;
} else if (strpos($this->image_text_position, 't') !== false) {
$text_y = 0;
} else {
$text_y = ($this->image_dst_y - $text_height) / 2;
}
}
// add a background, maybe transparent
if (!empty($this->image_text_background)) {
list($red, $green, $blue) = $this->getcolors($this->image_text_background);
if ($gd_version >= 2 && (is_numeric($this->image_text_background_opacity)) && $this->image_text_background_opacity >= 0 && $this->image_text_background_opacity <= 100) {
$filter = imagecreatetruecolor($text_width, $text_height);
$background_color = imagecolorallocate($filter, $red, $green, $blue);
imagefilledrectangle($filter, 0, 0, $text_width, $text_height, $background_color);
$this->imagecopymergealpha($image_dst, $filter, $text_x, $text_y, 0, 0, $text_width, $text_height, $this->image_text_background_opacity);
imagedestroy($filter);
} else {
$background_color = imagecolorallocate($image_dst ,$red, $green, $blue);
imagefilledrectangle($image_dst, $text_x, $text_y, $text_x + $text_width, $text_y + $text_height, $background_color);
}
}
$text_x += $this->image_text_padding_x;
$text_y += $this->image_text_padding_y;
$t_width = $text_width - (2 * $this->image_text_padding_x);
$t_height = $text_height - (2 * $this->image_text_padding_y);
list($red, $green, $blue) = $this->getcolors($this->image_text_color);
// add the text, maybe transparent
if ($gd_version >= 2 && (is_numeric($this->image_text_opacity)) && $this->image_text_opacity >= 0 && $this->image_text_opacity <= 100) {
if ($t_width < 0) $t_width = 0;
if ($t_height < 0) $t_height = 0;
$filter = $this->imagecreatenew($t_width, $t_height, false, true);
$text_color = imagecolorallocate($filter ,$red, $green, $blue);
if ($font_type == 'gd') {
foreach ($text as $k => $v) {
if ($this->image_text_direction == 'v') {
imagestringup($filter,
$this->image_text_font,
$k * ($line_width + ($k > 0 && $k < (sizeof($text)) ? $this->image_text_line_spacing : 0)),
$text_height - (2 * $this->image_text_padding_y) - ($this->image_text_alignment == 'l' ? 0 : (($t_height - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2))) ,
$v,
$text_color);
} else {
imagestring($filter,
$this->image_text_font,
($this->image_text_alignment == 'l' ? 0 : (($t_width - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2))),
$k * ($line_height + ($k > 0 && $k < (sizeof($text)) ? $this->image_text_line_spacing : 0)),
$v,
$text_color);
}
}
} else if ($font_type == 'tt') {
imagettftext($filter,
$this->image_text_size,
$this->image_text_angle,
$text_offset_x,
$text_offset_y,
$text_color,
$this->image_text_font,
$text);
}
$this->imagecopymergealpha($image_dst, $filter, $text_x, $text_y, 0, 0, $t_width, $t_height, $this->image_text_opacity);
imagedestroy($filter);
} else {
$text_color = imagecolorallocate($image_dst ,$red, $green, $blue);
if ($font_type == 'gd') {
foreach ($text as $k => $v) {
if ($this->image_text_direction == 'v') {
imagestringup($image_dst,
$this->image_text_font,
$text_x + $k * ($line_width + ($k > 0 && $k < (sizeof($text)) ? $this->image_text_line_spacing : 0)),
$text_y + $text_height - (2 * $this->image_text_padding_y) - ($this->image_text_alignment == 'l' ? 0 : (($t_height - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2))),
$v,
$text_color);
} else {
imagestring($image_dst,
$this->image_text_font,
$text_x + ($this->image_text_alignment == 'l' ? 0 : (($t_width - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2))),
$text_y + $k * ($line_height + ($k > 0 && $k < (sizeof($text)) ? $this->image_text_line_spacing : 0)),
$v,
$text_color);
}
}
} else if ($font_type == 'tt') {
imagettftext($image_dst,
$this->image_text_size,
$this->image_text_angle,
$text_offset_x + ($this->image_dst_x / 2) - ($text_width / 2) + $this->image_text_padding_x,
$text_offset_y + ($this->image_dst_y / 2) - ($text_height / 2) + $this->image_text_padding_y,
$text_color,
$this->image_text_font,
$text);
}
}
}
// add a reflection
if ($this->image_reflection_height) {
$this->log .= '- add reflection : ' . $this->image_reflection_height . '<br />';
// we decode image_reflection_height, which can be a integer, a string in pixels or percentage
$image_reflection_height = $this->image_reflection_height;
if (strpos($image_reflection_height, '%')>0) $image_reflection_height = $this->image_dst_y * (str_replace('%','',$image_reflection_height / 100));
if (strpos($image_reflection_height, 'px')>0) $image_reflection_height = str_replace('px','',$image_reflection_height);
$image_reflection_height = (int) $image_reflection_height;
if ($image_reflection_height > $this->image_dst_y) $image_reflection_height = $this->image_dst_y;
if (empty($this->image_reflection_opacity)) $this->image_reflection_opacity = 60;
// create the new destination image
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y + $image_reflection_height + $this->image_reflection_space, true);
$transparency = $this->image_reflection_opacity;
// copy the original image
imagecopy($tmp, $image_dst, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y + ($this->image_reflection_space < 0 ? $this->image_reflection_space : 0));
// we have to make sure the extra bit is the right color, or transparent
if ($image_reflection_height + $this->image_reflection_space > 0) {
// use the background color if present
if (!empty($this->image_background_color)) {
list($red, $green, $blue) = $this->getcolors($this->image_background_color);
$fill = imagecolorallocate($tmp, $red, $green, $blue);
} else {
$fill = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
}
// fill in from the edge of the extra bit
imagefill($tmp, round($this->image_dst_x / 2), $this->image_dst_y + $image_reflection_height + $this->image_reflection_space - 1, $fill);
}
// copy the reflection
for ($y = 0; $y < $image_reflection_height; $y++) {
for ($x = 0; $x < $this->image_dst_x; $x++) {
$pixel_b = imagecolorsforindex($tmp, imagecolorat($tmp, $x, $y + $this->image_dst_y + $this->image_reflection_space));
$pixel_o = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $this->image_dst_y - $y - 1 + ($this->image_reflection_space < 0 ? $this->image_reflection_space : 0)));
$alpha_o = 1 - ($pixel_o['alpha'] / 127);
$alpha_b = 1 - ($pixel_b['alpha'] / 127);
$opacity = $alpha_o * $transparency / 100;
if ($opacity > 0) {
$red = round((($pixel_o['red'] * $opacity) + ($pixel_b['red'] ) * $alpha_b) / ($alpha_b + $opacity));
$green = round((($pixel_o['green'] * $opacity) + ($pixel_b['green']) * $alpha_b) / ($alpha_b + $opacity));
$blue = round((($pixel_o['blue'] * $opacity) + ($pixel_b['blue'] ) * $alpha_b) / ($alpha_b + $opacity));
$alpha = ($opacity + $alpha_b);
if ($alpha > 1) $alpha = 1;
$alpha = round((1 - $alpha) * 127);
$color = imagecolorallocatealpha($tmp, $red, $green, $blue, $alpha);
imagesetpixel($tmp, $x, $y + $this->image_dst_y + $this->image_reflection_space, $color);
}
}
if ($transparency > 0) $transparency = $transparency - ($this->image_reflection_opacity / $image_reflection_height);
}
// copy the resulting image into the destination image
$this->image_dst_y = $this->image_dst_y + $image_reflection_height + $this->image_reflection_space;
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// change opacity
if ($gd_version >= 2 && is_numeric($this->image_opacity) && $this->image_opacity < 100) {
$this->log .= '- change opacity<br />';
// create the new destination image
$tmp = $this->imagecreatenew($this->image_dst_x, $this->image_dst_y, true);
for($y=0; $y < $this->image_dst_y; $y++) {
for($x=0; $x < $this->image_dst_x; $x++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = $pixel['alpha'] + round((127 - $pixel['alpha']) * (100 - $this->image_opacity) / 100);
if ($alpha > 127) $alpha = 127;
if ($alpha > 0) {
$color = imagecolorallocatealpha($tmp, $pixel['red'] , $pixel['green'], $pixel['blue'], $alpha);
imagesetpixel($tmp, $x, $y, $color);
}
}
}
// copy the resulting image into the destination image
$image_dst = $this->imagetransfer($tmp, $image_dst);
}
// reduce the JPEG image to a set desired size
if (is_numeric($this->jpeg_size) && $this->jpeg_size > 0 && ($this->image_convert == 'jpeg' || $this->image_convert == 'jpg')) {
// inspired by: JPEGReducer class version 1, 25 November 2004, Author: Huda M ElMatsani, justhuda at netscape dot net
$this->log .= '- JPEG desired file size : ' . $this->jpeg_size . '<br />';
// calculate size of each image. 75%, 50%, and 25% quality
ob_start(); imagejpeg($image_dst,null,75); $buffer = ob_get_contents(); ob_end_clean();
$size75 = strlen($buffer);
ob_start(); imagejpeg($image_dst,null,50); $buffer = ob_get_contents(); ob_end_clean();
$size50 = strlen($buffer);
ob_start(); imagejpeg($image_dst,null,25); $buffer = ob_get_contents(); ob_end_clean();
$size25 = strlen($buffer);
// make sure we won't divide by 0
if ($size50 == $size25) $size50++;
if ($size75 == $size50 || $size75 == $size25) $size75++;
// calculate gradient of size reduction by quality
$mgrad1 = 25 / ($size50-$size25);
$mgrad2 = 25 / ($size75-$size50);
$mgrad3 = 50 / ($size75-$size25);
$mgrad = ($mgrad1 + $mgrad2 + $mgrad3) / 3;
// result of approx. quality factor for expected size
$q_factor = round($mgrad * ($this->jpeg_size - $size50) + 50);
if ($q_factor<1) {
$this->jpeg_quality=1;
} elseif ($q_factor>100) {
$this->jpeg_quality=100;
} else {
$this->jpeg_quality=$q_factor;
}
$this->log .= ' JPEG quality factor set to ' . $this->jpeg_quality . '<br />';
}
// converts image from true color, and fix transparency if needed
$this->log .= '- converting...<br />';
$this->image_dst_type = $this->image_convert;
switch($this->image_convert) {
case 'gif':
// if the image is true color, we convert it to a palette
if (imageistruecolor($image_dst)) {
$this->log .= ' true color to palette<br />';
// creates a black and white mask
$mask = array(array());
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$mask[$x][$y] = $pixel['alpha'];
}
}
list($red, $green, $blue) = $this->getcolors($this->image_default_color);
// first, we merge the image with the background color, so we know which colors we will have
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
if ($mask[$x][$y] > 0){
// we have some transparency. we combine the color with the default color
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
$alpha = ($mask[$x][$y] / 127);
$pixel['red'] = round(($pixel['red'] * (1 -$alpha) + $red * ($alpha)));
$pixel['green'] = round(($pixel['green'] * (1 -$alpha) + $green * ($alpha)));
$pixel['blue'] = round(($pixel['blue'] * (1 -$alpha) + $blue * ($alpha)));
$color = imagecolorallocate($image_dst, $pixel['red'], $pixel['green'], $pixel['blue']);
imagesetpixel($image_dst, $x, $y, $color);
}
}
}
// transforms the true color image into palette, with its merged default color
if (empty($this->image_background_color)) {
imagetruecolortopalette($image_dst, true, 255);
$transparency = imagecolorallocate($image_dst, 254, 1, 253);
imagecolortransparent($image_dst, $transparency);
// make the transparent areas transparent
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
// we test wether we have enough opacity to justify keeping the color
if ($mask[$x][$y] > 120) imagesetpixel($image_dst, $x, $y, $transparency);
}
}
}
unset($mask);
}
break;
case 'jpg':
case 'bmp':
// if the image doesn't support any transparency, then we merge it with the default color
$this->log .= ' fills in transparency with default color<br />';
list($red, $green, $blue) = $this->getcolors($this->image_default_color);
$transparency = imagecolorallocate($image_dst, $red, $green, $blue);
// make the transaparent areas transparent
for ($x = 0; $x < $this->image_dst_x; $x++) {
for ($y = 0; $y < $this->image_dst_y; $y++) {
// we test wether we have some transparency, in which case we will merge the colors
if (imageistruecolor($image_dst)) {
$rgba = imagecolorat($image_dst, $x, $y);
$pixel = array('red' => ($rgba >> 16) & 0xFF,
'green' => ($rgba >> 8) & 0xFF,
'blue' => $rgba & 0xFF,
'alpha' => ($rgba & 0x7F000000) >> 24);
} else {
$pixel = imagecolorsforindex($image_dst, imagecolorat($image_dst, $x, $y));
}
if ($pixel['alpha'] == 127) {
// we have full transparency. we make the pixel transparent
imagesetpixel($image_dst, $x, $y, $transparency);
} else if ($pixel['alpha'] > 0) {
// we have some transparency. we combine the color with the default color
$alpha = ($pixel['alpha'] / 127);
$pixel['red'] = round(($pixel['red'] * (1 -$alpha) + $red * ($alpha)));
$pixel['green'] = round(($pixel['green'] * (1 -$alpha) + $green * ($alpha)));
$pixel['blue'] = round(($pixel['blue'] * (1 -$alpha) + $blue * ($alpha)));
$color = imagecolorclosest($image_dst, $pixel['red'], $pixel['green'], $pixel['blue']);
imagesetpixel($image_dst, $x, $y, $color);
}
}
}
break;
default:
break;
}
// interlace options
if($this->image_interlace) imageinterlace($image_dst, true);
// outputs image
$this->log .= '- saving image...<br />';
switch($this->image_convert) {
case 'jpeg':
case 'jpg':
if (!$return_mode) {
$result = @imagejpeg($image_dst, $this->file_dst_pathname, $this->jpeg_quality);
} else {
ob_start();
$result = @imagejpeg($image_dst, null, $this->jpeg_quality);
$return_content = ob_get_contents();
ob_end_clean();
}
if (!$result) {
$this->processed = false;
$this->error = $this->translate('file_create', array('JPEG'));
} else {
$this->log .= ' JPEG image created<br />';
}
break;
case 'png':
imagealphablending( $image_dst, false );
imagesavealpha( $image_dst, true );
if (!$return_mode) {
if (is_numeric($this->png_compression) && version_compare(PHP_VERSION, '5.1.2') >= 0) {
$result = @imagepng($image_dst, $this->file_dst_pathname, $this->png_compression);
} else {
$result = @imagepng($image_dst, $this->file_dst_pathname);
}
} else {
ob_start();
if (is_numeric($this->png_compression) && version_compare(PHP_VERSION, '5.1.2') >= 0) {
$result = @imagepng($image_dst, null, $this->png_compression);
} else {
$result = @imagepng($image_dst);
}
$return_content = ob_get_contents();
ob_end_clean();
}
if (!$result) {
$this->processed = false;
$this->error = $this->translate('file_create', array('PNG'));
} else {
$this->log .= ' PNG image created<br />';
}
break;
case 'gif':
if (!$return_mode) {
$result = @imagegif($image_dst, $this->file_dst_pathname);
} else {
ob_start();
$result = @imagegif($image_dst);
$return_content = ob_get_contents();
ob_end_clean();
}
if (!$result) {
$this->processed = false;
$this->error = $this->translate('file_create', array('GIF'));
} else {
$this->log .= ' GIF image created<br />';
}
break;
case 'bmp':
if (!$return_mode) {
$result = $this->imagebmp($image_dst, $this->file_dst_pathname);
} else {
ob_start();
$result = $this->imagebmp($image_dst);
$return_content = ob_get_contents();
ob_end_clean();
}
if (!$result) {
$this->processed = false;
$this->error = $this->translate('file_create', array('BMP'));
} else {
$this->log .= ' BMP image created<br />';
}
break;
default:
$this->processed = false;
$this->error = $this->translate('no_conversion_type');
}
if ($this->processed) {
if (is_resource($image_src)) imagedestroy($image_src);
if (is_resource($image_dst)) imagedestroy($image_dst);
$this->log .= ' image objects destroyed<br />';
}
}
} else {
$this->log .= '- no image processing wanted<br />';
if (!$return_mode) {
// copy the file to its final destination. we don't use move_uploaded_file here
// if we happen to have open_basedir restrictions, it is a temp file that we copy, not the original uploaded file
if (!copy($this->file_src_pathname, $this->file_dst_pathname)) {
$this->processed = false;
$this->error = $this->translate('copy_failed');
}
} else {
// returns the file, so that its content can be received by the caller
$return_content = @file_get_contents($this->file_src_pathname);
if ($return_content === FALSE) {
$this->processed = false;
$this->error = $this->translate('reading_failed');
}
}
}
}
if ($this->processed) {
$this->log .= '- <b>process OK</b><br />';
} else {
$this->log .= '- <b>error</b>: ' . $this->error . '<br />';
}
// we reinit all the vars
$this->init();
// we may return the image content
if ($return_mode) return $return_content;
}
|
Actually uploads the file, and act on it according to the set processing class variables
This function copies the uploaded file to the given location, eventually performing actions on it.
Typically, you can call {@link process} several times for the same file,
for instance to create a resized image and a thumbnail of the same file.
The original uploaded file remains intact in its temporary location, so you can use {@link process} several times.
You will be able to delete the uploaded file with {@link clean} when you have finished all your {@link process} calls.
According to the processing class variables set in the calling file, the file can be renamed,
and if it is an image, can be resized or converted.
When the processing is completed, and the file copied to its new location, the
processing class variables will be reset to their default value.
This allows you to set new properties, and perform another {@link process} on the same uploaded file
If the function is called with a null or empty argument, then it will return the content of the picture
It will set {@link processed} (and {@link error} is an error occurred)
@access public
@param string $server_path Optional path location of the uploaded file, with an ending slash
@return string Optional content of the image
|
entailment
|
function imagecreatefrombmp($filename) {
if (! $f1 = fopen($filename,"rb")) return false;
$file = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
if ($file['file_type'] != 19778) return false;
$bmp = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
$bmp['colors'] = pow(2,$bmp['bits_per_pixel']);
if ($bmp['size_bitmap'] == 0) $bmp['size_bitmap'] = $file['file_size'] - $file['bitmap_offset'];
$bmp['bytes_per_pixel'] = $bmp['bits_per_pixel']/8;
$bmp['bytes_per_pixel2'] = ceil($bmp['bytes_per_pixel']);
$bmp['decal'] = ($bmp['width']*$bmp['bytes_per_pixel']/4);
$bmp['decal'] -= floor($bmp['width']*$bmp['bytes_per_pixel']/4);
$bmp['decal'] = 4-(4*$bmp['decal']);
if ($bmp['decal'] == 4) $bmp['decal'] = 0;
$palette = array();
if ($bmp['colors'] < 16777216) {
$palette = unpack('V'.$bmp['colors'], fread($f1,$bmp['colors']*4));
}
$im = fread($f1,$bmp['size_bitmap']);
$vide = chr(0);
$res = imagecreatetruecolor($bmp['width'],$bmp['height']);
$P = 0;
$Y = $bmp['height']-1;
while ($Y >= 0) {
$X=0;
while ($X < $bmp['width']) {
if ($bmp['bits_per_pixel'] == 24)
$color = unpack("V",substr($im,$P,3).$vide);
elseif ($bmp['bits_per_pixel'] == 16) {
$color = unpack("n",substr($im,$P,2));
$color[1] = $palette[$color[1]+1];
} elseif ($bmp['bits_per_pixel'] == 8) {
$color = unpack("n",$vide.substr($im,$P,1));
$color[1] = $palette[$color[1]+1];
} elseif ($bmp['bits_per_pixel'] == 4) {
$color = unpack("n",$vide.substr($im,floor($P),1));
if (($P*2)%2 == 0) $color[1] = ($color[1] >> 4) ; else $color[1] = ($color[1] & 0x0F);
$color[1] = $palette[$color[1]+1];
} elseif ($bmp['bits_per_pixel'] == 1) {
$color = unpack("n",$vide.substr($im,floor($P),1));
if (($P*8)%8 == 0) $color[1] = $color[1] >>7;
elseif (($P*8)%8 == 1) $color[1] = ($color[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $color[1] = ($color[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $color[1] = ($color[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $color[1] = ($color[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $color[1] = ($color[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $color[1] = ($color[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $color[1] = ($color[1] & 0x1);
$color[1] = $palette[$color[1]+1];
} else
return FALSE;
imagesetpixel($res,$X,$Y,$color[1]);
$X++;
$P += $bmp['bytes_per_pixel'];
}
$Y--;
$P+=$bmp['decal'];
}
fclose($f1);
return $res;
}
|
Opens a BMP image
This function has been written by DHKold, and is used with permission of the author
@access public
|
entailment
|
public static function push($crumbs = [], $url = '')
{
if (empty($crumbs)) {
return false;
}
if (is_string($crumbs) && (is_string($url) || is_array($url))) {
// "title" and "URL" as arguments"
$crumbs = [['title' => $crumbs, 'url' => $url]];
} elseif (is_array($crumbs) && isset($crumbs['title']) && isset($crumbs['url'])) {
// Single crumb push as an array
$crumbs = [$crumbs];
}
foreach ((array)$crumbs as $crumb) {
if (isset($crumb['title']) && isset($crumb['url'])) {
static::$_crumbs[] = $crumb;
}
}
return true;
}
|
Adds a new crumb to the stack.
### Usage
#### Single crumb push as an array:
```php
BreadcrumbRegistry::push(['title' => 'Crumb 1', 'url' => 'URL for crumb 1']);
BreadcrumbRegistry::push(['title' => 'Crumb 2', 'url' => '/MyPlugin/my_controller/action_name']);
BreadcrumbRegistry::push(['title' => 'Crumb 3', 'url' => 'URL for crumb 3']);
```
#### Multiple crumbs at once:
```php
BreadcrumbRegistry::push([
['title' => 'Crumb 1', 'url' => 'URL for crumb 1'],
['title' => 'Crumb 2', 'url' => '/MyPlugin/my_controller/action_name'],
['title' => 'Crumb 3', 'url' => 'URL for crumb 3'],
]);
```
#### "title" and "URL" as arguments:
```php
BreadcrumbRegistry::push('Crumb 1', 'URL for crumb 1');
BreadcrumbRegistry::push('Crumb 2', ['plugin' => 'MyPlugin', 'controller' => 'my_controller', 'action' => 'action_name']);
BreadcrumbRegistry::push('Crumb 3', 'URL for crumb 3');
```
All three examples above produces the same HTML output when using `BreadcrumbHelper::render()`:
```html
<ol>
<li class="first-item"><a href="URL for crumb 1"><span>Crumb 1</span></a></li>
<li class="active"><a href="/MyPlugin/my_controller/action_name"><span>Crumb 2</span></a></li>
<li class="last-item"><a href="URL for crumb 3"><span>Crumb 3</span></a></li>
</ol>
```
NOTE: you can provide URLs as both, string values or as an array compatible
with `Router::url()`.
@param array|string $crumbs Single crumb or an array of multiple crumbs to
push at once
@param mixed $url If both $crumbs is a string value and $url is a string
(or an array) value they will be used as `title` and `url` respectively
@return bool True on success, False otherwise
@see \Menu\View\Helper\BreadcrumbHelper::render()
|
entailment
|
public static function getUrls()
{
$urls = [];
foreach (static::$_crumbs as $crumb) {
if (!empty($crumb['url'])) {
$urls[] = $crumb['url'];
} elseif (is_object($crumb)) {
$urls[] = $crumb->url;
}
}
return $urls;
}
|
Gets a list of all URLs.
@return array
|
entailment
|
public function beforeSave(Event $event, $entity, $options = [])
{
if ($this->_table->hasField($this->config('createdByField')) ||
$this->_table->hasField($this->config('modifiedByField'))
) {
$userId = $this->_getUserId();
if ($userId > 0) {
$entity->set($this->config('modifiedByField'), $userId);
if ($entity->isNew()) {
$entity->set($this->config('createdByField'), $userId);
}
}
}
return true;
}
|
Run before a model is saved.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Entity $entity The entity being saved
@param array $options Array of options for the save operation
@return bool True if save should proceed, false otherwise
|
entailment
|
protected function _getUserId()
{
$callable = $this->config('idCallable');
$id = 0;
if (is_string($callable)) {
$session = Session::create();
$id = $session->read($callable);
} elseif (is_callable($callable)) {
$id = $callable();
}
return (int)$id;
}
|
Gets current User's ID.
@return int User ID, zero if not found
|
entailment
|
public function index()
{
$collection = plugin()->filter(function ($plugin) {
return !$plugin->isTheme;
});
$plugins = $collection;
$enabled = count($collection->filter(function ($plugin) {
return $plugin->status;
})->toArray());
$disabled = count($collection->filter(function ($plugin) {
return !$plugin->status;
})->toArray());
$this->title(__d('system', 'Plugins'));
$this->set(compact('plugins', 'all', 'enabled', 'disabled'));
$this->_awaitingPlugins();
$this->Breadcrumb->push('/admin/system/plugins');
}
|
Main action.
@return void
|
entailment
|
public function delete($pluginName)
{
$plugin = plugin($pluginName); // throws if not exists
$task = (bool)WebShellDispatcher::run("Installer.plugins uninstall -p {$plugin->name}");
if ($task) {
$this->Flash->success(__d('system', 'Plugin was successfully removed!'));
} else {
$this->Flash->set(__d('system', 'Plugins could not be removed'), [
'element' => 'System.installer_errors',
'params' => ['errors' => WebShellDispatcher::output()],
]);
}
$this->title(__d('system', 'Uninstall Plugin'));
header('Location:' . $this->referer());
exit();
}
|
Uninstalls the given plugin.
@param string $pluginName Plugin's name
@return void Redirects to previous page
|
entailment
|
public function index()
{
$this->loadModel('Block.Blocks');
if ($this->request->isPost()) {
if ($this->_reorder()) {
$this->Flash->success(__d('block', 'Blocks ordering updated!'));
}
$this->redirect(['plugin' => 'Block', 'controller' => 'manage', 'action' => 'index']);
}
$front = $this->Blocks->inFrontTheme();
$back = $this->Blocks->inBackTheme();
$unused = $this->Blocks->unused();
$this->set(compact('front', 'back', 'unused'));
$this->title(__d('block', 'Site Blocks'));
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('block', 'Manage Blocks'), '#');
}
|
Shows a list of all the blocks & widgets.
@return void
|
entailment
|
public function add()
{
$this->loadModel('Block.Blocks');
$block = $this->Blocks->newEntity();
$block->set('region', []);
if ($this->request->data()) {
$block = $this->_patchEntity($block);
if (!$block->errors()) {
if ($this->Blocks->save($block)) {
$this->Flash->success(__d('block', 'Block created.'));
$this->redirect(['plugin' => 'Block', 'controller' => 'manage', 'action' => 'edit', $block->id]);
} else {
$this->Flash->danger(__d('block', 'Block could not be created, please check your information.'));
}
} else {
$this->Flash->danger(__d('block', 'Block could not be created, please check your information.'));
}
}
$this->_setLanguages();
$this->_setRoles();
$this->_setRegions();
$this->set('block', $block);
$this->title(__d('block', 'Create New Block'));
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('block', 'Manage Blocks'), ['plugin' => 'Block', 'controller' => 'manage', 'action' => 'index'])
->push(__d('block', 'Create New Block'), '#');
}
|
Creates a new custom block.
@return void
|
entailment
|
public function edit($id)
{
$this->loadModel('Block.Blocks');
$block = $this->Blocks->get($id, ['flatten' => true, 'contain' => ['BlockRegions', 'Roles']]);
if ($this->request->data()) {
$block->accessible('id', false);
$block->accessible('handler', false);
$block = $this->_patchEntity($block);
if (!$block->errors()) {
if ($this->Blocks->save($block)) {
$this->Flash->success(__d('block', 'Block updated!'));
$this->redirect($this->referer());
} else {
$this->Flash->success(__d('block', 'Your information could not be saved, please try again.'));
}
} else {
$this->Flash->danger(__d('block', 'Block could not be updated, please check your information.'));
}
}
$this->set(compact('block'));
$this->_setLanguages();
$this->_setRoles();
$this->_setRegions($block);
$this->title(__d('block', 'Editing Block'));
$this->Breadcrumb
->push('/admin/system/structure')
->push(__d('block', 'Manage Blocks'), ['plugin' => 'Block', 'controller' => 'manage', 'action' => 'index'])
->push(__d('block', 'Editing Block'), '#');
}
|
Edits the given block by ID.
The event `Block.<handler>.validate` will be automatically triggered,
so custom block's (those handled by plugins <> "Block") can be validated
before persisted.
@param string $id Block's ID
@return void
@throws \Cake\ORM\Exception\RecordNotFoundException if no block is not found
|
entailment
|
public function delete($id)
{
$this->loadModel('Block.Blocks');
$block = $this->Blocks->find()
->where(['id' => $id])
->first();
if ($block &&
($block->handler == 'Block' || !empty($block->copy_id))
) {
if ($this->Blocks->delete($block)) {
$this->Flash->success(__d('block', 'Block was successfully removed!'));
} else {
$this->Flash->danger(__d('block', 'Block could not be removed'));
}
} else {
$this->Flash->warning(__d('block', 'Block not found!'));
}
$this->title(__d('block', 'Delete Block'));
$this->redirect($this->referer());
}
|
Deletes the given block by ID.
Only custom blocks can be deleted (those with "Block" has handler).
@param string $id Block's ID
@return void Redirects to previous page
@throws \Cake\ORM\Exception\RecordNotFoundException if no record can be found
given a primary key value
@throws \InvalidArgumentException When $primaryKey has an incorrect number
of elements
|
entailment
|
public function duplicate($id)
{
$this->loadModel('Block.Blocks');
$original = $this->Blocks->get((int)$id);
$new = $this->Blocks->newEntity($original->toArray());
$new->set('copy_id', $original->id);
$new->unsetProperty('id');
$new->isNew(true);
if ($this->Blocks->save($new)) {
$this->Flash->success(__d('block', 'Block has been duplicated, it can be found under the "Unused or Unassigned" section.'));
} else {
$this->Flash->danger(__d('block', 'Block could not be duplicated, please try again.'));
}
$this->title(__d('block', 'Duplicate Block'));
$this->redirect($this->referer() . '#unused-blocks');
}
|
Edits the given block by ID.
@param string $id Block's ID
@return void Redirects to previous page
@throws \Cake\ORM\Exception\RecordNotFoundException if no block is not found
|
entailment
|
protected function _reorder()
{
if (!empty($this->request->data['regions'])) {
foreach ($this->request->data['regions'] as $theme => $regions) {
foreach ($regions as $region => $ids) {
$ordering = 0;
foreach ($ids as $id) {
$blockRegion = $this->Blocks
->BlockRegions
->newEntity([
'id' => $id,
'theme' => $theme,
'region' => $region,
'ordering' => $ordering
]);
$blockRegion->isNew(false);
$this->Blocks->BlockRegions->save($blockRegion);
$ordering++;
}
}
}
return true;
}
return false;
}
|
Reorders blocks based on the order provided via POST.
@return bool True on success, false otherwise
|
entailment
|
protected function _setRoles()
{
$this->loadModel('Block.Blocks');
$roles = $this->Blocks->Roles->find('list');
$this->set('roles', $roles);
}
|
Sets "roles" variable for later use in FormHelper.
@return void
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.