code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function setLocLon($varValue, \DataContainer $dc) { if ($varValue != 0) { if (!\con4gis\MapsBundle\Resources\contao\classes\Utils::validateLon($varValue)) { throw new \Exception($GLOBALS['TL_LANG']['c4g_maps']['geox_invalid']); } } return $varValue; }
Validate Longitude
public function setLocLat($varValue, \DataContainer $dc) { if ($varValue != 0) { if (!\con4gis\MapsBundle\Resources\contao\classes\Utils::validateLat($varValue)) { throw new \Exception($GLOBALS['TL_LANG']['c4g_maps']['geoy_invalid']); } } return $varValue; }
Validate Latitude
public function getAllLocStyles(DataContainer $dc) { $locStyles = $this->Database->prepare("SELECT id,name FROM tl_c4g_map_locstyles ORDER BY name") ->execute(); while ($locStyles->next()) { $return[$locStyles->id] = $locStyles->name; } return $return; }
Return all Location Styles as array @param object @return array
public function getAllBaseLayers(DataContainer $dc) { $baseLayers = $this->Database->prepare("SELECT id,name FROM tl_c4g_map_baselayers ORDER BY name") ->execute(); while ($baseLayers->next()) { $return[$baseLayers->id] = $baseLayers->name; } return $return; }
Return all Base Layers as array @param object @return array
public function pickUrl(DataContainer $dc) { return ' <a href="contao/page.php?do='.Input::get('do').'&amp;table='.$dc->table.'&amp;field='.$dc->field.'&amp;value='.str_replace(array('{{link_url::', '}}'), '', $dc->value).'" title="'.specialchars($GLOBALS['TL_LANG']['MSC']['pagepicker']).'" onclick="Backend.getScrollOffset();Backend.openModalSelector({\'width\':765,\'title\':\''.specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MOD']['page'][0])).'\',\'url\':this.href,\'id\':\''.$dc->field.'\',\'tag\':\'ctrl_'.$dc->field . ((Input::get('act') == 'editAll') ? '_' . $dc->id : '').'\',\'self\':this});return false">' . $this->generateImage('pickpage.gif', $GLOBALS['TL_LANG']['MSC']['pagepicker'], 'style="vertical-align:top;cursor:pointer"') . '</a>'; }
Return the page pick wizard for the editor_helpurl @param DataContainer $dc
public function editLocationStyle(DataContainer $dc) { return ($dc->value < 1) ? '' : ' <a href="contao/main.php?do=c4g_map_locstyles&amp;act=edit&amp;id=' . $dc->value . '&amp;popup=1&amp;nb=1&amp;rt=' . REQUEST_TOKEN . '" title="' . sprintf(specialchars($GLOBALS['TL_LANG']['tl_c4g_maps']['editalias'][1]), $dc->value) . '" style="padding-left:3px" onclick="Backend.openModalIframe({\'width\':768,\'title\':\'' . specialchars(str_replace("'", "\\'", sprintf($GLOBALS['TL_LANG']['tl_c4g_maps']['editalias'][1], $dc->value))) . '\',\'url\':this.href});return false">' . Image::getHtml('alias.gif', $GLOBALS['TL_LANG']['tl_c4g_maps']['editalias'][0], 'style="vertical-align:top"') . '</a>'; }
Return the edit location style wizard @param \DataContainer @return string
public function getAllThemes() { $return = []; $themes = $this->Database->prepare("SELECT id,name FROM tl_c4g_map_themes ORDER BY name") ->execute(); while ($themes->next()) { $return[$themes->id] = $themes->name; } return $return; }
Return all themes as array @return array
public function editModule(DataContainer $dc) { return ($dc->value < 1) ? '' : ' <a href="contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $dc->value . '&amp;popup=1&amp;nb=1&amp;rt=' . REQUEST_TOKEN . '" title="' . sprintf(StringUtil::specialchars($GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $dc->value) . '" onclick="Backend.openModalIframe({\'title\':\'' . StringUtil::specialchars(str_replace("'", "\\'", sprintf($GLOBALS['TL_LANG']['tl_content']['editalias'][1], $dc->value))) . '\',\'url\':this.href});return false">' . Image::getHtml('alias.svg', $GLOBALS['TL_LANG']['tl_content']['editalias'][0]) . '</a>'; }
Return the edit module wizard @param DataContainer $dc @return string
public function getModules() { $arrModules = []; $objModules = $this->Database->execute("SELECT m.id, m.name, t.name AS theme FROM tl_module m LEFT JOIN tl_theme t ON m.pid=t.id ORDER BY t.name, m.name"); while ($objModules->next()) { $arrModules[$objModules->theme][$objModules->id] = $objModules->name . ' (ID ' . $objModules->id . ')'; } return $arrModules; }
Get all modules and return them as array @return array
public function generate() { if (TL_MODE == 'BE') { $objMap = $this->Database->prepare("SELECT * FROM tl_c4g_maps WHERE id=?") ->limit(1) ->execute($this->c4g_map_id); $return = '<h1>' . $objMap->name . '<img src="bundles/con4gismaps/images/logo_con4gis-maps.png" style="float:right"></h1>'; return $return; } return parent::generate(); }
Generate content element
protected function getStyleData($arrIds) { $arrLocationsStyles = array(); $objLocationStyles = C4gMapLocstylesModel::findMultipleByIds($arrIds); if ($objLocationStyles == null) { HttpResultHelper::NotFound(); } while($objLocationStyles->next()) { $arrLocationsStyles[] = $this->prepareStyleData($objLocationStyles->row()); } return $arrLocationsStyles; }
Returns the layer data. @param int $id
public function init() { parent::init(); self::$plugin = $this; if (!Craft::$app->getRequest()->getIsCpRequest()) { return; } // Register Components (Services) $this->setComponents([ 'singlesList' => SinglesList::class, ]); // Modified the entry index sources Event::on(Entry::class, Element::EVENT_REGISTER_SOURCES, function(RegisterElementSourcesEvent $event) { // Have we enabled the plugin? if ($this->getSettings()->expandSingles) { // Are there any Singles at all? foreach ($event->sources as $source) { if (array_key_exists('key', $source) && $source['key'] === 'singles') { $this->singlesList->createSinglesList($event); } } } }); // Hook onto a special hook from Redactor - it handles singles a little differently! if (class_exists(RedactorField::class)) { Event::on(RedactorField::class, RedactorField::EVENT_REGISTER_LINK_OPTIONS, function(RegisterLinkOptionsEvent $event) { // Have we enabled the plugin? if ($this->getSettings()->expandSingles) { foreach ($event->linkOptions as $i => $linkOption) { // Only apply this for entries, and if there are any singles if ($linkOption['refHandle'] === 'entry') { if (in_array('singles', $linkOption['sources'])) { $modifiedSources = $this->singlesList->createSectionedSinglesList($linkOption['sources']); if ($modifiedSources) { $event->linkOptions[$i]['sources'] = $modifiedSources; } } } } } }); } }
=========================================================================
public static function validateLon($value) { if (strpos($value, '{{') !== -1) { return true; } if (self::validateGeo($value)) { return (($value >= -180.0) && ($value <= 180.0)); } return false; }
Validate a longitude coordinate @param [type] $value [description] @return [type] [description]
public static function validateLat($value) { if (strpos($value, '{{') !== -1) { return true; } if (self::validateGeo($value)) { return (($value >= -90.0) && ($value <= 90.0)); } return false; }
Validate a latitude coordinate @param [type] $value [description] @return [type] [description]
public static function validateGeo($value) { if (!isset($value)) { return false; } $value = floatval($value); if ($value == 0) { return false; } return true; }
Validate a Geo Coordinate @param [type] $value [description] @return [type] [description]
private function setChildHide($childList, $parentLayer) { $newChildList = []; if ($childList && $parentLayer) { foreach($childList as $index=>$child) { if ($parentLayer->data_hidelayer) { $child['hide'] = $parentLayer->data_hidelayer; if ($child['hasChilds']) { $child['childs'] = $this->setChildHide($child['childs'], $parentLayer); } } $newChildList[$index] = $child; } } return $newChildList; }
Private function to set the hide property of childs correctly. @param $childList @param $parentLayer @return array
private function getChildsForLinkedLayer($layerId, $parentLayer) { $childLayers = C4gMapsModel::findPublishedByPid($layerId); $arrLayerData['childs'] = []; foreach ($childLayers as $childLayer) { if ($childLayer->location_type !== "none") { // we reached the "bottom" of the tree leaf $childData = $this->parseLayer($childLayer); $childData['pid'] = $parentLayer->id; $arrLayerData['childs'][] = $childData; $arrLayerData['hide'] = $parentLayer->data_hidelayer; } else { $currentChildLayer = $this->parseLayer($childLayer); // set correct pid for the contentless element $currentChildLayer['pid'] = $parentLayer->id; // $childLayer is the acutal existing layer. $arrChildData = $this->getChildsForLinkedLayer($childLayer->id, (object) $currentChildLayer); $currentChildLayer['childs'] = $arrChildData['childs']; $currentChildLayer['content'] = []; $currentChildLayer['hasChilds'] = count($currentChildLayer['childs']) > 0; $currentChildLayer['childsCount'] = count($currentChildLayer['childs']); $arrLayerData['childs'][] = $currentChildLayer; } $arrLayerData['content'] = []; $arrLayerData['hasChilds'] = count($arrLayerData['childs']) > 0; $arrLayerData['childsCount'] = count($arrLayerData['childs']); } return $arrLayerData; }
Returns the linked structure. @param $layerId @param $parentLayer @return array
public function createSectionedSinglesList(array $sources) { // Grab all the Singles $singleSections = Craft::$app->sections->getSectionsByType(Section::TYPE_SINGLE); // Create list of Singles $singles = []; foreach ($singleSections as $single) { $entry = Entry::find() ->status(null) ->sectionId($single->id) ->one(); if ($entry && Craft::$app->getUser()->checkPermission('editEntries:' . $single->uid)) { $url = $entry->getCpEditUrl(); $singles[] = 'single:' . $single->uid; } } // Replace original Singles link with new singles list array_splice($sources, 0, 1, $singles); return $sources; }
Create a new singles list and replace the old one with it. This is a slightly modified and short-hand version of `createSinglesList`, and is used for a Redactor field. This uses a simple array, and outputs an array of section:id combinations. This is because Redactor shows entries grouped by channels. @param array $sources @return array
public function getMapTables() { $tables = []; if (is_array($GLOBALS['con4gis']['maps']['sourcetable'])) { foreach ($GLOBALS['con4gis']['maps']['sourcetable'] as $key=>$sourcetable) { $tables[$key] = $GLOBALS['TL_LANG']['c4g_maps']['sourcetable'][$key]['name']; } } return $tables; }
Return available Map tables @return array Array of map tables
public function on($event,$pattern,$handler) { $bak = $this->f3->ROUTES; $this->f3->ROUTES=array(); $this->f3->route($pattern,$handler); $this->routes[$event] = (isset($this->routes[$event])) ? $this->f3->extend('ROUTES',$this->routes[$event]) : $this->f3->ROUTES; $this->f3->ROUTES=$bak; }
register route to a specific event @param $event @param $pattern @param $handler
protected function getEditorConfigForProfile($intId) { $arrEditorConfig = array(); // Find the requested profile $objProfile = C4gMapProfilesModel::findById($intId); if ($objProfile == null) { HttpResultHelper::NotFound(); } // Get editor config from profile $arrEditorConfig['styles_point'] = unserialize($objProfile->editor_styles_point); $arrEditorConfig['styles_line'] = unserialize($objProfile->editor_styles_line); $arrEditorConfig['styles_polygon'] = unserialize($objProfile->editor_styles_polygon); $arrEditorConfig['styles_circle'] = unserialize($objProfile->editor_styles_circle); $arrEditorConfig['styles_freehand'] = unserialize($objProfile->editor_styles_freehand); $arrEditorConfig['vars'] = $objProfile->editor_vars; $arrEditorConfig['show_items'] = $objProfile->editor_show_items; $arrEditorConfig['helpurl'] = $objProfile->editor_helpurl; return $arrEditorConfig; }
Returns the editor configuration from a given profile. @param $intId integer the profileId @return array
public function setLocLon($varValue, \DataContainer $dc) { if ($varValue != 0) { if (!Utils::validateLon($varValue)) { throw new \Exception($GLOBALS['TL_LANG']['c4g_maps']['geox_invalid']); } } return $varValue; }
Validate Longitude
public function setLocLat($varValue, \DataContainer $dc) { if ($varValue != 0) { if (!Utils::validateLat($varValue)) { throw new \Exception($GLOBALS['TL_LANG']['c4g_maps']['geoy_invalid']); } } return $varValue; }
Validate Latitude
public static function findPublishedByPid($intPid, array $arrOptions = array()) { $t = static::$strTable; $arrColumns = array("$t.pid=?"); $arrValues = array($intPid); if (!C4GUtils::checkBackendUserLogin()) { $time = time(); $arrColumns[] = "$t.published=1"; } if (!isset($arrOptions['order'])) { $arrOptions['order'] = "$t.sorting"; } return static::findBy($arrColumns, $arrValues, $arrOptions); }
ToDo Funktioniert unter contao 4 offensichtlich nicht mehr so wie es soll.
public static function loadGeopickerResources($additionalResources = array()) { //load geopicker profile $profile = C4gMapProfilesModel::findBy('is_backend_geopicker_default', 1); // use default if the profile was not found if (!$profile) { $settings = C4gSettingsModel::findAll(); $profile = $settings[0]->defaultprofile; if (!$profile) { $profiles = C4gMapProfilesModel::findAll(); if ($profiles && (!empty($profiles))) { $length = count($profiles); $profile = $profiles[$length-1]; } else { return; } } } self::loadResourcesForProfile($profile->id, true, $profile); if (count($additionalResources) > 0) { self::loadResources($additionalResources); } }
Loads the default geopicker profile and resources according to that profile @return void
public function generate($strInput) { $arrInputExploded = explode(':', $strInput); $strTable = $arrInputExploded[0]; $intId = $arrInputExploded[1]; return $this->getInfoWindowContent($strTable, $intId); }
Determines the request method and selects the appropriate data result. @param string $strInput Fragments from request uri @return mixed JSON data
protected function validator($varInput) { $validatedInput = parent::validator($varInput); $validatedInput[2] = preg_replace('/[^a-z0-9_%]+/', '', $varInput[2]); return $validatedInput; }
Trim values @param mixed @return mixed
public function generateLabel() { if (($this->require_input) && ($this->value == '')) { $this->required = true; } return parent::generateLabel(); }
Check custom setting 'require_input', which implements custom mandatory handling possibility @return string
public function getFolderData($objLayer, $key=false, $folder=false, $count=0) { if (!$folder) { $folder = $this->getFolder($objLayer); } if (!$key) { $key =$objLayer->id; } $folderPath = realpath(TL_ROOT.'/'.$folder); $countFiles = 2050; if (is_dir($folderPath)) { $dict = scandir($folderPath); unset($dict[array_search('.', $dict)]); unset($dict[array_search('..', $dict)]); foreach ($dict as $value) { // $value = utf8_encode($value); $path = realpath(TL_ROOT."/".$folder."/".$value); if (is_dir($path)) { $fileFolder = pathinfo($path); $arrSubFolder = $this->getFolderContent($objLayer, $fileFolder, $key, $count); $count += 1; $data = $this->getFolderData($objLayer, $arrSubFolder['id'], $folder."/".$value, $count); if ($data) { $arrSubFolder['childsCount'] = count($data); $arrSubFolder['childs'] = $data; $arrData[] = $arrSubFolder; } } elseif (is_file($path)) { $fileData = pathinfo($path); $arrFile = $this->getFileContent($objLayer, $folder, $fileData, $key, $countFiles); $countFiles += 2; if($arrFile) { $arrData[] = $arrFile; } } } return $arrData; } else { return false; } }
Creates the layer data for a given layer of the location_type folder. @param $objLayer @param bool $key @param bool $folder @param int $count @return array|bool
private function getFolderContent($objLayer, $folderInfo, $key, $count) { $month = array('01' => 'Januar', '02', 'Frebruar', '03' => 'März', '04' => 'April', '05' => 'Mai', '06' => 'Juni', '07' => 'Juli', '08' => 'August', '09' => 'Sebtember', '10' => 'Oktober', '11' => 'November', '12' => 'Dezember'); $folder = array( "id" => strval($objLayer->id.$count), "pid" => $key, "name" => utf8_encode($folderInfo['filename']), "hide" => $objLayer->published, "display" => true, "type" => $objLayer->location_type, "hasChilds" => true, "childsCount" => '', "childs" => array() ); return $folder; }
Parses meta information from a directory. @param $objLayer @param $folderInfo @param $key @param $count @return array
protected function getBaseLayerList($arrFilter) { $arrBaseLayer = array(); // C4gMapBaselayersModel $objBaseLayers = C4gMapBaselayersModel::findAll(); if ($objBaseLayers != null) { while ($objBaseLayers->next()) { if ($objBaseLayers->published != 1) { continue; } if ($objBaseLayers->protect_baselayer) { if (FE_USER_LOGGED_IN && !empty($objBaseLayers->permitted_groups)) { if (sizeof(array_intersect($this->User->groups, deserialize($objBaseLayers->permitted_groups))) <= 0) { continue; } } else { continue; } } if ($arrFilter) { if (!in_array($objBaseLayers->id, $arrFilter)) { continue; } } $arrLayerData = $this->parseBaseLayer($objBaseLayers); $objOverlays = C4gMapOverlaysModel::findBy('pid', $objBaseLayers->id); if ($objOverlays !== null) { $arrLayerData['hasOverlays'] = true; $arrLayerData['overlays'] = array(); while ($objOverlays->next()) { $arrLayerData['overlays'][] = $this->parseOverlay($objOverlays); } } $arrBaseLayer[] = $arrLayerData; } } return $arrBaseLayer; }
Returns the layer structure for the map. @param int $id
public static function render($t,$v=null){ if (Options::get('core.text.replace_empties', true)) { $replacer = function($c) use ($v){ return Structure::fetch(trim($c[1]), $v); }; } else { $replacer = function($c) use ($v){ return Structure::fetch(trim($c[1]), $v) ?: $c[0]; }; } return preg_replace_callback("(\{\{([^}]+)\}\})S",$replacer,$t); }
Fast string templating. Uses a Twig-like syntax. @example echo Text::render('Your IP is : {{ server.REMOTE_HOST }}',array('server' => $_SERVER)); @author Stefano Azzolini <[email protected]> @access public @static @param mixed $t The text template @param mixed $v (default: null) The array of values exposed in template. @return string
public static function removeAccents($text){ static $diac; return strtr( utf8_decode($text), $diac ? $diac : $diac = utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY'); }
Translit accented characters to neutral ones @example echo Text::removeAccents("Thîs îs à vêry wrong séntènce!"); // This is a very wrong sentence! @access public @static @param string $text The text to translit @return string The translited text
public static function cut($text, $start_tag, $end_tag=null){ $_s = strlen($start_tag) + strpos($text, $start_tag); return $end_tag ? substr($text, $_s, strpos($text,$end_tag,$_s)-$_s) : substr($text, $_s); }
Cut a string from the end of a substring to the start of another @example echo strcut("Name: Ethan Hunt; Role: Agent",'Name: ',';'); // Ethan Hunt @param string $text The source text @param string $start_tag The starting substring @param string $end_tag Ending substring, if omitted all remaining string is returned @return string The cutted string
public function offsetSet($key, $value){ if ( is_array($value) ) parent::offsetSet($key, new static($value)); else parent::offsetSet($key, $value); }
ArrayObject::offsetSet
public function offsetGet($key){ $raw = parent::offsetGet($key); return is_callable($raw) ? call_user_func($raw) : $raw; }
ArrayObject::offsetGet
public static function fetch($path, $root) { $_ = (array)$root; if (strpos($path,'.') === false) { return isset($_[$path]) ? $_[$path] : null; } else { list($frag,$rest) = explode('.', $path, 2); if ($rest) { return isset($_[$frag]) ? self::fetch($rest, $_[$frag]) : null; } elseif ($frag) { return (array)$_[$frag]; } else { return null; } } }
Dot-Notation Array Path Resolver @param string $path The dot-notation path @param array $root The array to navigate @return mixed The pointed value
public function get($key, $default=null){ if (null !== ($ptr =& $this->find($key,false))){ return $ptr; } else { if ($default !== null){ return $this->set($key, is_callable($default) ? call_user_func($default) : $default); } else { return null; } } }
Get a value assigned to a key path from the map @param string $key The key path of the value in dot notation @param mixed $default (optional) The default value. If is a callable it will executed and the return value will be used. @return mixed The value of the key or the default (resolved) value if the key not existed.
public function set($key, $value=null){ if (is_array($key)) { return $this->merge($key); } else { $ptr =& $this->find($key, true); return $ptr = $value; } }
Set a value for a key path from map @param string $key The key path of the value in dot notation @param mixed $value (optional) The value. If is a callable it will executed and the return value will be used. @return mixed The value of the key or the default (resolved) value if the key not existed.
public function delete($key, $compact=true){ $this->set($key, null); if ($compact) $this->compact(); }
Delete a value and the key path from map. @param string $key The key path in dot notation @param boolean $compact (optional) Compact map removing empty paths.
public function merge($array, $merge_back=false){ $this->fields = $merge_back ? array_replace_recursive((array)$array, $this->fields) : array_replace_recursive($this->fields, (array)$array); }
Merge an associative array to the map. @param array $array The array to merge @param boolean $merge_back If `true` merge the map over the $array, if `false` (default) the reverse.
public function compact(){ $array_filter_rec = function($input, $callback = null) use (&$array_filter_rec) { foreach ($input as &$value) { if (is_array($value)) { $value = $array_filter_rec($value, $callback); } } return array_filter($input, $callback); }; $this->fields = $array_filter_rec($this->fields,function($a){ return $a !== null; }); }
Compact map removing empty paths
public function & find($path, $create=false, callable $operation=null) { $create ? $value =& $this->fields : $value = $this->fields; foreach (explode('.',$path) as $tok) if ($create || isset($value[$tok])) { $value =& $value[$tok]; } else { $value = $create ? $value : null; break; } if ( is_callable($operation) ) $operation($value); return $value; }
Navigate map and find the element from the path in dot notation. @param string $path Key path in dot notation. @param boolean $create If true will create empty paths. @param callable If passed this callback will be applied to the founded value. @return mixed The founded value.
static public function start($name=null){ if (isset($_SESSION)) return; $ln = static::name($name); // Obfuscate IDs ini_set('session.hash_function', 'whirlpool'); session_cache_limiter('must-revalidate'); if (session_status() == PHP_SESSION_NONE) { @session_start(); } static::trigger("start", $name?:$ln); }
Start session handler @access public @static @return void
static public function cookieParams($args = []) { if (empty($args)) return session_get_cookie_params(); $args = array_merge(session_get_cookie_params(), $args); session_set_cookie_params($args["lifetime"], $args["path"], $args["domain"], $args["secure"], $args["httponly"]); return $args; }
Get/Set Session's cookie params @access public @static @param array $args Array of cookie's parameters @see http://php.net/manual/en/function.session-set-cookie-params.php @example $args = [ "lifetime" => 600, "path" => "/", "domain" => ".caffeina.com", "secure" => true, "httponly" => false ]; @return array The cookie's parameters @see http://php.net/manual/en/function.session-get-cookie-params.php
static public function get($key,$default=null){ if (($active = static::active()) && isset($_SESSION[$key])) { return $_SESSION[$key]; } else if ($active) { return $_SESSION[$key] = (is_callable($default)?call_user_func($default):$default); } else { return (is_callable($default)?call_user_func($default):$default); } }
Get a session variable reference @access public @static @param mixed $key The variable name @return mixed The variable value
public static function download($data){ if (is_array($data)) { if (isset($data['filename'])) static::$force_dl = $data['filename']; if (isset($data['charset'])) static::charset($data['charset']); if (isset($data['mime'])) static::type($data['mime']); if (isset($data['body'])) static::body($data['body']); } else static::$force_dl = $data; }
Force download of Response body @param mixed $data Pass a falsy value to disable download, pass a filename for exporting content or array with raw string data @return void
public static function enableCORS($origin='*'){ // Allow from any origin if ($origin = $origin ?:( isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '*') )) { static::header('Access-Control-Allow-Origin', $origin); static::header('Access-Control-Allow-Credentials', 'true'); static::header('Access-Control-Max-Age', 86400); } // Access-Control headers are received during OPTIONS requests if (filter_input(INPUT_SERVER,'REQUEST_METHOD') == 'OPTIONS') { static::clean(); if (filter_input(INPUT_SERVER,'HTTP_ACCESS_CONTROL_REQUEST_METHOD')) { static::header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD, CONNECT, PATCH, TRACE'); } if ($req_h = filter_input(INPUT_SERVER,'HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) { static::header('Access-Control-Allow-Headers',$req_h); } self::trigger('cors.preflight'); static::send(); exit; } }
Enable CORS HTTP headers.
public static function json($payload){ static::type(static::TYPE_JSON); static::$payload[] = json_encode($payload, Options::get('core.response.json_flags',JSON_NUMERIC_CHECK|JSON_BIGINT_AS_STRING)); }
Append a JSON object to the buffer. @param mixed $payload Data to append to the response buffer
public static function add(){ foreach(func_get_args() as $data){ switch (true) { case is_callable($data) : return static::add($data()); case is_a($data, 'View') : return static::$payload[] = "$data"; case is_object($data) || is_array($data) || is_bool($data): return static::json($data); default: return static::$payload[] = $data; } } }
Append data to the buffer. Rules : - Callables will be called and their results added (recursive) - Views will be rendered - Objects, arrays and bools will be JSON encoded - Strings and numbers will be appendend to the response @param mixed $payload Data to append to the response buffer
public static function load($data){ $data = (object)$data; if (isset($data->head)) static::headers($data->head); if (isset($data->body)) static::body($data->body); }
Load response from a saved state @method load @param array $data head/body saved state
public static function push($links, $type='text'){ if (is_array($links)){ foreach($links as $_type => $link) { // Extract URL basename extension (query-safe version) if (is_numeric($_type)) switch(strtolower(substr(strrchr(strtok(basename($link),'?'),'.'),1))) { case 'js': $_type = 'script'; break; case 'css': $_type = 'style'; break; case 'png': case 'svg': case 'gif': case 'jpg': $_type = 'image'; break; case 'woff': case 'woff2': case 'ttf': case 'eof': $_type = 'font'; break; default: $_type = 'text'; break; } foreach ((array)$link as $link_val) { static::header("Link","<$link_val>; rel=preload; as=$_type"); } } } else { static::header("Link","<".((string)$links).">; rel=preload; as=$type"); } }
Push resources to client (HTTP/2 spec) @param string/array $links The link(s) to the resources to push. @return Response The Route object
protected static function _compileCommand($command,array $params){ $s = $w = []; foreach ($params as $p) { if ($p instanceof static) { $s[] = '$('.$p->getShellCommand().')'; } else if (is_array($p)) foreach ($p as $key => $value) { if(is_numeric($key)){ $w[] = '--'.$value; } else { if(is_bool($value)){ if($value) $w[] = '--'.$key; } else { $w[] = '--'.$key.'='.escapeshellarg($value); } } } else { $s[] = $p; } } return trim( '/usr/bin/env '.$command.' '.implode(' ',array_merge($w,$s)) ); }
Compile a shell command @param string $command @param array $params @return string
public static function pipe(/* ... */){ $cmd = []; foreach (func_get_args() as $item) { $cmd[] = ($item instanceof static)?$item->getShellCommand():$item; } return new static(implode(' | ',$cmd)); }
Concatenate multiple shell commands via piping @return Shell The piped shell command
public static function sequence(...$items){ $cmd = []; foreach ($items as $item) { $cmd[] = ($item instanceof static)?$item->getShellCommand():$item; } return new static(implode(' && ',$cmd)); }
Concatenate multiple shell commands via logical implication ( && ) @return Shell The concatenated shell command
public static function from($template,$data=null){ $view = new self($template); return $data ? $view->with($data) : $view; }
View factory method, can optionally pass data to pre-init view @param string $template The template path @param array $data The key-value map of data to pass to the view @return View
public function with($data){ if ($data){ $tmp = array_merge($data, (isset($this->options['data'])?$this->options['data']:[])); $this->options['data'] = $tmp; } return $this; }
Assigns data to the view @param array $data The key-value map of data to pass to the view @return View
public function disconnect() { if (!empty($this->conn)) { ftp_close($this->conn); $this->conn = null; } }
{@inheritdoc}
public function exists(BucketInterface $bucket, string $name): bool { $this->connect(); return ftp_size($this->conn, $this->getPath($bucket, $name)) !== -1; }
{@inheritdoc}
public function size(BucketInterface $bucket, string $name): ?int { $this->connect(); if (($size = ftp_size($this->conn, $this->getPath($bucket, $name))) != -1) { return $size; } return null; }
{@inheritdoc}
public function put(BucketInterface $bucket, string $name, StreamInterface $stream): bool { $this->connect(); $location = $this->ensureLocation($bucket, $name); $filename = StreamWrapper::getFilename($stream); try { if (!ftp_put($this->conn, $location, $filename, FTP_BINARY)) { throw new ServerException("Unable to put '{$name}' to FTP server"); } } finally { StreamWrapper::release($filename); } return $this->refreshPermissions($bucket, $name); }
{@inheritdoc}
public function getStream(BucketInterface $bucket, string $name): StreamInterface { $this->connect(); if (!$filename = $this->localFilename($bucket, $name)) { throw new ServerException( "Unable to create stream for '{$name}', object does not exists" ); } //Thought local file return stream_for(fopen($filename, 'rb')); }
{@inheritdoc}
public function delete(BucketInterface $bucket, string $name) { $this->connect(); if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to delete object, file not found"); } ftp_delete($this->conn, $this->getPath($bucket, $name)); }
{@inheritdoc}
public function rename(BucketInterface $bucket, string $oldName, string $newName): bool { $this->connect(); if (!$this->exists($bucket, $oldName)) { throw new ServerException("Unable to rename '{$oldName}', object does not exists"); } $location = $this->ensureLocation($bucket, $newName); try { if (!ftp_rename($this->conn, $this->getPath($bucket, $oldName), $location)) { throw new \ErrorException("Unable to rename '{$oldName}' to '{$newName}'."); } } catch (\Throwable $e) { throw new ServerException($e->getMessage(), $e->getCode(), $e); } return $this->refreshPermissions($bucket, $newName); }
{@inheritdoc}
public function replace( BucketInterface $bucket, BucketInterface $destination, string $name ): bool { $this->connect(); if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to replace '{$name}', object does not exists"); } $location = $this->ensureLocation($destination, $name); try { if (!ftp_rename($this->conn, $this->getPath($bucket, $name), $location)) { throw new \ErrorException("Unable to replace '{$name}'."); } } catch (\Throwable $e) { throw new ServerException($e->getMessage(), $e->getCode(), $e); } return $this->refreshPermissions($bucket, $name); }
{@inheritdoc}
protected function connect() { if (!empty($this->conn)) { return; } if (!extension_loaded('ftp')) { throw new ServerException( "Unable to initialize ftp storage server, extension 'ftp' not found" ); } $conn = ftp_connect( $this->options['host'], $this->options['port'], $this->options['timeout'] ); if (empty($conn)) { throw new ServerException( "Unable to connect to remote FTP server '{$this->options['host']}'" ); } if (!ftp_login($conn, $this->options['username'], $this->options['password'])) { throw new ServerException( "Unable to authorize on remote FTP server '{$this->options['host']}'" ); } if (!ftp_pasv($conn, $this->options['passive'])) { throw new ServerException( "Unable to set passive mode at remote FTP server '{$this->options['host']}'" ); } $this->conn = $conn; }
Ensure FTP connection. @throws ServerException
protected function ensureLocation(BucketInterface $bucket, string $name): string { $directory = dirname($this->getPath($bucket, $name)); $mode = $bucket->getOption('mode', FilesInterface::RUNTIME); try { if (ftp_chdir($this->conn, $directory)) { ftp_chmod($this->conn, $mode | 0111, $directory); return $this->getPath($bucket, $name); } } catch (\Exception $e) { //Directory has to be created } ftp_chdir($this->conn, $this->options['home']); $directories = explode('/', substr($directory, strlen($this->options['home']))); foreach ($directories as $directory) { if (!$directory) { continue; } try { ftp_chdir($this->conn, $directory); } catch (\Exception $e) { ftp_mkdir($this->conn, $directory); ftp_chmod($this->conn, $mode | 0111, $directory); ftp_chdir($this->conn, $directory); } } return $this->getPath($bucket, $name); }
Ensure that target directory exists and has right permissions. @param BucketInterface $bucket @param string $name @return string @throws ServerException
protected function localFilename(BucketInterface $bucket, string $name): string { $this->connect(); if (!$this->exists($bucket, $name)) { throw new ServerException( "Unable to create local filename for '{$name}', object does not exists" ); } //File should be removed after processing $tempFilename = $this->files->tempFilename($this->files->extension($name)); if (!ftp_get( $this->conn, $tempFilename, $this->getPath($bucket, $name), FTP_BINARY )) { throw new ServerException("Unable to create local filename for '{$name}'"); } return $tempFilename; }
{@inheritdoc}
protected function getPath(BucketInterface $bucket, string $name): string { return $this->files->normalizePath( $this->options['home'] . '/' . $bucket->getOption('directory') . $name ); }
Get full file location on server including homedir. @param BucketInterface $bucket @param string $name @return string
protected function refreshPermissions(BucketInterface $bucket, string $name): bool { if (!$this->options['chmod']) { //No CHMOD altering return true; } $mode = $bucket->getOption('mode', FilesInterface::RUNTIME); return ftp_chmod($this->conn, $mode, $this->getPath($bucket, $name)) !== false; }
Refresh file permissions accordingly to container options. @param BucketInterface $bucket @param string $name @return bool
public function rename(string $newName): ObjectInterface { $this->bucket->rename($this->name, $newName); $this->name = $newName; return $this; }
{@inheritdoc}
public function copy(BucketInterface $destination): ObjectInterface { $object = clone $this; $object->bucket = $destination; $this->bucket->copy($destination, $this->name); return $object; }
{@inheritdoc}
public function replace(BucketInterface $destination): ObjectInterface { $this->bucket->replace($destination, $this->name); $this->bucket = $destination; return $this; }
{@inheritdoc}
public function withClient(ClientInterface $client): AmazonServer { $server = clone $this; $server->client = $client; return $this; }
Version of driver with alternative client being set up. @param ClientInterface $client @return self
public function exists( BucketInterface $bucket, string $name, ResponseInterface &$response = null ): bool { $response = $this->run($this->buildRequest('HEAD', $bucket, $name), [404]); if (empty($response) || $response->getStatusCode() !== 200) { return false; } return true; }
{@inheritdoc}
public function size(BucketInterface $bucket, string $name): ?int { if (!$this->exists($bucket, $name, $response)) { return null; } /** @var ResponseInterface $response */ return (int)$response->getHeaderLine('Content-Length'); }
{@inheritdoc}
public function put(BucketInterface $bucket, string $name, StreamInterface $stream): bool { if (empty($mimetype = mimetype_from_filename($name))) { $mimetype = self::DEFAULT_MIMETYPE; } $request = $this->buildRequest( 'PUT', $bucket, $name, $this->createHeaders($bucket, $name, $stream), [ 'Acl' => $bucket->getOption('public') ? 'public-read' : 'private', 'Content-Type' => $mimetype ] ); $stream->rewind(); return $this->run($request->withBody($stream)) !== null; }
{@inheritdoc}
public function getStream(BucketInterface $bucket, string $name): StreamInterface { return $this->run($this->buildRequest('GET', $bucket, $name))->getBody(); }
{@inheritdoc}
public function delete(BucketInterface $bucket, string $name) { if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to delete object, file not found"); } $this->run($this->buildRequest('DELETE', $bucket, $name)); }
{@inheritdoc}
public function rename(BucketInterface $bucket, string $oldName, string $newName): bool { $request = $this->buildRequest( 'PUT', $bucket, $newName, [], [ 'Acl' => $bucket->getOption('public') ? 'public-read' : 'private', 'Copy-Source' => $this->buildUri($bucket, $oldName)->getPath() ] ); $this->run($request); $this->delete($bucket, $oldName); return true; }
{@inheritdoc}
public function copy(BucketInterface $bucket, BucketInterface $destination, string $name): bool { $request = $this->buildRequest( 'PUT', $destination, $name, [], [ 'Acl' => $destination->getOption('public') ? 'public-read' : 'private', 'Copy-Source' => $this->buildUri($bucket, $name)->getPath() ] ); $this->run($request); return true; }
{@inheritdoc}
protected function buildUri(BucketInterface $bucket, string $name): UriInterface { return new Uri( $this->options['server'] . '/' . $bucket->getOption('bucket') . '/' . rawurlencode($name) ); }
Create instance of UriInterface based on provided bucket options and storage object name. @param BucketInterface $bucket @param string $name @return UriInterface
protected function buildRequest( string $method, BucketInterface $bucket, string $name, array $headers = [], array $commands = [] ): RequestInterface { $headers += [ 'Date' => gmdate('D, d M Y H:i:s T'), 'Content-MD5' => '', 'Content-Type' => '' ]; $packedCommands = $this->packCommands($commands); return $this->signRequest( new Request($method, $this->buildUri($bucket, $name), $headers + $packedCommands), $packedCommands ); }
Helper to create configured PSR7 request with set of amazon commands. @param string $method @param BucketInterface $bucket @param string $name @param array $headers @param array $commands Amazon commands associated with values. @return RequestInterface
private function packCommands(array $commands): array { $headers = []; foreach ($commands as $command => $value) { $headers['X-Amz-' . $command] = $value; } return $headers; }
Generate request headers based on provided set of amazon commands. @param array $commands @return array
private function run(RequestInterface $request, array $skipCodes = []): ?ResponseInterface { try { return $this->client->send($request); } catch (GuzzleException $e) { if (in_array($e->getCode(), $skipCodes)) { return null; } throw new ServerException($e->getMessage(), $e->getCode(), $e); } }
Wrap guzzle errors into @param RequestInterface $request @param array $skipCodes Method should return null if code matched. @return ResponseInterface
private function signRequest( RequestInterface $request, array $packedCommands = [] ): RequestInterface { $signature = [ $request->getMethod(), $request->getHeaderLine('Content-MD5'), $request->getHeaderLine('Content-Type'), $request->getHeaderLine('Date') ]; $normalizedCommands = []; foreach ($packedCommands as $command => $value) { if (!empty($value)) { $normalizedCommands[] = strtolower($command) . ':' . $value; } } if (!empty($normalizedCommands)) { sort($normalizedCommands); $signature[] = join("\n", $normalizedCommands); } $signature[] = $request->getUri()->getPath(); return $request->withAddedHeader( 'Authorization', 'AWS ' . $this->options['key'] . ':' . base64_encode(hash_hmac( 'sha1', join("\n", $signature), $this->options['secret'], true )) ); }
Sign amazon request. @param RequestInterface $request @param array $packedCommands Headers generated based on request commands, see packCommands() method for more information. @return RequestInterface
private function createHeaders(BucketInterface $bucket, string $name, StreamInterface $stream): array { if (empty($mimetype = mimetype_from_filename($name))) { $mimetype = self::DEFAULT_MIMETYPE; }; //Possible to add custom headers into the bucket $headers = $bucket->getOption('headers', []); if (!empty($maxAge = $bucket->getOption('maxAge', 0))) { //Shortcut $headers['Cache-control'] = 'max-age=' . $bucket->getOption('maxAge', 0) . ', public'; $headers['Expires'] = gmdate( 'D, d M Y H:i:s T', time() + $bucket->getOption('maxAge', 0) ); } $stream->rewind(); return $headers + [ 'Content-MD5' => base64_encode(md5($stream->getContents(), true)), 'Content-Type' => $mimetype ]; }
Generate object headers. @param BucketInterface $bucket @param string $name @param StreamInterface $stream @return array
public static function make($payload, $method = 'md5', $raw_output = false) { return $method == 'murmur' ? static::murmur(serialize($payload)) : hash($method, serialize($payload), $raw_output); }
Create ah hash for payload @param mixed $payload The payload string/object/array @param integer $method The hashing method, default is "md5" @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits. @return string The hash string
public function exists(BucketInterface $bucket, string $name): bool { $this->connect(); return file_exists($this->castRemoteFilename($bucket, $name)); }
{@inheritdoc}
public function size(BucketInterface $bucket, string $name): ?int { $this->connect(); if (!$this->exists($bucket, $name)) { return null; } return filesize($this->castRemoteFilename($bucket, $name)); }
{@inheritdoc}
public function put(BucketInterface $bucket, string $name, StreamInterface $stream): bool { $this->connect(); $stream->rewind(); $expectedSize = $stream->getSize(); //Make sure target directory exists $this->ensureLocation($bucket, $name); //Remote file $destination = fopen($this->castRemoteFilename($bucket, $name), 'w'); $resource = StreamWrapper::getResource($stream); try { $size = stream_copy_to_stream($resource, $destination); } finally { StreamWrapper::release($resource); fclose($resource); fclose($destination); } return $expectedSize == $size && $this->refreshPermissions($bucket, $name); }
{@inheritdoc}
public function getStream(BucketInterface $bucket, string $name): StreamInterface { $this->connect(); //Thought native sftp resource return stream_for(fopen($this->castRemoteFilename($bucket, $name), 'rb')); }
{@inheritdoc}
public function delete(BucketInterface $bucket, string $name) { $this->connect(); if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to delete object, file not found"); } ssh2_sftp_unlink($this->conn, $path = $this->castPath($bucket, $name)); //Cleaning file cache for removed file clearstatcache(false, $path); }
{@inheritdoc}
public function rename(BucketInterface $bucket, string $oldName, string $newName): bool { $this->connect(); if (!$this->exists($bucket, $oldName)) { throw new ServerException( "Unable to rename storage object '{$oldName}', object does not exists at SFTP server" ); } $location = $this->ensureLocation($bucket, $newName); if (file_exists($this->castRemoteFilename($bucket, $newName))) { //We have to clean location before renaming $this->delete($bucket, $newName); } if (!ssh2_sftp_rename($this->conn, $this->castPath($bucket, $oldName), $location)) { throw new ServerException( "Unable to rename storage object '{$oldName}' to '{$newName}'" ); } return $this->refreshPermissions($bucket, $newName); }
{@inheritdoc}
protected function connect() { if (!empty($this->conn)) { return; } if (!extension_loaded('ssh2')) { throw new ServerException( "Unable to initialize sftp storage server, extension 'ssh2' not found" ); } $session = ssh2_connect( $this->options['host'], $this->options['port'], $this->options['methods'] ); if (empty($session)) { throw new ServerException( "Unable to connect to remote SSH server '{$this->options['host']}'" ); } //Authorization switch ($this->options['authMethod']) { case self::NONE: ssh2_auth_none($session, $this->options['username']); break; case self::PASSWORD: ssh2_auth_password( $session, $this->options['username'], $this->options['password'] ); break; case self::PUB_KEY: ssh2_auth_pubkey_file( $session, $this->options['username'], $this->options['publicKey'], $this->options['privateKey'], $this->options['secret'] ); break; } $this->conn = ssh2_sftp($session); }
Ensure that SSH connection is up and can be used for file operations. @throws ServerException
protected function castRemoteFilename(BucketInterface $bucket, string $name): string { return 'ssh2.sftp://' . $this->conn . $this->castPath($bucket, $name); }
Get ssh2 specific uri which can be used in default php functions. Assigned to ssh2.sftp stream wrapper. @param BucketInterface $bucket @param string $name @return string
protected function ensureLocation(BucketInterface $bucket, string $name): string { $directory = dirname($this->castPath($bucket, $name)); $mode = $bucket->getOption('mode', FilesInterface::RUNTIME); if (file_exists('ssh2.sftp://' . $this->conn . $directory)) { if (function_exists('ssh2_sftp_chmod')) { ssh2_sftp_chmod($this->conn, $directory, $mode | 0111); } return $this->castPath($bucket, $name); } $directories = explode('/', substr($directory, strlen($this->options['home']))); $location = $this->options['home']; foreach ($directories as $directory) { if (!$directory) { continue; } $location .= '/' . $directory; if (!file_exists('ssh2.sftp://' . $this->conn . $location)) { if (!ssh2_sftp_mkdir($this->conn, $location)) { throw new ServerException( "Unable to create directory {$location} using sftp connection" ); } if (function_exists('ssh2_sftp_chmod')) { ssh2_sftp_chmod($this->conn, $directory, $mode | 0111); } } } return $this->castPath($bucket, $name); }
Ensure that target directory exists and has right permissions. @param BucketInterface $bucket @param string $name @return string @throws ServerException
protected function refreshPermissions(BucketInterface $bucket, string $name): bool { if (!function_exists('ssh2_sftp_chmod')) { return true; } return ssh2_sftp_chmod( $this->conn, $this->castPath($bucket, $name), $bucket->getOption('mode', FilesInterface::RUNTIME) ); }
Refresh file permissions accordingly to container options. @param BucketInterface $bucket @param string $name @return bool
public static function register(){ ini_set('unserialize_callback_func', 'spl_autoload_call'); spl_autoload_register(function($class){ $cfile = strtr($class,'_\\','//') . '.php'; foreach (static::$paths as $path => $v) { $file = rtrim($path,'/').'/'.$cfile; if(is_file($file)) return include($file); } return false; },false,true); }
Register core autoloader @return bool Returns false if autoloader failed inclusion
public static function using($driver){ foreach((array)$driver as $key => $value){ if(is_numeric($key)){ $drv = $value; $conf = []; } else { $drv = $key; $conf = $value; } $class = 'Cache\\' . ucfirst(strtolower($drv)); if(class_exists($class) && $class::valid()) { static::$driver = new $class($conf); return true; } } return false; }
Load cache drivers with a FCFS strategy @method using @param mixed $driver can be a single driver name string, an array of driver names or a map [ driver_name => driver_options array ] @return bool true if a driver was loaded @example Cache::using('redis'); Cache::using(['redis','files','memory']); // Prefer "redis" over "files" over "memory" caching Cache::using([ 'redis' => [ 'host' => '127.0.0.1', 'prefix' => 'mycache', ], 'files' => [ 'cache_dir' => '/tmp', ], 'memory' ]);