sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function symlinkCE($source, $targetDir, $name) { return (!$this->encoding)? $this->_symlink($source, $targetDir, $name) : $this->convEncOut($this->_symlink($this->convEncIn($source), $this->convEncIn($targetDir), $this->convEncIn($name))); }
Create symlink (with convert encording) @param string $source file to link to @param string $targetDir folder to create link in @param string $name symlink name @return bool @author Naoki Sawada
entailment
protected function encode($path) { if ($path !== '') { // cut ROOT from $path for security reason, even if hacker decodes the path he will not know the root $p = $this->relpathCE($path); // if reqesting root dir $path will be empty, then assign '/' as we cannot leave it blank for crypt if ($p === '') { $p = DIRECTORY_SEPARATOR; } // TODO crypt path and return hash $hash = $this->crypt($p); // hash is used as id in HTML that means it must contain vaild chars // make base64 html safe and append prefix in begining $hash = strtr(base64_encode($hash), '+/=', '-_.'); // remove dots '.' at the end, before it was '=' in base64 $hash = rtrim($hash, '.'); // append volume id to make hash unique return $this->id.$hash; } }
Encode path into hash @param string file path @return string @author Dmitry (dio) Levashov @author Troex Nevelin
entailment
protected function nameAccepted($name) { if ($this->nameValidator) { if (is_callable($this->nameValidator)) { $res = call_user_func($this->nameValidator, $name); return $res; } if (preg_match($this->nameValidator, '') !== false) { return preg_match($this->nameValidator, $name); } } return true; }
Validate file name based on $this->options['acceptedName'] regexp or function @param string $name file name @return bool @author Dmitry (dio) Levashov
entailment
public function convEncIn($var = null, $restoreLocale = false, $unknown = '_') { return (!$this->encoding)? $var : $this->convEnc($var, 'UTF-8', $this->encoding, $this->options['locale'], $restoreLocale, $unknown); }
Converts character encoding from UTF-8 to server's one @param mixed $var target string or array var @param bool $restoreLocale do retore global locale, default is false @param string $unknown replaces character for unknown @return mixed @author Naoki Sawada
entailment
public function convEncOut($var = null, $restoreLocale = true, $unknown = '_') { return (!$this->encoding)? $var : $this->convEnc($var, $this->encoding, 'UTF-8', $this->options['locale'], $restoreLocale, $unknown); }
Converts character encoding from server's one to UTF-8 @param mixed $var target string or array var @param bool $restoreLocale do retore global locale, default is true @param string $unknown replaces character for unknown @return mixed @author Naoki Sawada
entailment
protected function convEnc($var, $from, $to, $locale, $restoreLocale, $unknown = '_') { if (strtoupper($from) !== strtoupper($to)) { if ($locale) { @setlocale(LC_ALL, $locale); } if (is_array($var)) { $_ret = array(); foreach($var as $_k => $_v) { $_ret[$_k] = $this->convEnc($_v, $from, $to, '', false, $unknown = '_'); } $var = $_ret; } else { $_var = false; if (is_string($var)) { $_var = $var; if (false !== ($_var = @iconv($from, $to.'//TRANSLIT', $_var))) { $_var = str_replace('?', $unknown, $_var); } } if ($_var !== false) { $var = $_var; } } if ($restoreLocale) { setlocale(LC_ALL, elFinder::$locale); } } return $var; }
Converts character encoding (base function) @param mixed $var target string or array var @param string $from from character encoding @param string $to to character encoding @param string $locale local locale @param string $unknown replaces character for unknown @return mixed
entailment
protected function getTempFile($path = '') { static $cache = array(); static $rmfunc; $key = ''; if ($path !== '') { $key = $this->id . '#' . $path; if (isset($cache[$key])) { return $cache[$key]; } } if ($tmpdir = $this->getTempPath()) { if (!$rmfunc) { $rmfunc = create_function('$f', '@unlink($f);'); } $name = tempnam($tmpdir, 'ELF'); if ($key) { $cache[$key] = $name; } register_shutdown_function($rmfunc, $name); return $name; } return false; }
Get temporary filename. Tempfile will be removed when after script execution finishes or exit() is called. When needing the unique file to a path, give $path to parameter. @param string $path for get unique file to a path @return string|false @author Naoki Sawada
entailment
protected function getWorkFile($path) { if ($work = $this->getTempFile()) { if ($wfp = fopen($work, 'wb')) { if ($fp = $this->_fopen($path)) { while(!feof($fp)) { fwrite($wfp, fread($fp, 8192)); } $this->_fclose($fp, $path); fclose($wfp); return $work; } } } return false; }
File path of local server side work file path @param string $path path need convert encoding to server encoding @return string @author Naoki Sawada
entailment
public function getImageSize($path, $mime = '') { $size = false; if ($mime === '' || strtolower(substr($mime, 0, 5)) === 'image') { if ($work = $this->getWorkFile($path)) { if ($size = @getimagesize($work)) { $size['dimensions'] = $size[0].'x'.$size[1]; } } is_file($work) && @unlink($work); } return $size; }
Get image size array with `dimensions` @param string $path path need convert encoding to server encoding @param string $mime file mime type @return array|false
entailment
protected function delTree($localpath) { foreach ($this->_scandir($localpath) as $p) { @set_time_limit(30); $stat = $this->stat($this->convEncOut($p)); $this->convEncIn(); ($stat['mime'] === 'directory')? $this->delTree($p) : $this->_unlink($p); } return $this->_rmdir($localpath); }
Delete dirctory trees @param string $localpath path need convert encoding to server encoding @return boolean @author Naoki Sawada
entailment
protected function attr($path, $name, $val=null, $isDir=null) { if (!isset($this->defaults[$name])) { return false; } $perm = null; if ($this->access) { $perm = call_user_func($this->access, $name, $path, $this->options['accessControlData'], $this, $isDir); if ($perm !== null) { return !!$perm; } } if ($this->separator != '/') { $path = str_replace($this->separator, '/', $this->relpathCE($path)); } else { $path = $this->relpathCE($path); } $path = '/'.$path; for ($i = 0, $c = count($this->attributes); $i < $c; $i++) { $attrs = $this->attributes[$i]; if (isset($attrs[$name]) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $path)) { $perm = $attrs[$name]; } } return $perm === null ? (is_null($val)? $this->defaults[$name] : $val) : !!$perm; }
Check file attribute @param string $path file path @param string $name attribute name (read|write|locked|hidden) @param bool $val attribute value returned by file system @param bool $isDir path is directory (true: directory, false: file) @return bool @author Dmitry (dio) Levashov
entailment
protected function allowCreate($dir, $name, $isDir = null) { $path = $this->joinPathCE($dir, $name); $perm = null; if ($this->access) { $perm = call_user_func($this->access, 'write', $path, $this->options['accessControlData'], $this, $isDir); if ($perm !== null) { return !!$perm; } } $testPath = $this->separator.$this->relpathCE($path); for ($i = 0, $c = count($this->attributes); $i < $c; $i++) { $attrs = $this->attributes[$i]; if (isset($attrs['write']) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $testPath)) { $perm = $attrs['write']; } } return $perm === null ? true : $perm; }
Return true if file with given name can be created in given folder. @param string $dir parent dir path @param string $name new file name @return bool @author Dmitry (dio) Levashov
entailment
protected function stat($path) { if ($path === false || is_null($path)) { return false; } $is_root = ($path === $this->root); if ($is_root) { if (isset($this->sessionCache['rootstat'])) { return $this->cache[$path] = unserialize(base64_decode($this->sessionCache['rootstat'])); } } $ret = isset($this->cache[$path]) ? $this->cache[$path] : $this->updateCache($path, $this->convEncOut($this->_stat($this->convEncIn($path)))); if ($is_root) { $this->sessionCache['rootstat'] = base64_encode(serialize($ret)); } return $ret; }
Return fileinfo @param string $path file cache @return array @author Dmitry (dio) Levashov
entailment
protected function updateCache($path, $stat) { if (empty($stat) || !is_array($stat)) { return $this->cache[$path] = array(); } $stat['hash'] = $this->encode($path); $root = $path == $this->root; if ($root) { $stat['volumeid'] = $this->id; if ($this->rootName) { $stat['name'] = $this->rootName; } if (! empty($this->options['icon'])) { $stat['icon'] = $this->options['icon']; } } else { if (!isset($stat['name']) || $stat['name'] === '') { $stat['name'] = $this->basenameCE($path); } if (empty($stat['phash'])) { $stat['phash'] = $this->encode($this->dirnameCE($path)); } } // fix name if required if ($this->options['utf8fix'] && $this->options['utf8patterns'] && $this->options['utf8replace']) { $stat['name'] = json_decode(str_replace($this->options['utf8patterns'], $this->options['utf8replace'], json_encode($stat['name']))); } if (empty($stat['mime'])) { $stat['mime'] = $this->mimetype($stat['name']); } // @todo move dateformat to client // $stat['date'] = isset($stat['ts']) // ? $this->formatDate($stat['ts']) // : 'unknown'; if (!isset($stat['size'])) { $stat['size'] = 'unknown'; } $isDir = ($stat['mime'] === 'directory'); $stat['read'] = intval($this->attr($path, 'read', isset($stat['read']) ? !!$stat['read'] : null, $isDir)); $stat['write'] = intval($this->attr($path, 'write', isset($stat['write']) ? !!$stat['write'] : null, $isDir)); if ($root) { $stat['locked'] = 1; } elseif ($this->attr($path, 'locked', isset($stat['locked']) ? !!$stat['locked'] : null, $isDir)) { $stat['locked'] = 1; } else { unset($stat['locked']); } if ($root) { unset($stat['hidden']); } elseif ($this->attr($path, 'hidden', isset($stat['hidden']) ? !!$stat['hidden'] : null, $isDir) || !$this->mimeAccepted($stat['mime'])) { $stat['hidden'] = 1; } else { unset($stat['hidden']); } if ($stat['read'] && empty($stat['hidden'])) { if ($isDir) { // for dir - check for subdirs if ($this->options['checkSubfolders']) { if (isset($stat['dirs'])) { if ($stat['dirs']) { $stat['dirs'] = 1; } else { unset($stat['dirs']); } } elseif (!empty($stat['alias']) && !empty($stat['target'])) { $stat['dirs'] = isset($this->cache[$stat['target']]) ? intval(isset($this->cache[$stat['target']]['dirs'])) : $this->subdirsCE($stat['target']); } elseif ($this->subdirsCE($path)) { $stat['dirs'] = 1; } } else { $stat['dirs'] = 1; } } else { // for files - check for thumbnails $p = isset($stat['target']) ? $stat['target'] : $path; if ($this->tmbURL && !isset($stat['tmb']) && $this->canCreateTmb($p, $stat)) { $tmb = $this->gettmb($p, $stat); $stat['tmb'] = $tmb ? $tmb : 1; } } if (!isset($stat['url']) && $this->URL && $this->encoding) { $_path = str_replace($this->separator, '/', substr($path, strlen($this->root) + 1)); $stat['url'] = rtrim($this->URL, '/') . '/' . str_replace('%2F', '/', rawurlencode($this->convEncIn($_path, true))); } } if (!empty($stat['alias']) && !empty($stat['target'])) { $stat['thash'] = $this->encode($stat['target']); unset($stat['target']); } if (isset($this->options['netkey']) && $path === $this->root) { $stat['netkey'] = $this->options['netkey']; } return $this->cache[$path] = $stat; }
Put file stat in cache and return it @param string $path file path @param array $stat file stat @return array @author Dmitry (dio) Levashov
entailment
protected function cacheDir($path) { $this->dirsCache[$path] = array(); foreach ($this->scandirCE($path) as $p) { if (($stat = $this->stat($p)) && empty($stat['hidden'])) { $this->dirsCache[$path][] = $p; } } }
Get stat for folder content and put in cache @param string $path @return void @author Dmitry (dio) Levashov
entailment
protected function mimetype($path, $name = '') { $type = ''; if ($this->mimeDetect == 'finfo') { if ($type = @finfo_file($this->finfo, $path)) { if ($name === '') { $name = $path; } $ext = (false === $pos = strrpos($name, '.')) ? '' : substr($name, $pos + 1); if ($ext && preg_match('~^application/(?:octet-stream|(?:x-)?zip)~', $type)) { if (isset(elFinderVolumeDriver::$mimetypes[$ext])) $type = elFinderVolumeDriver::$mimetypes[$ext]; } } } elseif ($type == 'mime_content_type') { $type = mime_content_type($path); } else { $type = elFinderVolumeDriver::mimetypeInternalDetect($path); } $type = explode(';', $type); $type = trim($type[0]); if (in_array($type, array('application/x-empty', 'inode/x-empty'))) { // finfo return this mime for empty files $type = 'text/plain'; } elseif ($type == 'application/x-zip') { // http://elrte.org/redmine/issues/163 $type = 'application/zip'; } return $type == 'unknown' && $this->mimeDetect != 'internal' ? elFinderVolumeDriver::mimetypeInternalDetect($path) : $type; }
Return file mimetype @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function countSize($path) { $stat = $this->stat($path); if (empty($stat) || !$stat['read'] || !empty($stat['hidden'])) { return 'unknown'; } if ($stat['mime'] != 'directory') { return $stat['size']; } $subdirs = $this->options['checkSubfolders']; $this->options['checkSubfolders'] = true; $result = 0; foreach ($this->getScandir($path) as $stat) { $size = $stat['mime'] == 'directory' && $stat['read'] ? $this->countSize($this->joinPathCE($path, $stat['name'])) : (isset($stat['size']) ? intval($stat['size']) : 0); if ($size > 0) { $result += $size; } } $this->options['checkSubfolders'] = $subdirs; return $result; }
Return file/total directory size @param string $path file path @return int @author Dmitry (dio) Levashov
entailment
protected function closestByAttr($path, $attr, $val) { $stat = $this->stat($path); if (empty($stat)) { return false; } $v = isset($stat[$attr]) ? $stat[$attr] : false; if ($v == $val) { return $path; } return $stat['mime'] == 'directory' ? $this->childsByAttr($path, $attr, $val) : false; }
If file has required attr == $val - return file path, If dir has child with has required attr == $val - return child path @param string $path file path @param string $attr attribute name @param bool $val attribute value @return string|false @author Dmitry (dio) Levashov
entailment
protected function getScandir($path) { $files = array(); !isset($this->dirsCache[$path]) && $this->cacheDir($path); foreach ($this->dirsCache[$path] as $p) { if (($stat = $this->stat($p)) && empty($stat['hidden'])) { $files[] = $stat; } } return $files; }
Return required dir's files info. If onlyMimes is set - return only dirs and files of required mimes @param string $path dir path @return array @author Dmitry (dio) Levashov
entailment
protected function doSearch($path, $q, $mimes) { $result = array(); foreach($this->scandirCE($path) as $p) { @set_time_limit(30); $stat = $this->stat($p); if (!$stat) { // invalid links continue; } if (!empty($stat['hidden']) || !$this->mimeAccepted($stat['mime'])) { continue; } $name = $stat['name']; if ($this->stripos($name, $q) !== false) { $stat['path'] = $this->path($p); if ($this->URL && !isset($stat['url'])) { $path = str_replace($this->separator, '/', substr($p, strlen($this->root) + 1)); if ($this->encoding) { $path = str_replace('%2F', '/', rawurlencode($this->convEncIn($path, true))); } $stat['url'] = $this->URL . $path; } $result[] = $stat; } if ($stat['mime'] == 'directory' && $stat['read'] && !isset($stat['alias'])) { $result = array_merge($result, $this->doSearch($p, $q, $mimes)); } } return $result; }
Recursive files search @param string $path dir path @param string $q search string @param array $mimes @return array @author Dmitry (dio) Levashov
entailment
protected function copy($src, $dst, $name) { $srcStat = $this->stat($src); $this->clearcache(); if (!empty($srcStat['thash'])) { $target = $this->decode($srcStat['thash']); $stat = $this->stat($target); $this->clearcache(); return $stat && $this->symlinkCE($target, $dst, $name) ? $this->joinPathCE($dst, $name) : $this->setError(elFinder::ERROR_COPY, $this->path($src)); } if ($srcStat['mime'] == 'directory') { $test = $this->stat($this->joinPathCE($dst, $name)); if (($test && $test['mime'] != 'directory') || $this->convEncOut(!$this->_mkdir($this->convEncIn($dst), $this->convEncIn($name)))) { return $this->setError(elFinder::ERROR_COPY, $this->path($src)); } $dst = $this->joinPathCE($dst, $name); foreach ($this->getScandir($src) as $stat) { if (empty($stat['hidden'])) { $name = $stat['name']; if (!$this->copy($this->joinPathCE($src, $name), $dst, $name)) { $this->remove($dst, true); // fall back return $this->setError($this->error, elFinder::ERROR_COPY, $this->_path($src)); } } } $this->clearcache(); return $dst; } return $this->convEncOut($this->_copy($this->convEncIn($src), $this->convEncIn($dst), $this->convEncIn($name))) ? $this->joinPathCE($dst, $name) : $this->setError(elFinder::ERROR_COPY, $this->path($src)); }
Copy file/recursive copy dir only in current volume. Return new file path or false. @param string $src source path @param string $dst destination dir path @param string $name new file name (optionaly) @return string|false @author Dmitry (dio) Levashov
entailment
protected function move($src, $dst, $name) { $stat = $this->stat($src); $stat['realpath'] = $src; $this->rmTmb($stat); // can not do rmTmb() after _move() $this->clearcache(); if ($this->convEncOut($this->_move($this->convEncIn($src), $this->convEncIn($dst), $this->convEncIn($name)))) { $this->removed[] = $stat; return $this->joinPathCE($dst, $name); } return $this->setError(elFinder::ERROR_MOVE, $this->path($src)); }
Move file Return new file path or false. @param string $src source path @param string $dst destination dir path @param string $name new file name @return string|false @author Dmitry (dio) Levashov
entailment
protected function copyFrom($volume, $src, $destination, $name) { if (($source = $volume->file($src)) == false) { return $this->setError(elFinder::ERROR_COPY, '#'.$src, $volume->error()); } $errpath = $volume->path($src); if (!$this->nameAccepted($source['name'])) { return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_INVALID_NAME); } if (!$source['read']) { return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED); } if ($source['mime'] == 'directory') { $stat = $this->stat($this->joinPathCE($destination, $name)); $this->clearcache(); if ((!$stat || $stat['mime'] != 'directory') && $this->convEncOut(!$this->_mkdir($this->convEncIn($destination), $this->convEncIn($name)))) { return $this->setError(elFinder::ERROR_COPY, $errpath); } $path = $this->joinPathCE($destination, $name); foreach ($volume->scandir($src) as $entr) { if (!$this->copyFrom($volume, $entr['hash'], $path, $entr['name'])) { $this->remove($path, true); // fall back return $this->setError($this->error, elFinder::ERROR_COPY, $errpath); } } } else { // $mime = $source['mime']; // $w = $h = 0; if (($dim = $volume->dimensions($src))) { $s = explode('x', $dim); $source['width'] = $s[0]; $source['height'] = $s[1]; } if (($fp = $volume->open($src)) == false || ($path = $this->saveCE($fp, $destination, $name, $source)) == false) { $fp && $volume->close($fp, $src); return $this->setError(elFinder::ERROR_COPY, $errpath); } $volume->close($fp, $src); } return $path; }
Copy file from another volume. Return new file path or false. @param Object $volume source volume @param string $src source file hash @param string $destination destination dir path @param string $name file name @return string|false @author Dmitry (dio) Levashov
entailment
protected function remove($path, $force = false) { $stat = $this->stat($path); if (empty($stat)) { return $this->setError(elFinder::ERROR_RM, $this->path($path), elFinder::ERROR_FILE_NOT_FOUND); } $stat['realpath'] = $path; $this->rmTmb($stat); $this->clearcache(); if (!$force && !empty($stat['locked'])) { return $this->setError(elFinder::ERROR_LOCKED, $this->path($path)); } if ($stat['mime'] == 'directory') { $ret = $this->delTree($this->convEncIn($path)); $this->convEncOut(); if (!$ret) { return $this->setError(elFinder::ERROR_RM, $this->path($path)); } } else { if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) { return $this->setError(elFinder::ERROR_RM, $this->path($path)); } } $this->removed[] = $stat; return true; }
Remove file/ recursive remove dir @param string $path file path @param bool $force try to remove even if file locked @return bool @author Dmitry (dio) Levashov
entailment
protected function gettmb($path, $stat) { if ($this->tmbURL && $this->tmbPath) { // file itself thumnbnail if (strpos($path, $this->tmbPath) === 0) { return basename($path); } $name = $this->tmbname($stat); if (file_exists($this->tmbPath.DIRECTORY_SEPARATOR.$name)) { return $name; } } return false; }
Return thumnbnail name if exists @param string $path file path @param array $stat file stat @return string|false @author Dmitry (dio) Levashov
entailment
protected function imgResize($path, $width, $height, $keepProportions = false, $resizeByBiggerSide = true, $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; list($size_w, $size_h) = array($width, $height); if ($keepProportions == true) { list($orig_w, $orig_h, $new_w, $new_h) = array($s[0], $s[1], $width, $height); /* Calculating image scale width and height */ $xscale = $orig_w / $new_w; $yscale = $orig_h / $new_h; /* Resizing by biggest side */ if ($resizeByBiggerSide) { if ($orig_w > $orig_h) { $size_h = $orig_h * $width / $orig_w; $size_w = $width; } else { $size_w = $orig_w * $height / $orig_h; $size_h = $height; } } else { if ($orig_w > $orig_h) { $size_w = $orig_w * $height / $orig_h; $size_h = $height; } else { $size_h = $orig_h * $width / $orig_w; $size_w = $width; } } } switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } // Imagick::FILTER_BOX faster than FILTER_LANCZOS so use for createTmb // resize bench: http://app-mgng.rhcloud.com/9 // resize sample: http://www.dylanbeattie.net/magick/filters/result.html $filter = ($destformat === 'png' /* createTmb */)? Imagick::FILTER_BOX : Imagick::FILTER_LANCZOS; $img->resizeImage($size_w, $size_h, $filter, 1); $result = $img->writeImage($path); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path,$s['mime']); if ($img && false != ($tmp = imagecreatetruecolor($size_w, $size_h))) { self::gdImageBackground($tmp,$this->options['tmbBgColor']); if (!imagecopyresampled($tmp, $img, 0, 0, 0, 0, $size_w, $size_h, $s[0], $s[1])) { return false; } $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
Resize image @param string $path image file @param int $width new width @param int $height new height @param bool $keepProportions crop image @param bool $resizeByBiggerSide resize image based on bigger side if true @param string $destformat image destination format @return string|false @author Dmitry (dio) Levashov @author Alexey Sukhotin
entailment
protected function imgCrop($path, $width, $height, $x, $y, $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->cropImage($width, $height, $x, $y); $result = $img->writeImage($path); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path,$s['mime']); if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) { self::gdImageBackground($tmp,$this->options['tmbBgColor']); $size_w = $width; $size_h = $height; if ($s[0] < $width || $s[1] < $height) { $size_w = $s[0]; $size_h = $s[1]; } if (!imagecopy($tmp, $img, 0, 0, $x, $y, $size_w, $size_h)) { return false; } $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
Crop image @param string $path image file @param int $width crop width @param int $height crop height @param bool $x crop left offset @param bool $y crop top offset @param string $destformat image destination format @return string|false @author Dmitry (dio) Levashov @author Alexey Sukhotin
entailment
protected function imgSquareFit($path, $width, $height, $align = 'center', $valign = 'middle', $bgcolor = '#0000ff', $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; /* Coordinates for image over square aligning */ $y = ceil(abs($height - $s[1]) / 2); $x = ceil(abs($width - $s[0]) / 2); switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img1 = new Imagick(); $img1->newImage($width, $height, new ImagickPixel($bgcolor)); $img1->setImageColorspace($img->getImageColorspace()); $img1->setImageFormat($destformat != null ? $destformat : $img->getFormat()); $img1->compositeImage( $img, imagick::COMPOSITE_OVER, $x, $y ); $result = $img1->writeImage($path); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path,$s['mime']); if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) { self::gdImageBackground($tmp,$bgcolor); if (!imagecopy($tmp, $img, $x, $y, 0, 0, $s[0], $s[1])) { return false; } $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
Put image to square @param string $path image file @param int $width square width @param int $height square height @param int $align reserved @param int $valign reserved @param string $bgcolor square background color in #rrggbb format @param string $destformat image destination format @return string|false @author Dmitry (dio) Levashov @author Alexey Sukhotin
entailment
protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->rotateImage(new ImagickPixel($bgcolor), $degree); $result = $img->writeImage($path); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path,$s['mime']); $degree = 360 - $degree; list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x"); $bgcolor = imagecolorallocate($img, $r, $g, $b); $tmp = imageRotate($img, $degree, (int)$bgcolor); $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imageDestroy($img); imageDestroy($tmp); return $result ? $path : false; break; } return false; }
Rotate image @param string $path image file @param int $degree rotete degrees @param string $bgcolor square background color in #rrggbb format @param string $destformat image destination format @return string|false @author nao-pon @author Troex Nevelin
entailment
protected function procExec($command , array &$output = null, &$return_var = -1, array &$error_output = null) { $descriptorspec = array( 0 => array("pipe", "r"), // stdin 1 => array("pipe", "w"), // stdout 2 => array("pipe", "w") // stderr ); $process = proc_open($command, $descriptorspec, $pipes, null, null); if (is_resource($process)) { fclose($pipes[0]); $tmpout = ''; $tmperr = ''; $output = stream_get_contents($pipes[1]); $error_output = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $return_var = proc_close($process); } return $return_var; }
Execute shell command @param string $command command line @param array $output stdout strings @param array $return_var process exit code @param array $error_output stderr strings @return int exit code @author Alexey Sukhotin
entailment
protected function rmTmb($stat) { if ($stat['mime'] === 'directory') { foreach ($this->scandirCE($this->decode($stat['hash'])) as $p) { @set_time_limit(30); $name = $this->basenameCE($p); $name != '.' && $name != '..' && $this->rmTmb($this->stat($p)); } } else if (!empty($stat['tmb']) && $stat['tmb'] != "1") { $tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$stat['tmb']; file_exists($tmb) && @unlink($tmb); clearstatcache(); } }
Remove thumbnail, also remove recursively if stat is directory @param string $stat file stat @return void @author Dmitry (dio) Levashov @author Naoki Sawada @author Troex Nevelin
entailment
protected function gdImageCreate($path,$mime){ switch($mime){ case 'image/jpeg': return imagecreatefromjpeg($path); case 'image/png': return imagecreatefrompng($path); case 'image/gif': return imagecreatefromgif($path); case 'image/xbm': return imagecreatefromxbm($path); } return false; }
Create an gd image according to the specified mime type @param string $path image file @param string $mime @return gd image resource identifier
entailment
protected function gdImage($image, $filename, $destformat, $mime ){ if ($destformat == 'jpg' || ($destformat == null && $mime == 'image/jpeg')) { return imagejpeg($image, $filename, 100); } if ($destformat == 'gif' || ($destformat == null && $mime == 'image/gif')) { return imagegif($image, $filename, 7); } return imagepng($image, $filename, 7); }
Output gd image to file @param resource $image gd image resource @param string $filename The path to save the file to. @param string $destformat The Image type to use for $filename @param string $mime The original image mime type
entailment
protected function gdImageBackground($image, $bgcolor){ if( $bgcolor == 'transparent' ){ imagesavealpha($image,true); $bgcolor1 = imagecolorallocatealpha($image, 255, 255, 255, 127); }else{ list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x"); $bgcolor1 = imagecolorallocate($image, $r, $g, $b); } imagefill($image, 0, 0, $bgcolor1); }
Assign the proper background to a gd image @param resource $image gd image resource @param string $bgcolor background color in #rrggbb format
entailment
protected function stripos($haystack , $needle , $offset = 0) { if (function_exists('mb_stripos')) { return mb_stripos($haystack , $needle , $offset); } else if (function_exists('mb_strtolower') && function_exists('mb_strpos')) { return mb_strpos(mb_strtolower($haystack), mb_strtolower($needle), $offset); } return stripos($haystack , $needle , $offset); }
Find position of first occurrence of string in a string with multibyte support @param string $haystack The string being checked. @param string $needle The string to find in haystack. @param int $offset The search offset. If it is not specified, 0 is used. @return int|bool @author Alexey Sukhotin
entailment
protected function getArchivers($use_cache = true) { $arcs = array( 'create' => array(), 'extract' => array() ); if (!function_exists('proc_open')) { return $arcs; } $sessionKey = elFinder::$sessionCacheKey . ':ARCHIVERS_CACHE'; if ($use_cache && isset($_SESSION[$sessionKey]) && is_array($_SESSION[$sessionKey])) { return $_SESSION[$sessionKey]; } $this->procExec('tar --version', $o, $ctar); if ($ctar == 0) { $arcs['create']['application/x-tar'] = array('cmd' => 'tar', 'argc' => '-cf', 'ext' => 'tar'); $arcs['extract']['application/x-tar'] = array('cmd' => 'tar', 'argc' => '-xf', 'ext' => 'tar'); unset($o); $test = $this->procExec('gzip --version', $o, $c); if ($c == 0) { $arcs['create']['application/x-gzip'] = array('cmd' => 'tar', 'argc' => '-czf', 'ext' => 'tgz'); $arcs['extract']['application/x-gzip'] = array('cmd' => 'tar', 'argc' => '-xzf', 'ext' => 'tgz'); } unset($o); $test = $this->procExec('bzip2 --version', $o, $c); if ($c == 0) { $arcs['create']['application/x-bzip2'] = array('cmd' => 'tar', 'argc' => '-cjf', 'ext' => 'tbz'); $arcs['extract']['application/x-bzip2'] = array('cmd' => 'tar', 'argc' => '-xjf', 'ext' => 'tbz'); } unset($o); $test = $this->procExec('xz --version', $o, $c); if ($c == 0) { $arcs['create']['application/x-xz'] = array('cmd' => 'tar', 'argc' => '-cJf', 'ext' => 'xz'); $arcs['extract']['application/x-xz'] = array('cmd' => 'tar', 'argc' => '-xJf', 'ext' => 'xz'); } } unset($o); $this->procExec('zip -v', $o, $c); if ($c == 0) { $arcs['create']['application/zip'] = array('cmd' => 'zip', 'argc' => '-r9', 'ext' => 'zip'); } unset($o); $this->procExec('unzip --help', $o, $c); if ($c == 0) { $arcs['extract']['application/zip'] = array('cmd' => 'unzip', 'argc' => '', 'ext' => 'zip'); } unset($o); $this->procExec('rar --version', $o, $c); if ($c == 0 || $c == 7) { $arcs['create']['application/x-rar'] = array('cmd' => 'rar', 'argc' => 'a -inul', 'ext' => 'rar'); $arcs['extract']['application/x-rar'] = array('cmd' => 'rar', 'argc' => 'x -y', 'ext' => 'rar'); } else { unset($o); $test = $this->procExec('unrar', $o, $c); if ($c==0 || $c == 7) { $arcs['extract']['application/x-rar'] = array('cmd' => 'unrar', 'argc' => 'x -y', 'ext' => 'rar'); } } unset($o); $this->procExec('7za --help', $o, $c); if ($c == 0) { $arcs['create']['application/x-7z-compressed'] = array('cmd' => '7za', 'argc' => 'a', 'ext' => '7z'); $arcs['extract']['application/x-7z-compressed'] = array('cmd' => '7za', 'argc' => 'x -y', 'ext' => '7z'); if (empty($arcs['create']['application/zip'])) { $arcs['create']['application/zip'] = array('cmd' => '7za', 'argc' => 'a -tzip', 'ext' => 'zip'); } if (empty($arcs['extract']['application/zip'])) { $arcs['extract']['application/zip'] = array('cmd' => '7za', 'argc' => 'x -tzip -y', 'ext' => 'zip'); } if (empty($arcs['create']['application/x-tar'])) { $arcs['create']['application/x-tar'] = array('cmd' => '7za', 'argc' => 'a -ttar', 'ext' => 'tar'); } if (empty($arcs['extract']['application/x-tar'])) { $arcs['extract']['application/x-tar'] = array('cmd' => '7za', 'argc' => 'x -ttar -y', 'ext' => 'tar'); } } else if (substr(PHP_OS,0,3) === 'WIN') { // check `7z` for Windows server. unset($o); $this->procExec('7z', $o, $c); if ($c == 0) { $arcs['create']['application/x-7z-compressed'] = array('cmd' => '7z', 'argc' => 'a', 'ext' => '7z'); $arcs['extract']['application/x-7z-compressed'] = array('cmd' => '7z', 'argc' => 'x -y', 'ext' => '7z'); if (empty($arcs['create']['application/zip'])) { $arcs['create']['application/zip'] = array('cmd' => '7z', 'argc' => 'a -tzip', 'ext' => 'zip'); } if (empty($arcs['extract']['application/zip'])) { $arcs['extract']['application/zip'] = array('cmd' => '7z', 'argc' => 'x -tzip -y', 'ext' => 'zip'); } if (empty($arcs['create']['application/x-tar'])) { $arcs['create']['application/x-tar'] = array('cmd' => '7z', 'argc' => 'a -ttar', 'ext' => 'tar'); } if (empty($arcs['extract']['application/x-tar'])) { $arcs['extract']['application/x-tar'] = array('cmd' => '7z', 'argc' => 'x -ttar -y', 'ext' => 'tar'); } } } $_SESSION[$sessionKey] = $arcs; return $arcs; }
Get server side available archivers @param bool $use_cache @return array
entailment
public function rmdirRecursive($dir) { if (is_dir($dir)) { foreach (array_diff(scandir($dir), array('.', '..')) as $file) { @set_time_limit(30); $path = $dir . '/' . $file; (is_dir($path)) ? $this->rmdirRecursive($path) : @unlink($path); } return @rmdir($dir); } else if (is_file($dir)) { return @unlink($dir); } return false; }
Remove directory recursive on local file system @param string $dir Target dirctory path @return boolean @author Naoki Sawada
entailment
public function render(Field $field, View $view) { $value = TextToolbox::process($field->value, $field->metadata->settings['text_processing']); $field->set('value', $value); return $view->element('Field.TextField/display', compact('field')); }
{@inheritDoc}
entailment
public function validate(Field $field, Validator $validator) { if ($field->metadata->required) { $validator ->requirePresence($field->name, __d('field', 'This field required.')) ->add($field->name, 'notEmpty', [ 'rule' => function ($value, $context) use ($field) { if ($field->metadata->settings['type'] === 'textarea') { $clean = html_entity_decode(trim(strip_tags($value))); } else { $clean = trim(strip_tags($value)); } return !empty($clean); }, 'message' => __d('field', 'This field cannot be left empty.'), ]); } else { $validator->allowEmpty($field->name, true); } if ($field->metadata->settings['type'] === 'text' && !empty($field->metadata->settings['max_len']) && $field->metadata->settings['max_len'] > 0 ) { $validator ->add($field->name, 'validateLen', [ 'rule' => function ($value, $context) use ($field) { return strlen(trim($value)) <= $field->metadata->settings['max_len']; }, 'message' => __d('field', 'Max. {0,number} characters length.', $field->metadata->settings['max_len']), ]); } if (!empty($field->metadata->settings['validation_rule'])) { if (!empty($field->metadata->settings['validation_message'])) { $message = $this->shortcodes($field->metadata->settings['validation_message']); } else { $message = __d('field', 'Invalid field.', $field->label); } $validator ->add($field->name, 'validateReg', [ 'rule' => function ($value, $context) use ($field) { return preg_match($field->metadata->settings['validation_rule'], $value) === 1; }, 'message' => $message, ]); } return true; }
{@inheritDoc}
entailment
public function beforeSave(Field $field, $post) { $field->set('extra', null); $field->set('value', $post); }
{@inheritDoc}
entailment
public function validateViewModeSettings(FieldInstance $instance, array $settings, Validator $validator, $viewMode) { if (!empty($settings['formatter']) && $settings['formatter'] == 'trimmed') { $validator ->requirePresence('trim_length', __d('field', 'Invalid trimmer string.')) ->notEmpty('trim_length', __d('field', 'Invalid trimmer string.')); } }
{@inheritDoc}
entailment
public function versionCompare($a, $b, $operator, $compareBranches = false) { $aIsBranch = 'dev-' === substr($a, 0, 4); $bIsBranch = 'dev-' === substr($b, 0, 4); if ($aIsBranch && $bIsBranch) { return $operator == '==' && $a === $b; } // when branches are not comparable, we make sure dev branches never match anything if (!$compareBranches && ($aIsBranch || $bIsBranch)) { return false; } return version_compare($a, $b, $operator); }
{@inheritDoc}
entailment
public static function formatter($view, $field) { $out = ''; $viewModeSettings = $field->viewModeSettings; foreach ((array)$field->extra as $image) { if (!empty($image['file_name'])) { $img = ''; $originalURL = normalizePath("/files/{$field->metadata->settings['upload_folder']}/{$image['file_name']}", '/'); $imageOptions = []; foreach (['title', 'alt'] as $attr) { if (!empty($field->metadata->settings["{$attr}_attr"]) && !empty($image[$attr])) { $imageOptions[$attr] = h($image[$attr]); } } if ($viewModeSettings['size']) { $thumbnail = static::thumbnail(normalizePath(WWW_ROOT . "/files/{$field->metadata->settings['upload_folder']}/{$image['file_name']}"), $viewModeSettings['size']); if ($thumbnail !== false) { $thumbnail = basename($thumbnail); $img = $view->Html->image(normalizePath("/files/{$field->metadata->settings['upload_folder']}/.tmb/{$thumbnail}", '/'), $imageOptions); } } else { $img = $view->Html->image($originalURL, $imageOptions); } if ($img) { switch ($viewModeSettings['link_type']) { case 'content': $entityURL = $field->metadata->entity->get('url'); if ($entityURL) { $out .= $view->Html->link($img, $entityURL, ['escape' => false]); } else { $out .= $img; } break; case 'file': $out .= $view->Html->link($img, $originalURL, ['escape' => false, 'target' => '_blank']); break; default: $out .= $img; break; } } } } return $out; }
Renders the given field instance. When using the `Link to content` option, entities must define the "url" property, and it should return a valid URL for that entity. @param \Cake\View\View $view Instance of view class @param \Field\Model\Entity\Field $field Field instance to render @return string HTML
entailment
public static function thumbnail($filePath, $previewSize) { $filePath = normalizePath($filePath); if (!is_readable($filePath)) { return false; } $srcFileName = basename($filePath); $srcPath = dirname($filePath) . DS; $dstPath = normalizePath("{$srcPath}/.tmb/"); $previewInfo = static::getPreviews($previewSize); require_once Plugin::classPath('Field') . 'Lib/class.upload.php'; $handle = new \upload($srcPath . $srcFileName); if (empty($previewInfo)) { $previews = static::getPreviews(); $previewInfo = reset($previews); } $dstFileNameBody = static::removeExt("{$previewInfo['width']}x{$previewInfo['height']}_{$srcFileName}"); $dstFilePath = normalizePath("{$dstPath}/{$dstFileNameBody}.jpg"); if (is_readable($dstFilePath)) { return $dstFilePath; } $handle->image_x = $previewInfo['width']; $handle->image_y = $previewInfo['height']; $handle->image_resize = true; $handle->image_ratio = false; $handle->image_ratio_crop = true; $handle->image_convert = 'jpg'; $handle->file_new_name_body = $dstFileNameBody; $handle->process($dstPath); if (empty($handle->error)) { return $handle->file_dst_pathname; } return false; }
Creates a thumbnail for the given image. @param string $filePath Full path to original image file @param string $previewSize A valid preview preset @return false|string Full path to thumbnail file on success, false otherwise
entailment
public static function previewsOptions() { static::_initPreviews(); $options = []; foreach (static::$_previews as $value => $info) { $options[$value] = $info['label']; } return $options; }
Returns an array list of available previews modes suitable for select boxes. @return array
entailment
public static function getPreviews($slug = null) { static::_initPreviews(); if ($slug !== null) { if (isset(static::$_previews[$slug])) { return static::$_previews[$slug]; } return []; } return static::$_previews; }
Gets all defined previews, or information for an specific preview. @param string $slug Slug of the preview for which get its info, set to null will retrieve info for all registered previews @return array
entailment
public static function addPreview($slug, $label, $width, $height) { static::_initPreviews(); static::$_previews[$slug] = [ 'label' => $label, 'width' => $width, 'height' => $height, ]; }
Defines a new preview configuration or overwrite if exists. @param string $slug Unique machine-name. e.g.: `my-preview-mode` @param string $label Human-readable name. e.g.: `My preview mode` @param int $width Width for images that would use this preview mode @param int $height Height for images that would use this preview mode @return void
entailment
public static function delete($imagePath) { $imagePath = normalizePath($imagePath); if (is_readable($imagePath)) { $original = new File($imagePath); static::deleteThumbnails($imagePath); $original->delete(); } }
Deletes the given image and all its thumbnails. @param string $imagePath Full path to image file @return void
entailment
public static function deleteThumbnails($imagePath) { $imagePath = normalizePath("{$imagePath}/"); $fileName = basename($imagePath); $tmbPath = normalizePath(dirname($imagePath) . '/.tmb/'); $folder = new Folder($tmbPath); $pattern = preg_quote(static::removeExt($fileName)); foreach ($folder->find(".*{$pattern}.*") as $tn) { $tn = new File($tmbPath . $tn); $tn->delete(); } }
Delete image's thumbnails if exists. @param string $imagePath Full path to original image file @return void
entailment
public function menu($id) { $this->loadModel('Menu.Menus'); $menu = $this->Menus->get($id); $links = $this->Menus->MenuLinks->find() ->where(['menu_id' => $menu->id]) ->order(['lft' => 'ASC']) ->all() ->map(function ($link) { $link->set('expanded', true); return $link; }) ->nest('id', 'parent_id'); if (!empty($this->request->data['tree_order'])) { $items = json_decode($this->request->data['tree_order']); if (!empty($items)) { unset($items[0]); $entities = []; foreach ($items as $key => $item) { $link = $this->Menus->MenuLinks->get($item->item_id); $link = $this->Menus->MenuLinks->patchEntity($link, [ 'parent_id' => intval($item->parent_id), 'lft' => intval(($item->left - 1)), 'rght' => intval(($item->right - 1)), ], ['validate' => false]); $entities[] = $link; } $this->Menus->MenuLinks->connection()->transactional(function () use ($entities) { foreach ($entities as $entity) { $result = $this->Menus->MenuLinks->save($entity); if (!$result) { return false; } } return true; }); // don't trust "left" and "right" values coming from user's POST $this->Menus->MenuLinks->addBehavior('Tree', ['scope' => ['menu_id' => $menu->id]]); $this->Menus->MenuLinks->recover(); $this->Flash->success(__d('menu', 'Menu has been reordered')); } else { $this->Flash->danger(__d('menu', 'Invalid information, check you have JavaScript enabled')); } $this->redirect($this->referer()); } $disabledIds = $links ->match(['status' => false]) ->extract('id') ->toArray(); $this->title(__d('menu', 'Menu’s Links')); $this->set(compact('menu', 'links', 'disabledIds')); $this->Breadcrumb ->push('/admin/menu/manage') ->push(__d('menu', 'Editing menu'), ['plugin' => 'Menu', 'controller' => 'manage', 'action' => 'edit', $menu->id]) ->push(__d('menu', 'Links'), '#'); }
Shows menu's links as a sortable tree. @param int $id Menu's ID for which render its links tree @return void
entailment
public function add($menuId) { $this->loadModel('Menu.Menus'); $this->loadModel('Content.Contents'); $menu = $this->Menus->get($menuId); $link = $this->Menus->MenuLinks->newEntity(); $link->set([ 'activation' => 'auto', 'status' => 1, 'menu_id' => $menuId ]); $this->Menus->MenuLinks->addBehavior('Tree', [ 'scope' => ['menu_id' => $menu->id] ]); if ($this->request->data()) { $link = $this->Menus->MenuLinks->patchEntity($link, $this->request->data, [ 'fieldList' => [ 'parent_id', 'title', 'url', 'description', 'target', 'expanded', 'active', 'activation', 'status' ] ]); if ($this->Menus->MenuLinks->save($link)) { $this->Menus->MenuLinks->recover(); $this->Flash->success(__d('menu', 'Link successfully created!')); if (!empty($this->request->data['action_add'])) { $this->redirect(['plugin' => 'Menu', 'controller' => 'links', 'action' => 'add', $menuId]); } elseif (!empty($this->request->data['action_menu'])) { $this->redirect(['plugin' => 'Menu', 'controller' => 'links', 'action' => 'menu', $menuId]); } } else { $this->Flash->danger(__d('menu', 'Link could not be saved, please check your information')); } } $contentLinks = []; $contents = $this->Contents ->find() ->select(['id', 'slug', 'content_type_slug', 'title']) ->all(); foreach ($contents as $content) { $contentLinks[stripLanguagePrefix($content->get('url'))] = __d('menu', '{0} [{1}]', [ $content->title, $content->content_type_slug ]); } $parentsTree = $this->Menus->MenuLinks ->find('treeList', ['spacer' => '--']) ->map(function ($link) { if (strpos($link, '-') !== false) { $link = str_replace_last('-', '- ', $link); } return $link; }); $this->title(__d('menu', 'Create New Link')); $this->set(compact('menu', 'link', 'contentLinks', 'parentsTree')); $this->Breadcrumb ->push('/admin/menu/manage') ->push(__d('menu', 'Editing menu "{0}"', $menu->title), ['plugin' => 'Menu', 'controller' => 'manage', 'action' => 'edit', $menuId]) ->push(__d('menu', 'Links'), ['plugin' => 'Menu', 'controller' => 'links', 'action' => 'menu', $menuId]) ->push(__d('menu', 'Add new link'), '#'); }
Adds a new link to the given menu. @param int $menuId Menu's ID for which add a link @return void
entailment
public function edit($id) { $this->loadModel('Menu.MenuLinks'); $this->loadModel('Content.Contents'); $link = $this->MenuLinks->get($id, ['contain' => ['Menus']]); if (!empty($this->request->data)) { $link = $this->MenuLinks->patchEntity($link, $this->request->data, [ 'fieldList' => [ 'title', 'url', 'description', 'target', 'expanded', 'active', 'activation', 'status' ] ]); if ($this->MenuLinks->save($link, ['associated' => false])) { $this->Flash->success(__d('menu', 'Link has been updated')); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('menu', 'Link could not be updated, please check your information')); } } $contentLinks = []; $contents = $this->Contents ->find() ->select(['id', 'slug', 'content_type_slug', 'title']) ->all(); foreach ($contents as $content) { $contentLinks[$content->get('url')] = __d('menu', '{0} [{1}]', $content->title, $content->content_type_slug); } $this->title(__d('menu', 'Editing Link')); $this->set(compact('link', 'contentLinks')); $this->Breadcrumb ->push('/admin/menu/manage') ->push(__d('menu', 'Editing menu'), ['plugin' => 'Menu', 'controller' => 'manage', 'action' => 'edit', $link->menu_id]) ->push(__d('menu', 'Links'), ['plugin' => 'Menu', 'controller' => 'links', 'action' => 'menu', $link->menu_id]) ->push(__d('menu', 'Editing link'), '#'); }
Edits the given menu link by ID. @param int $id Link's ID @return void
entailment
public function delete($id) { $this->loadModel('Menu.MenuLinks'); $link = $this->MenuLinks->get($id); $this->MenuLinks->addBehavior('Tree', ['scope' => ['menu_id' => $link->menu_id]]); $this->MenuLinks->removeFromTree($link); if ($this->MenuLinks->delete($link)) { $this->Flash->success(__d('menu', 'Link successfully removed!')); } else { $this->Flash->danger(__d('menu', 'Link could not be removed, please try again')); } $this->title(__d('menu', 'Delete Link')); $this->redirect($this->referer()); }
Deletes the given link. @param int $id Link's ID @return void
entailment
public function main() { if (!$this->_init()) { $this->_reset(); return false; } if (!$this->params['no-callbacks']) { // "before" events occurs even before plugins is moved to its destination $this->_attachListeners($this->_plugin['name'], "{$this->_workingDir}/"); try { $event = $this->trigger("Plugin.{$this->_plugin['name']}.beforeUpdate"); if ($event->isStopped() || $event->result === false) { $this->err(__d('installer', 'Task was explicitly rejected by the plugin.')); $this->_reset(); return false; } } catch (\Exception $ex) { $this->err(__d('installer', 'Internal error, plugin did not respond to "beforeUpdate" callback correctly.')); $this->_reset(); return false; } } if (!$this->_movePackage(true)) { $this->_reset(); return false; } if (!$this->params['no-callbacks']) { try { $event = $this->trigger("Plugin.{$this->_plugin['name']}.afterUpdate"); } catch (\Exception $e) { $this->err(__d('installer', 'Plugin was installed but some errors occur.')); } } $this->_finish(); return true; }
Task main method. @return bool
entailment
protected function _init() { if (!parent::_init()) { return false; } if (!Plugin::exists($this->_plugin['name'])) { $this->err(__d('installer', 'The plugin "{0}" is not installed, you cannot update a plugin that is not installed in your system.', $this->_plugin['name'])); return false; } else { $plugin = plugin($this->_plugin['name']); if (!$this->canBeDeleted($plugin->path)) { $this->err(__d('installer', 'Unable to update, please check write permissions for "{0}".', $plugin->path)); return false; } } return true; }
Prepares this task and the package to be installed. @return bool True on success
entailment
protected function _canBeDeleted($path) { if (!file_exists($path) || !is_dir($path)) { $this->err(__d('installer', "Plugin's directory was not found: ", $path)); return false; } $folder = new Folder($path); $content = $folder->tree(); $notWritable = []; foreach ($content as $foldersOrFiles) { foreach ($foldersOrFiles as $element) { if (!is_writable($element)) { $notWritable[] = $element; } } } if (!empty($notWritable)) { $this->err(__d('installer', "Some plugin's files or directories cannot be removed from your server:")); foreach ($notWritable as $path) { $this->err(__d('installer', " -{0}", $path)); } return false; } return true; }
Recursively checks if the given directory (and its content) can be deleted. This method automatically registers an error message if validation fails. @param string $path Directory to check @return bool
entailment
public static function formatter(Field $field, View $view) { $out = []; $instance = static::getInstance(); $glue = ' '; $termIds = (array)$field->extra; $termIds = empty($termIds) ? [-1] : $termIds; $terms = TableRegistry::get('Taxonomy.Terms') ->find() ->where(['id IN' => $termIds]) ->all(); if (!empty($field->viewModeSettings['link_template'])) { $templatesBefore = $view->Html->templates(); $view->Html->templates(['link' => $field->viewModeSettings['link_template']]); } foreach ($terms as $term) { if ($field->viewModeSettings['shortcodes']) { $term->set('name', $instance->shortcodes($term->name)); } if ($field->viewModeSettings['formatter'] === 'link_localized') { $glue = ' '; $out[] = $view->Html->link(__($term->name), "/find/term:{$term->slug}", ['class' => 'label label-primary']); } elseif ($field->viewModeSettings['formatter'] === 'plain_localized') { $glue = ', '; $out[] = __($term->name); } else { $glue = ', '; $out[] = $term->name; } } if (isset($templatesBefore)) { $view->Html->templates($templatesBefore); } return implode($glue, $out); }
Formats the given field. @param \Field\Model\Entity\Field $field The field being rendered @param \Cake\View\View $view Instance of View, used to access HtmlHelper @return string
entailment
public static function termsForBlock($terms, $block) { foreach ($terms as $term) { $title = $term->name; if (!empty($block->settings['show_counters'])) { $countCacheKey = "t{$term->id}"; $count = (string)Cache::read($countCacheKey, 'terms_count'); if ($count == '') { $count = (int)TableRegistry::get('Taxonomy.EntitiesTerms') ->find() ->where(['EntitiesTerms.term_id' => $term->id]) ->count(); Cache::write($countCacheKey, $count, 'terms_count'); } $title .= " ({$count})"; } $term->set('title', $title); $term->set('url', "/find/term:{$term->slug}"); if (!empty($term->children)) { $term->set('expanded', true); static::termsForBlock($term->children, $block); } } }
Prepares the given threaded list of terms. @param array $terms Threaded list of terms @param \Cake\Datasource\EntityInterface $block The block
entailment
public function install($dbConfig = []) { $this->_installed = true; if (!$this->prepareConfig($dbConfig)) { return false; } $conn = $this->getConn(); if ($conn === false) { return false; } if (!$this->isDbEmpty($conn)) { return false; } if (!$this->importTables($conn)) { return false; } $this->writeSetting(); return true; }
Starts the process. @param array $dbConfig Database connection information @return bool True on success, false otherwise
entailment
public function prepareConfig($dbConfig = []) { if ($this->config('connection')) { return true; } if (is_readable(ROOT . '/config/settings.php.tmp')) { $dbConfig = include ROOT . '/config/settings.php.tmp'; if (empty($dbConfig['Datasources']['default'])) { $this->error(__d('installer', 'Invalid database information in file "{0}"', ROOT . '/config/settings.php.tmp')); return false; } $dbConfig = $dbConfig['Datasources']['default']; } else { if (empty($dbConfig['driver'])) { $dbConfig['driver'] = '__INVALID__'; } if (strpos($dbConfig['driver'], "\\") === false) { $dbConfig['driver'] = "Cake\\Database\\Driver\\{$dbConfig['driver']}"; } } list(, $driverClass) = namespaceSplit($dbConfig['driver']); if (!in_array($driverClass, ['Mysql', 'Postgres', 'Sqlite', 'Sqlserver'])) { $this->error(__d('installer', 'Invalid database type ({0}).', $driverClass)); return false; } $this->config('connection', Hash::merge($this->_defaultConnection, $dbConfig)); return true; }
Prepares database configuration attributes. If the file "ROOT/config/settings.php.tmp" exists, and has declared a connection named "default" it will be used. @param array $dbConfig Database connection info coming from POST @return bool True on success, false otherwise
entailment
public function getConn() { if (!$this->config('connection.className')) { $this->error(__d('installer', 'Database engine cannot be empty.')); return false; } try { ConnectionManager::drop('installation'); ConnectionManager::config('installation', $this->config('connection')); $conn = ConnectionManager::get('installation'); $conn->connect(); return $conn; } catch (\Exception $ex) { $this->error(__d('installer', 'Unable to connect to database, please check your information. Details: {0}', '<p>' . $ex->getMessage() . '</p>')); return false; } }
Generates a new connection to DB. @return \Cake\Database\Connection|bool A connection object, or false on failure. On failure error messages are automatically set
entailment
public function importTables($conn) { $Folder = new Folder($this->config('schemaPath')); $fixtures = $Folder->read(false, false, true)[1]; try { return (bool)$conn->transactional(function ($connection) use ($fixtures) { foreach ($fixtures as $fixture) { $result = $this->_processFixture($fixture, $connection); if (!$result) { $this->error(__d('installer', 'Error importing "{0}".', $fixture)); return false; } } return true; }); } catch (\Exception $ex) { $this->error(__d('installer', 'Unable to import database information. Details: {0}', '<p>' . $ex->getMessage() . '</p>')); return false; } }
Imports tables schema and populates them. @param \Cake\Database\Connection $conn Database connection to use @return bool True on success, false otherwise. On failure error messages are automatically set
entailment
public function isDbEmpty($conn) { $Folder = new Folder($this->config('schemaPath')); $existingSchemas = $conn->schemaCollection()->listTables(); $newSchemas = array_map(function ($item) { return Inflector::underscore(str_replace('Schema.php', '', $item)); }, $Folder->read()[1]); $result = !array_intersect($existingSchemas, $newSchemas); if (!$result) { $this->error(__d('installer', 'A previous installation of QuickAppsCMS already exists, please drop your database tables before continue.')); } return $result; }
Checks whether connected database is empty or not. @param \Cake\Database\Connection $conn Database connection to use @return bool True if database if empty and tables can be imported, false if there are some existing tables
entailment
public function writeSetting() { $config = [ 'Datasources' => [ 'default' => $this->config('connection'), ], 'Security' => [ 'salt' => $this->salt() ], 'debug' => false, ]; $filePath = $this->config('settingsPath'); if (!str_ends_with(strtolower($filePath), '.tmp')) { $filePath .= '.tmp'; } $settingsFile = new File($filePath, true); return $settingsFile->write("<?php\n return " . var_export($config, true) . ";\n"); }
Creates site's "settings.php" file. @return bool True on success
entailment
protected function _processFixture($path, Connection $connection) { if (!is_readable($path)) { return false; } require $path; $fixtureClass = str_replace('.php', '', basename($path)); $schema = $this->_prepareSchema($fixtureClass); $sql = $schema->createSql($connection); $tableCreated = true; foreach ($sql as $stmt) { try { if (!$connection->execute($stmt)) { $tableCreated = false; } } catch (\Exception $ex) { $this->error(__d('installer', 'Unable to create table "{0}". Details: {1}', $schema->name(), $ex->getMessage())); $tableCreated = false; } } if (!$tableCreated) { return false; } if (!$this->_importRecords($fixtureClass, $schema, $connection)) { return false; } return true; }
Process the given fixture class, creates its schema and imports its records. @param string $path Full path to schema class file @param \Cake\Database\Connection $connection Database connection to use @return bool True on success
entailment
protected function _prepareSchema($fixtureClassName) { $fixture = new $fixtureClassName; if (!empty($fixture->table)) { $tableName = $fixture->table; } else { $tableName = (string)Inflector::underscore(str_replace_last('Fixture', '', $fixtureClassName)); } list($fields, $constraints, $indexes, $options) = $this->_prepareSchemaProperties($fixture); $schema = new TableSchema($tableName, $fields); foreach ($constraints as $name => $attrs) { $schema->addConstraint($name, $attrs); } foreach ($indexes as $name => $attrs) { $schema->addIndex($name, $attrs); } if (!empty($options)) { $schema->options($options); } return $schema; }
Gets an schema instance for the given fixture class. @param string $fixtureClassName The fixture to be "converted" @return \Cake\Database\Schema\Table Schema instance
entailment
protected function _prepareSchemaProperties($fixture) { $fields = (array)$fixture->fields; $constraints = []; $indexes = []; $options = []; if (isset($fields['_constraints'])) { $constraints = $fields['_constraints']; unset($fields['_constraints']); } if (isset($fields['_indexes'])) { $indexes = $fields['_indexes']; unset($fields['_indexes']); } if (isset($fields['_options'])) { $options = $fields['_options']; unset($fields['_options']); } return [ $fields, $constraints, $indexes, $options, ]; }
Extracts some properties from the given fixture instance to properly build a new table schema instance (constrains, indexes, etc). @param object $fixture Fixture instance from which extract schema properties @return array Where with keys 0 => $fields, 1 => $constraints, 2 => $indexes and 3 => $options
entailment
protected function _importRecords($fixtureClassName, TableSchema $schema, Connection $connection) { $fixture = new $fixtureClassName; if (!isset($fixture->records) || empty($fixture->records)) { return true; } $fixture->records = (array)$fixture->records; if (count($fixture->records) > 100) { $chunk = array_chunk($fixture->records, 100); } else { $chunk = [0 => $fixture->records]; } foreach ($chunk as $records) { list($fields, $values, $types) = $this->_getRecords($records, $schema); $query = $connection->newQuery() ->insert($fields, $types) ->into($schema->name()); foreach ($values as $row) { $query->values($row); } try { $statement = $query->execute(); $statement->closeCursor(); } catch (\Exception $ex) { $this->error(__d('installer', 'Error while importing data for table "{0}". Details: {1}', $schema->name(), $ex->getMessage())); return false; } } return true; }
Imports all records of the given fixture. @param string $fixtureClassName Fixture class name @param \Cake\Database\Schema\Table $schema Table schema for which records will be imported @param \Cake\Database\Connection $connection Database connection to use @return bool True on success
entailment
protected function _getRecords(array $records, TableSchema $schema) { $fields = $values = $types = []; $columns = $schema->columns(); foreach ($records as $record) { $fields = array_merge($fields, array_intersect(array_keys($record), $columns)); } $fields = array_values(array_unique($fields)); foreach ($fields as $field) { $types[$field] = $schema->column($field)['type']; } $default = array_fill_keys($fields, null); foreach ($records as $record) { $values[] = array_merge($default, $record); } return [$fields, $values, $types]; }
Converts the given array of records into data used to generate a query. @param array $records Records to be imported @param \Cake\Database\Schema\Table $schema Table schema for which records will be imported @return array
entailment
public function read() { $request = Router::getRequest(); if (!empty($request) && empty($this->_postData)) { $this->_postData = (array)$request->data(); } if (!empty($this->_postData)) { $keys = array_keys($this->_postData); $first = array_shift($keys); $value = $this->_postData[$first]; unset($this->_postData[$first]); return $value; } return false; }
Read a value from POST data. It reads the first input and removes that value from the stack, so consecutive readings are supported as follow: **Incoming POST data array** ```php [ 'input1' => 'value1', 'input2' => 'value2', 'input3' => 'value3', ] ``` **Reading from POST**: ```php $this->read(); // returns "value1" $this->read(); // returns "value2" $this->read(); // returns "value3" $this->read(); // returns false ``` @return mixed The value from POST data
entailment
protected function configureAop(AspectContainer $container) { foreach ((array)aspects() as $class) { $class = class_exists($class) ? new $class : null; if ($class instanceof Aspect) { $container->registerAspect($class); } } }
Configure an AspectContainer with advisors, aspects and pointcuts @param \Go\Core\AspectContainer $container AOP Container instance @return void
entailment
public function settingsValidate(Event $event, $data, Validator $validator) { if (isset($data['password_min_length'])) { $validator ->add('password_min_length', 'validNumber', [ 'rule' => ['naturalNumber', false], // false: exclude zero 'message' => __d('user', 'Invalid password min-length.') ]); } $validator ->requirePresence('message_welcome_subject') ->notEmpty('message_welcome_subject', __d('user', 'This field cannot be empty.')) ->requirePresence('message_welcome_body') ->notEmpty('message_welcome_body', __d('user', 'This field cannot be empty.')) ->requirePresence('message_password_recovery_subject') ->notEmpty('message_password_recovery_body', __d('user', 'This field cannot be empty.')) ->requirePresence('message_cancel_request_subject') ->notEmpty('message_cancel_request_body', __d('user', 'This field cannot be empty.')); if ($data['message_activation']) { $validator ->requirePresence('message_activation_subject') ->notEmpty('message_activation_body', __d('user', 'This field cannot be empty.')); } if ($data['message_blocked']) { $validator ->requirePresence('message_blocked_subject') ->notEmpty('message_blocked_body', __d('user', 'This field cannot be empty.')); } if ($data['message_canceled']) { $validator ->requirePresence('message_canceled_subject') ->notEmpty('message_canceled_body', __d('user', 'This field cannot be empty.')); } }
Validates plugin's settings. @param \Cake\Event\Event $event The event that was triggered @param array $data Data to be validated @param \Cake\Validation\Validator $validator The validator object @return void
entailment
public function render(Block $block, View $view) { $contentsTable = TableRegistry::get('Content.Contents'); $query = $contentsTable->find('all', ['fieldable' => false]); if (!empty($block->settings['filter_criteria'])) { $query = $contentsTable->search($block->settings['filter_criteria'], $query); } $contents = $query ->order(['created' => 'DESC']) ->where(['Contents.status' => true]) ->limit($block->settings['limit']) ->all(); return $view->element('Content.Widget/recent_content_render', compact('block', 'contents')); }
{@inheritDoc}
entailment
public function scope(Query $query, TokenInterface $token) { $column = $this->config('field'); $value = $token->value(); if (!$column || empty($value)) { return $query; } $tableAlias = $this->_table->alias(); $range = $this->_parseRange($token->value()); if ($range['lower'] !== $range['upper']) { $conjunction = $token->negated() ? 'AND NOT' : 'AND'; $conditions = [ "{$conjunction}" => [ "{$tableAlias}.{$column} >=" => $range['lower'], "{$tableAlias}.{$column} <=" => $range['upper'], ] ]; } else { $cmp = $token->negated() ? '<=' : '>='; $conditions = ["{$tableAlias}.{$column} {$cmp}" => $range['lower']]; } if ($token->where() === 'or') { $query->orWhere($conditions); } elseif ($token->where() === 'and') { $query->andWhere($conditions); } else { $query->where($conditions); } return $query; }
{@inheritDoc}
entailment
protected function _parseRange($value) { if (strpos($value, '..') !== false) { list($lower, $upper) = explode('..', $value); } else { $lower = $upper = $value; } if (intval($lower) > intval($upper)) { list($lower, $upper) = [$upper, $lower]; } return [ 'lower' => $lower, 'upper' => $upper, ]; }
Parses and extracts lower and upper values from the given range given as `lower..upper`. @param string $value A values range given as `<lowerValue>..<upperValue>`. For instance. `100..200` @return array Associative array with two keys: `lower` and `upper`
entailment
public function main() { if (empty($this->params['theme'])) { $this->err(__d('installer', 'You must provide a theme.')); return false; } if (!Plugin::exists($this->params['theme'])) { $this->err(__d('installer', 'Theme "{0}" was not found.', $this->params['theme'])); return false; } $plugin = plugin($this->params['theme']); if (!$plugin->isTheme) { $this->err(__d('installer', '"{0}" is not a theme.', $plugin->humanName)); return false; } if (in_array($this->params['theme'], [option('front_theme'), option('back_theme')])) { $this->err(__d('installer', 'Theme "{0}" is already active.', $plugin->humanName)); return false; } // MENTAL NOTE: As theme is "inactive" its listeners are not attached to the // system, so we need to manually attach them in order to trigger callbacks. if (!$this->params['no-callbacks']) { $this->_attachListeners($plugin->name, "{$plugin->path}/"); try { $event = $this->trigger("Plugin.{$plugin->name}.beforeActivate"); if ($event->isStopped() || $event->result === false) { $this->err(__d('installer', 'Task was explicitly rejected by the theme.')); $this->_detachListeners(); return false; } } catch (\Exception $ex) { $this->err(__d('installer', 'Internal error, theme did not respond to "beforeActivate" callback properly.')); $this->_detachListeners(); return false; } } if (isset($plugin->composer['extra']['admin']) && $plugin->composer['extra']['admin']) { $prefix = 'back_'; $previousTheme = option('back_theme'); } else { $prefix = 'front_'; $previousTheme = option('front_theme'); } $this->loadModel('System.Options'); $this->loadModel('System.Plugins'); if ($this->Plugins->updateAll(['status' => 0], ['name' => $previousTheme]) && $this->Plugins->updateAll(['status' => 1], ['name' => $this->params['theme']]) ) { if ($this->Options->update("{$prefix}theme", $this->params['theme'])) { $this->_copyBlockPositions($this->params['theme'], $previousTheme); } else { $this->err(__d('installer', 'Internal error, the option "{0}" could not be persisted on database.', "{$prefix}theme")); $this->_detachListeners(); return false; } } else { $this->err(__d('installer', 'Internal error, unable to turnoff current theme ({0}) and active new one ({1}).', $previousTheme, $this->params['theme'])); return false; } if (!$this->params['no-callbacks']) { try { $this->trigger("Plugin.{$plugin->name}.afterActivate"); } catch (\Exception $e) { $this->err(__d('installer', 'Theme did not respond to "afterActivate" callback.')); } } return true; }
Switch site's theme. @return void
entailment
protected function _copyBlockPositions($dst, $src) { $this->loadModel('Block.BlockRegions'); $dstTheme = plugin($dst); $newRegions = isset($dstTheme->composer['extra']['regions']) ? array_keys($dstTheme->composer['extra']['regions']) : []; if (empty($newRegions)) { return; } $existingPositions = $this->BlockRegions ->find() ->where(['theme' => $src]) ->all(); foreach ($existingPositions as $position) { if (in_array($position->region, $newRegions)) { $newPosition = $this->BlockRegions->newEntity([ 'block_id' => $position->block_id, 'theme' => $dstTheme->name, 'region' => $position->region, 'ordering' => $position->ordering, ]); $this->BlockRegions->save($newPosition); } } }
If $src has any region in common with $dst this method will make $dst have these blocks in the same regions as $src. @param string $dst Destination theme name @param string $src Source theme name @return void
entailment
public function displayBlock(Event $event, $block, $options = []) { return $this->trigger(['Block.Menu.display', $event->subject()], $block, $options)->result; }
All blocks registered by "System" plugin are associated blocks of some core's menus. So we redirect rendering task to Menu plugin's render. @param \Cake\Event\Event $event The event that was triggered @param \Block\Model\Entity\Block $block The block being rendered @param array $options Array of additional options @return array
entailment
public function netmountPrepare($options) { if (!empty($_REQUEST['encoding']) && @iconv('UTF-8', $_REQUEST['encoding'], '') !== false) { $options['encoding'] = $_REQUEST['encoding']; if (!empty($_REQUEST['locale']) && @setlocale(LC_ALL, $_REQUEST['locale'])) { setlocale(LC_ALL, elFinder::$locale); $options['locale'] = $_REQUEST['locale']; } } return $options; }
Prepare Call from elFinder::netmout() before volume->mount() @return Array @author Naoki Sawada
entailment
protected function init() { if (!$this->options['host'] || !$this->options['user'] || !$this->options['pass'] || !$this->options['port']) { return $this->setError('Required options undefined.'); } // make ney mount key $this->netMountKey = md5(join('-', array('ftp', $this->options['host'], $this->options['port'], $this->options['path'], $this->options['user']))); if (!function_exists('ftp_connect')) { return $this->setError('FTP extension not loaded.'); } // remove protocol from host $scheme = parse_url($this->options['host'], PHP_URL_SCHEME); if ($scheme) { $this->options['host'] = substr($this->options['host'], strlen($scheme)+3); } // normalize root path $this->root = $this->options['path'] = $this->_normpath($this->options['path']); if (empty($this->options['alias'])) { $this->options['alias'] = $this->options['user'].'@'.$this->options['host']; // $num = elFinder::$volumesCnt-1; // $this->options['alias'] = $this->root == '/' || $this->root == '.' ? 'FTP folder '.$num : basename($this->root); } $this->rootName = $this->options['alias']; $this->options['separator'] = '/'; return $this->connect(); }
Prepare FTP connection Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn @return bool @author Dmitry (dio) Levashov @author Cem (DiscoFever)
entailment
protected function configure() { parent::configure(); if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) { $this->tmp = $this->options['tmpPath']; } } if (!$this->tmp && $this->tmbPath) { $this->tmp = $this->tmbPath; } if (!$this->tmp) { $this->disabled[] = 'mkfile'; $this->disabled[] = 'paste'; $this->disabled[] = 'duplicate'; $this->disabled[] = 'upload'; $this->disabled[] = 'edit'; $this->disabled[] = 'archive'; $this->disabled[] = 'extract'; } // echo $this->tmp; }
Configure after successfull mount. @return void @author Dmitry (dio) Levashov
entailment
protected function connect() { if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) { return $this->setError('Unable to connect to FTP server '.$this->options['host']); } if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) { $this->umount(); return $this->setError('Unable to login into '.$this->options['host']); } // try switch utf8 mode if ($this->encoding) { @ftp_exec($this->connect, 'OPTS UTF8 OFF'); } else { @ftp_exec($this->connect, 'OPTS UTF8 ON' ); } // switch off extended passive mode - may be usefull for some servers @ftp_exec($this->connect, 'epsv4 off' ); // enter passive mode if required ftp_pasv($this->connect, $this->options['mode'] == 'passive'); // enter root folder if (!ftp_chdir($this->connect, $this->root) || $this->root != ftp_pwd($this->connect)) { $this->umount(); return $this->setError('Unable to open root folder.'); } // check for MLST support $features = ftp_raw($this->connect, 'FEAT'); if (!is_array($features)) { $this->umount(); return $this->setError('Server does not support command FEAT.'); } foreach ($features as $feat) { if (strpos(trim($feat), 'MLST') === 0) { return true; } } return $this->setError('Server does not support command MLST.'); }
Connect to ftp server @return bool @author Dmitry (dio) Levashov
entailment
protected function parseRaw($raw) { $info = preg_split("/\s+/", $raw, 9); $stat = array(); if (count($info) < 9 || $info[8] == '.' || $info[8] == '..') { return false; } if (!isset($this->ftpOsUnix)) { $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1)); } if ($this->ftpOsUnix) { $stat['ts'] = strtotime($info[5].' '.$info[6].' '.$info[7]); if (empty($stat['ts'])) { $stat['ts'] = strtotime($info[6].' '.$info[5].' '.$info[7]); } $stat['owner'] = $info[2]; $name = $info[8]; if (preg_match('|(.+)\-\>(.+)|', $name, $m)) { $name = trim($m[1]); $target = trim($m[2]); if (substr($target, 0, 1) != '/') { $target = $this->root.'/'.$target; } $target = $this->_normpath($target); $stat['name'] = $name; if ($this->_inpath($target, $this->root) && ($tstat = $this->stat($target))) { $stat['size'] = $tstat['mime'] == 'directory' ? 0 : $info[4]; $stat['alias'] = $this->_relpath($target); $stat['thash'] = $tstat['hash']; $stat['mime'] = $tstat['mime']; $stat['read'] = $tstat['read']; $stat['write'] = $tstat['write']; } else { $stat['mime'] = 'symlink-broken'; $stat['read'] = false; $stat['write'] = false; $stat['size'] = 0; } return $stat; } $perm = $this->parsePermissions($info[0], $stat['owner']); $stat['name'] = $name; $stat['mime'] = substr(strtolower($info[0]), 0, 1) == 'd' ? 'directory' : $this->mimetype($stat['name']); $stat['size'] = $stat['mime'] == 'directory' ? 0 : $info[4]; $stat['read'] = $perm['read']; $stat['write'] = $perm['write']; $stat['perm'] = substr($info[0], 1); } else { die('Windows ftp servers not supported yet'); } return $stat; }
Parse line from ftp_rawlist() output and return file stat (array) @param string $raw line from ftp_rawlist() output @return array @author Dmitry Levashov
entailment
protected function parsePermissions($perm, $user = '') { $res = array(); $parts = array(); $owner = $user? ($user == $this->options['user']) : $this->options['owner']; for ($i = 0, $l = strlen($perm); $i < $l; $i++) { $parts[] = substr($perm, $i, 1); } $read = ($owner && $parts[0] == 'r') || $parts[4] == 'r' || $parts[7] == 'r'; return array( 'read' => $parts[0] == 'd' ? $read && (($owner && $parts[3] == 'x') || $parts[6] == 'x' || $parts[9] == 'x') : $read, 'write' => ($owner && $parts[2] == 'w') || $parts[5] == 'w' || $parts[8] == 'w' ); }
Parse permissions string. Return array(read => true/false, write => true/false) @param string $perm permissions string @return string @author Dmitry (dio) Levashov
entailment
protected function cacheDir($path) { $this->dirsCache[$path] = array(); $list = array(); foreach (ftp_rawlist($this->connect, $this->convEncIn($path)) as $raw) { if (($stat = $this->parseRaw($raw))) { $list[] = $stat; } } $list = $this->convEncOut($list); foreach($list as $stat) { $p = $path.'/'.$stat['name']; $stat = $this->updateCache($p, $stat); if (empty($stat['hidden'])) { // $files[] = $stat; $this->dirsCache[$path][] = $p; } } }
Cache dir contents @param string $path dir path @return void @author Dmitry Levashov
entailment
protected function _normpath($path) { if (empty($path)) { $path = '.'; } // path must be start with / $path = preg_replace('|^\.\/?|', '/', $path); $path = preg_replace('/^([^\/])/', "/$1", $path); if (strpos($path, '/') === 0) { $initial_slashes = true; } else { $initial_slashes = false; } if (($initial_slashes) && (strpos($path, '//') === 0) && (strpos($path, '///') === false)) { $initial_slashes = 2; } $initial_slashes = (int) $initial_slashes; $comps = explode('/', $path); $new_comps = array(); foreach ($comps as $comp) { if (in_array($comp, array('', '.'))) { continue; } if (($comp != '..') || (!$initial_slashes && !$new_comps) || ($new_comps && (end($new_comps) == '..'))) { array_push($new_comps, $comp); } elseif ($new_comps) { array_pop($new_comps); } } $comps = $new_comps; $path = implode('/', $comps); if ($initial_slashes) { $path = str_repeat('/', $initial_slashes) . $path; } return $path ? $path : '.'; }
Return normalized path, this works the same as os.path.normpath() in Python @param string $path path @return string @author Troex Nevelin
entailment
protected function _relpath($path) { return $path == $this->root ? '' : substr($path, strlen($this->root)+1); }
Return file path related to root dir @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function _abspath($path) { return $path == $this->separator ? $this->root : $this->root.$this->separator.$path; }
Convert path related to root dir into real path @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function _path($path) { return $this->rootName.($path == $this->root ? '' : $this->separator.$this->_relpath($path)); }
Return fake path started from root dir @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function _stat($path) { $raw = ftp_raw($this->connect, 'MLST ' . $path); if (is_array($raw) && count($raw) > 1 && substr(trim($raw[0]), 0, 1) == 2) { $parts = explode(';', trim($raw[1])); array_pop($parts); $parts = array_map('strtolower', $parts); $stat = array(); // debug($parts); foreach ($parts as $part) { list($key, $val) = explode('=', $part); switch ($key) { case 'type': $stat['mime'] = strpos($val, 'dir') !== false ? 'directory' : $this->mimetype($path); break; case 'size': $stat['size'] = $val; break; case 'modify': $ts = mktime(intval(substr($val, 8, 2)), intval(substr($val, 10, 2)), intval(substr($val, 12, 2)), intval(substr($val, 4, 2)), intval(substr($val, 6, 2)), substr($val, 0, 4)); $stat['ts'] = $ts; // $stat['date'] = $this->formatDate($ts); break; case 'unix.mode': $stat['chmod'] = $val; break; case 'perm': $val = strtolower($val); $stat['read'] = (int)preg_match('/e|l|r/', $val); $stat['write'] = (int)preg_match('/w|m|c/', $val); if (!preg_match('/f|d/', $val)) { $stat['locked'] = 1; } break; } } if (empty($stat['mime'])) { return array(); } if ($stat['mime'] == 'directory') { $stat['size'] = 0; } if (isset($stat['chmod'])) { $stat['perm'] = ''; if ($stat['chmod'][0] == 0) { $stat['chmod'] = substr($stat['chmod'], 1); } for ($i = 0; $i <= 2; $i++) { $perm[$i] = array(false, false, false); $n = isset($stat['chmod'][$i]) ? $stat['chmod'][$i] : 0; if ($n - 4 >= 0) { $perm[$i][0] = true; $n = $n - 4; $stat['perm'] .= 'r'; } else { $stat['perm'] .= '-'; } if ($n - 2 >= 0) { $perm[$i][1] = true; $n = $n - 2; $stat['perm'] .= 'w'; } else { $stat['perm'] .= '-'; } if ($n - 1 == 0) { $perm[$i][2] = true; $stat['perm'] .= 'x'; } else { $stat['perm'] .= '-'; } $stat['perm'] .= ' '; } $stat['perm'] = trim($stat['perm']); $owner = $this->options['owner']; $read = ($owner && $perm[0][0]) || $perm[1][0] || $perm[2][0]; $stat['read'] = $stat['mime'] == 'directory' ? $read && (($owner && $perm[0][2]) || $perm[1][2] || $perm[2][2]) : $read; $stat['write'] = ($owner && $perm[0][1]) || $perm[1][1] || $perm[2][1]; unset($stat['chmod']); } return $stat; } return array(); }
Return stat for given path. Stat contains following fields: - (int) size file size in b. required - (int) ts file modification time in unix time. required - (string) mime mimetype. required for folders, others - optionally - (bool) read read permissions. required - (bool) write write permissions. required - (bool) locked is object locked. optionally - (bool) hidden is object hidden. optionally - (string) alias for symlinks - link target path relative to root path. optionally - (string) target for symlinks - link target path. optionally If file does not exists - returns empty array or false. @param string $path file path @return array|false @author Dmitry (dio) Levashov
entailment
protected function _subdirs($path) { foreach (ftp_rawlist($this->connect, $path) as $str) { if (($stat = $this->parseRaw($str)) && $stat['mime'] == 'directory') { return true; } } return false; }
Return true if path is dir and has at least one childs directory @param string $path dir path @return bool @author Dmitry (dio) Levashov
entailment
protected function _dimensions($path, $mime) { $ret = false; if ($imgsize = $this->getImageSize($path, $mime)) { $ret = $imgsize['dimensions']; } return $ret; }
Return object width and height Ususaly used for images, but can be realize for video etc... @param string $path file path @param string $mime file mime type @return string|false @author Dmitry (dio) Levashov
entailment
protected function _scandir($path) { $files = array(); foreach (ftp_rawlist($this->connect, $path) as $str) { if (($stat = $this->parseRaw($str))) { $files[] = $path.DIRECTORY_SEPARATOR.$stat['name']; } } return $files; }
Return files list in directory. @param string $path dir path @return array @author Dmitry (dio) Levashov @author Cem (DiscoFever)
entailment
protected function _fopen($path, $mode='rb') { if ($this->tmp) { $local = $this->getTempFile($path); $fp = @fopen($local, 'wb'); if (ftp_fget($this->connect, $fp, $path, FTP_BINARY)) { fclose($fp); $fp = fopen($local, $mode); return $fp; } @fclose($fp); is_file($local) && @unlink($local); } return false; }
Open file and return file pointer @param string $path file path @param bool $write open file for writing @return resource|false @author Dmitry (dio) Levashov
entailment
protected function _fclose($fp, $path='') { @fclose($fp); if ($path) { @unlink($this->getTempFile($path)); } }
Close opened file @param resource $fp file pointer @return bool @author Dmitry (dio) Levashov
entailment
protected function _mkdir($path, $name) { $path = $path.'/'.$name; if (ftp_mkdir($this->connect, $path) === false) { return false; } $this->options['dirMode'] && @ftp_chmod($this->connect, $this->options['dirMode'], $path); return $path; }
Create dir and return created dir path or false on failed @param string $path parent dir path @param string $name new directory name @return string|bool @author Dmitry (dio) Levashov
entailment
protected function _mkfile($path, $name) { if ($this->tmp) { $path = $path.'/'.$name; $local = $this->getTempFile(); $res = touch($local) && ftp_put($this->connect, $path, $local, FTP_ASCII); @unlink($local); return $res ? $path : false; } return false; }
Create file and return it's path or false on failed @param string $path parent dir path @param string $name new file name @return string|bool @author Dmitry (dio) Levashov
entailment
protected function _copy($source, $targetDir, $name) { $res = false; if ($this->tmp) { $local = $this->getTempFile(); $target = $targetDir.DIRECTORY_SEPARATOR.$name; if (ftp_get($this->connect, $local, $source, FTP_BINARY) && ftp_put($this->connect, $target, $local, $this->ftpMode($target))) { $res = $target; } @unlink($local); } return $res; }
Copy file into another file @param string $source source file path @param string $targetDir target directory path @param string $name new file name @return bool @author Dmitry (dio) Levashov
entailment
protected function _move($source, $targetDir, $name) { $target = $targetDir.DIRECTORY_SEPARATOR.$name; return ftp_rename($this->connect, $source, $target) ? $target : false; }
Move file into another parent dir. Return new file path or false. @param string $source source file path @param string $target target dir path @param string $name file name @return string|bool @author Dmitry (dio) Levashov
entailment
protected function _save($fp, $dir, $name, $stat) { $path = $dir.'/'.$name; return ftp_fput($this->connect, $path, $fp, $this->ftpMode($path)) ? $path : false; }
Create new file and write into it from file pointer. Return new file path or false on error. @param resource $fp file pointer @param string $dir target dir path @param string $name file name @param array $stat file stat (required by some virtual fs) @return bool|string @author Dmitry (dio) Levashov
entailment