sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function setFields($fields) { foreach ($fields as $name => $value) { $property = '_' . $name; if (property_exists($this, $property)) $this->$property = $value; } }
Устанавливает свойства объекта @internal @param array значения свойств объекта @return void
entailment
public function asArray() { if (func_num_args() == 0) { $fields = array('id'); } else { $fields = array(); $args = func_get_args(); if (count($args)==1 && is_array($args[0])) { $args = $args[0]; } foreach ($args as $f ) { if (is_string($f)) $fields[] = $f; } } $obj = array(); foreach ($fields as $f) { $obj[$f] = $this->$f; } return $obj; }
Возвращает объект в виде массива с указанными полями @return array
entailment
private function _mangleTags($tags) { foreach ($tags as $i => $tag) { $tags[$i] = $this->_mangleTag($tag); } return $tags; }
The same as _mangleTag(), but mangles a list of tags. @see self::_mangleTag @param array $tags Tags to mangle. @return array List of mangled tags.
entailment
public static function enum() { $res = array(); $r = self::getDbConnection()->query('SELECT * FROM menus ORDER BY name'); while ($f = $r->fetch()) { $res[] = new self($f); } return $res; }
Возвращает все созданные меню. @return array
entailment
public static function getById($id) { $f = self::getDbConnection()->fetchAssoc('SELECT * FROM menus WHERE id=?',array($id)); if (!$f) throw new Exception\CMS('Меню ID='.$id.' не найдено'); return new self($f); }
Возвращает меню по его идентификатору. @param int $id ID меню @return Menu @throws Exception\CMS
entailment
public static function getByAlias($alias) { $f = self::getDbConnection()->fetchAssoc('SELECT * FROM menus WHERE alias=?',array($alias)); if (!$f) throw new Exception\CMS('Меню alias='.$alias.' не найдено'); return new self($f); }
Возвращает меню по его алиасу. @param string $alias алиас меню @return Menu @throws Exception\CMS
entailment
public static function getByName($name) { $f = self::getDbConnection()->fetchAssoc('SELECT * FROM menus WHERE name=?',array($name)); if (!$f) new Exception\CMS('Меню name='.$id.' не найдено'); return new self($f); }
Возвращает меню по его названию. @param string $name название меню @return Menu @throws Exception\CMS
entailment
public static function create() { $alias = func_get_arg(0); $name = func_get_arg(1); try { $m = self::getByAlias($alias); } catch (\Exception $e) {} if ($m) throw new Exception\CMS('Меню c таким алиасом уже существует.'); self::getDbConnection()->insert('menus', array( 'alias' => $alias, 'name' => $name )); return self::getById( self::getDbConnection()->lastInsertId() ); }
Создает меню @param string $alias алиас меню @param string $name название меню @return Menu @throws Exception\CMS
entailment
public function save() { try { $m = self::getByAlias($this->alias); } catch (\Exception $e) {} if ($m && $m->id != $this->id) throw new Exception\CMS('Меню c таким алиасом уже существует.'); self::getDbConnection()->update('menus', array( 'alias' => $this->alias, 'name' => $this->name, 'data' => serialize($this->data), ), array('id' => $this->id) ); }
Сохраняет меню @throws Exception\CMS
entailment
public static function factory($type=0, $table = null, $fields = null) { if ($type instanceof ObjectDefinition) { $type_id = $type->id; $od = $type; } elseif ((int)$type) { $type_id = (int)$type; $od = new ObjectDefinition($type_id, $table); } switch ($type_id) { case User::TYPE: $o = User::create(); break; case Catalog::TYPE: if ($fields && $fields['is_server']) { $o = Server::create(); break; } $o = Catalog::create(); break; default: if ( isset(ObjectDefinition::$userClasses[$type_id]) ) { $uc = ObjectDefinition::$userClasses[$type_id]; $o = $uc::create(); } else { $o = Material::create(); } break; } $o->objectDefinition = $od; return $o; }
Создает экземпляр нужного класса в зависимости от "Типа материалов". @internal @param int|ObjectDefinition $type "Тип материалов" объекта @param string $table Таблица БД, в которой хранятся объекты @return DynamicFieldsObject
entailment
public static function fetch($data, $type = 0, $table = null) { if (is_array($data)) { $id = (int)$data['id']; $fields = $data; } else { $id = (int)$data; $fields = null; } if ($type instanceof ObjectDefinition) { $type_id = $type->id; } else { $type_id = $type; } if (!$id || $fields || !isset(self::$instances[$type_id][$id])) { $o = static::factory($type, $table, $fields); if ($id) { if (!$fields) $o->load($id); self::$instances[$type_id][$id] = $o; } } else { $o = self::$instances[$type_id][$id]; } if ($fields) { $o->setFields($fields); } return $o; }
Создает экземпляр нужного класса в зависимости от "Типа материалов", поля загружаются из БД, резульат кэшируется @internal @param array $data поля объекта @param int|ObjectDefinition $type "Тип материалов" объекта @param string $table Таблица БД, в которой хранятся объекты @return DynamicFieldsObject
entailment
public function setFields($fields) { $this->fields = $fields; $this->raw_fields = array_merge($this->raw_fields, $fields); parent::setFields($fields); return $this; }
Устанавливает поля объекта @internal @param array $fields поля объекта
entailment
private function load($id) { $fields = $this->getDbConnection()->fetchAssoc('SELECT * FROM `'.$this->objectDefinition->table.'` WHERE id = ?', array($id)); if (!$fields) throw new \Exception('Object '.$this->objectDefinition->table.':'.$id.' is not found'); $this->setFields($fields); $this->_id = $id; return $this; }
Загружает из БД объект @internal @param int $id ID объекта
entailment
public static function getByIdType($id, $type) { $o = self::factory($type); $o->load($id); return $o; }
Возвращает объект по ID и "Типу материалов". @param int $id ID объекта @param int $type "Тип материалов" объекта @param string $table Таблица БД, в которой хранятся поля объекта @return DynamicFieldsObject
entailment
public function getDynamicField($name) { $fields = $this->getFieldsDef(); if (!isset($fields[$name])) { if (isset($this->fields[$name])) return $this->fields[$name]; return false; } //throw new LogicException('Property "'.$name.'" does not exist.'); switch($fields[$name]['type']){ //case FIELD_FORM: // return $this->getFormField($fields[$name]); // break; case FIELD_LINK: case FIELD_MATERIAL: return $this->getMaterialField($fields[$name]); break; //case FIELD_HLINK: // return $this->getHlinkField($fields[$name]); // break; case FIELD_LINKSET: case FIELD_MATSET: return $this->getLinksetField($fields[$name]); break; case FIELD_LINKSET2: return $this->getLinkset2Field($fields[$name]); break; default: return $this->getPlainField($fields[$name]); } }
Возвращает прочитанное из БД поле объекта в соответствии с типом поля @internal @param string $name имя поля @return mixed
entailment
private function getPlainField($field) { if (!isset($this->fields[$field['name']])) { $this->fields[$field['name']] = $this->getDbConnection()->fetchColumn('SELECT `'.$field['name'].'` FROM '.$this->table.' WHERE id='.(int)$this->fields['id']); } return $this->fields[$field['name']]; }
Чтение из БД "простого" поля: текст, число, логическое и т.д. @internal @param string $name имя поля @return mixed
entailment
private function getLinksetField($field) { if (!isset($this->fields[$field['name']])) { $this->fields[$field['name']] = new Iterator\Linkset( $this, $field ); $this->fields[$field['name']]->orderBy('b.tag','ASC'); } return $this->fields[$field['name']]; }
Чтение из БД группы материалов, связанных с полем @internal @param string $name имя поля @return Iterator\Object
entailment
private function getLinkset2Field($field) { if (!isset($this->fields[$field['name']])) { $this->fields[$field['name']] = new Iterator\Linkset2( $this, $field ); } return $this->fields[$field['name']]; }
Чтение из БД группы материалов, связанных с полем @internal @param string $name имя поля @return Iterator\Object
entailment
private function getMaterialField($field) { if (isset($this->fields[$field['name']]) && is_object($this->fields[$field['name']])) return $this->fields[$field['name']]; $slot = new Cache\Slot\MaterialField($this->table, $this->fields['id'], $field['name']); if (!$this->fields['id'] || false === ($_tmp = $slot->load())) { if (!isset($this->fields[$field['name']])) $this->fields[$field['name']] = $this->getPlainField($field); if ($this->fields[$field['name']]) { try { if ($field['pseudo_type'] == PSEUDO_FIELD_LINK_CATALOG) { $this->fields[$field['name']] = Catalog::getById($this->fields[$field['name']]); } elseif ($field['pseudo_type'] == PSEUDO_FIELD_LINK_USER) { $this->fields[$field['name']] = User::getById($this->fields[$field['name']]); } else { if ($field['type'] == FIELD_LINK) { if ($field['len']) { $c = Catalog::getById($field['len']); if (!$c) throw new Exception\CMS('Catalog '.$field['len'].' is not found.'); $type = $c->materialsType; } else $type = $this->objectDefinition->id; } else { $type = $field['len']; } $this->fields[$field['name']] = self::getByIdType( $this->fields[$field['name']], $type ); } } catch (\Exception $e) { $this->fields[$field['name']] = null; } } else { $this->fields[$field['name']] = null; } $slot->addTag(new Cache\Tag\Material($this->table, $this->fields['id'])); $slot->save($this->fields[$field['name']]); } else { $this->fields[$field['name']] = $_tmp; } return $this->fields[$field['name']]; }
Чтение из БД группы материала, связанных с полем @internal @param string $name имя поля @return DynamicFieldsObject
entailment
private function getHlinkField($field) { if (isset($this->fields[$field['name']]) && is_array($this->fields[$field['name']])) return $this->fields[$field['name']]; $slot = new Cache\Slot\MaterialField($this->table, $this->fields['id'], $field['name']); if (false === ($a = $slot->load())) { if (!isset($this->fields[$field['name']])) $this->fields[$field['name']] = $this->get_plain_field($field); $a = $this->getDbConnection()->fetchAssoc('SELECT * FROM field_link WHERE link_id='.(int)$this->fields[$field['name']]); if ($a['structure_id']) { if ($a['structure_type'] == 'main') { $c = Catalog::getById($a['structure_id']); if ($c) { $a['link_value'] = $c->url; $a['name'] = $c->name; } } else { $b = $this->getDbConnection()->fetchAssoc('SELECT idcat, alias, name FROM '.$a['structure_type'].' WHERE id='.$a['structure_id']); if ($b) { $c = Catalog::getById($b['idcat']); if ($c) $path = $c->url; $a['link_value'] = $path.$b['alias'].'.html'; $a['alias'] = $b['alias']; $a['idcat'] = $b['idcat']; $a['name'] = $b['name']; } } } $this->fields[$field['name']] = $a; $slot->addTag(new Cache\Tag\Material($this->table, $this->fields['id'])); $slot->save($this->fields[$field['name']]); } else { $this->fields[$field['name']] = $a; } return $this->fields[$field['name']]; }
Чтение из БД поля-ссылки @internal @param string $name имя поля @return array
entailment
public function selectLinks($fieldname, $fields='A.*', $where='', $order='B.tag', $group='', $limit='') { $flds = $this->getFieldsDef(); if (!isset($flds[$fieldname])) throw new Exception\CMS('Property "'.$fieldname.'" does not exist.'); $field = $flds[$fieldname]; if ($field['type'] != FIELD_LINKSET && $field['type'] != FIELD_MATSET) return false; if ($fields != '*') $fields = 'A.id,'.$fields; $w = PUBLISHED.' and '; if ($field['type'] == FIELD_LINKSET) { if ($field['len'] == CATALOG_VIRTUAL_USERS) { $tableto = User::TABLE; $dtype = User::TYPE; $w = ''; } elseif ($field['pseudo_type'] == PSEUDO_FIELD_CATOLOGS) { $tableto = Catalog::TABLE; $dtype = Catalog::TYPE; $w = ''; } elseif (!$field['len']) { $tableto = $this->table; $dtype = $this->objectDefinition->id; } else { $c = Catalog::getById($field['len']); if (!$c) throw new Exception\CMS('Catalog '.$field['len'].' is not found.'); $dtype = $c->materialsObjectDefinition->id; $tableto = $c->materialsObjectDefinition->table; } } else { $od = new ObjectDefinition($field['len']); $tableto = $od->table; $dtype = $field['len']; } $linktable = $this->table.'_'.$tableto.'_'.$field['name']; $sql = 'SELECT '.$fields.' FROM '.$tableto.' A LEFT JOIN '.$linktable.' B ON (A.id=B.dest) WHERE '.$w.' B.id='.$this->fields['id']; if ($where) $sql .= ' and ('.$where.')'; if ($group) $sql .= ' GROUP BY '.$group; if ($order) $sql .= ' ORDER BY '.$order; if ($limit) $sql .= ' LIMIT '.$limit; $res = new Iterator\Object(); $r = $this->getDbConnection()->query($sql); while ($f = $r->fetch()) { $res->append(DynamicFieldsObject::fetch($f, $dtype, $tableto)); } return $res; }
DEPRECATED Чтение из БД объектов, на которые ссылается поле При построении SQL запроса к базе данных, таблице, из которой производится чтение полей объектов присваивается псевдоним "A", а таблице, в которой хранятся связи между объектами - "B". Рекомендуется использовать эти псевдонимы, если вы используете параметры $fields, $where, $order, $group, $limit @deprecated @internal @param string $fieldname имя поля @param string $fields поля, которые запрашивать из таблицы БД при выборке @param string $where параметр WHERE запроса @param string $order параметр ORDER BY запроса @param string $group параметр GROUP BY запроса @param string $limit параметр LIMIT запроса @return Iterator\Object
entailment
public function selectLinksIn($from,$field,$fields='*',$where='',$order='',$group='',$limit='') { if (is_int($from)) { $type = $from; $tablefrom = ObjectDefinition::findById($type)->table; } else { $tablefrom = $from; $type = ObjectDefinition::findByTable($tablefrom)->id; } if ($fields != '*') $fields = 'A.id,'.$fields; $f = $this->getDbConnection()->fetchArray("select A.len, A.type from types_fields A, types B where B.id=A.id and B.id=$type and A.name='$field'"); if (!$f) throw new Exception\CMS('Field '.$field.' is not found for type '.$type); if ($f[1] == FIELD_LINKSET) { if ($f[0]) { $c = Catalog::getById($f[0]); $tableto = $c->materialsTable; } else $tableto = $tablefrom; } elseif ($f[1] == FIELD_MATSET) { $tableto = ObjectDefinition::findById($f[0])->table; } else { return FALSE; } $linktable = $tablefrom.'_'.$tableto.'_'.$field; $sql = 'SELECT '.$fields.' FROM '.$tablefrom.' A LEFT JOIN '.$linktable.' B ON (A.id=B.id) WHERE '.PUBLISHED.' and B.dest='.$this->fields['id']; if ($where) $sql .= ' and '.$where; if ($group) $sql .= ' group by '.$group; if ($order) $sql .= ' order by '.$order; if ($limit) $sql .= ' limit '.$limit; $res = new Iterator\Object(); $r = $this->getDbConnection()->query($sql); while ($f = $r->fetch()) { $res->append(self::fetch($f, $type, $tablefrom)); } return $res; }
DEPRECATED Чтение из БД объектов, которые связаны полем $field с объектом. При построении SQL запроса к базе данных, таблице, из которой производится чтение полей объектов присваивается псевдоним "A", а таблице, в которой хранятся связи между объектами - "B". Рекомендуется использовать эти псевдонимы, если вы используете параметры $fields, $where, $order, $group, $limit @internal @param int|string $from ID "Типа материалов" или имя таблицы БД, в которой хранятся объекты @param string $field имя поля по которому объекты связаны с текущим @param string $fields поля, которые запрашивать из таблицы БД при выборке @param string $where параметр WHERE запроса @param string $order параметр ORDER BY запроса @param string $group параметр GROUP BY запроса @param string $limit параметр LIMIT запроса @return Iterator\Object
entailment
public function delete() { // удаление ссылок с удаляемого материала $r = $this->getDbConnection()->query("select B.name, B.len, B.type, B.pseudo_type from types A, types_fields B where A.alias='".$this->table."' and B.id=A.id and (B.type=".FIELD_LINKSET." or B.type=".FIELD_MATSET.")"); while ($f = $r->fetch(\PDO::FETCH_NUM)) { $tbl = ObjectDefinition::get_table($f[2], $f[1], $this->objectDefinition->id, $f[3]); if ($f[2] != FIELD_LINKSET && $f[3] != PSEUDO_FIELD_TAGS) { $r1 = $this->getDbConnection()->query("select dest from ".$this->table."_".$tbl."_".$f[0]." where id=".$this->id); while ($f1 = $r1->fetch(\PDO::FETCH_NUM)) { $m = Material::getById($f1[0], $f[1], $tbl); $m->delete(); } } $this->getDbConnection()->executeQuery("delete from ".$this->table."_".$tbl."_"."$f[0] where id=".$this->id); } // удаление ссылок на этот материал if (property_exists($this, 'idcat') && $this->idcat >= 0) { $r = $this->getDbConnection()->query("select A.alias, B.name, B.type from types A, types_fields B where B.id=A.id and B.len=".$this->idcat." and (B.type=".FIELD_LINK." or B.type=".FIELD_LINKSET.")"); while ($f = $r->fetch(\PDO::FETCH_NUM)) { if ($f[2] == FIELD_LINK) { $this->getDbConnection()->executeQuery("update $f[0] set $f[1]=0 where $f[1]=".$this->id); } else { $this->getDbConnection()->executeQuery("delete from $f[0]"."_".$this->table."_"."$f[1] where dest=".$this->id); } } } else { $r = $this->getDbConnection()->query("select A.alias, B.name from types A, types_fields B where B.id=A.id and B.len = ".$this->objectDefinition->id." and B.type=".FIELD_MATSET); while ($f = $r->fetch(\PDO::FETCH_NUM)) { $this->getDbConnection()->executeQuery("delete from $f[0]"."_".$this->table."_"."$f[1] where dest=".$this->id); } } // удаление самого материала $this->getDbConnection()->executeQuery("delete from ".$this->table." where id=".$this->id); }
Удаляет объект из БД @return void
entailment
public function getChildren() { if (!$this->_children) { if ($this->getParam('iterator')) { $this->_children = $this->getParam('iterator'); } else { try { $this->_children = $this->getCatalog()->getMaterials(); if ($this->getParam('order')) { $this->_children->orderBy($this->getParam('order'), $this->getParam('sort')); } $this->_children->orderBy('id', 'ASC', true); if ($this->getParam('subfolders') || $this->getParam('subsections')) { $this->_children->subfolders(); } if ($this->getParam('filter')) { list($filter) = explode(';',$this->getParam('filter')); eval('$this->_children->'.$filter.';'); } } catch (\Exception $e) { return []; } } if ($this->getParam('limit')) $this->_children->setItemCountPerPage($this->getParam('limit')); if ($this->getParam('where')) $this->_children->where($this->getParam('where')); $this->_children->setCurrentPageNumber( $this->getPage() ); } return $this->_children; }
Список материалов для показа
entailment
public static function directorySize($path){ $bytestotal = 0; $path = realpath($path); if($path!==false && $path!='' && file_exists($path)){ foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)) as $object){ $bytestotal += $object->getSize(); } } return $bytestotal; }
/* Вычисляет размер каталога @param string $path путь @return int
entailment
public static function hbytes($bytes, $base10=false, $round=2, $labels=array('', ' Kb', ' Mb', ' Gb')) { if ((! is_array($labels)) || (count($labels) <= 0)) return null; $step = $base10 ? 3 : 10 ; $base = $base10 ? 10 : 2; $log = (int)(log10($bytes)/log10($base)); krsort($labels); foreach ($labels as $p=>$lab) { $pow = $p * $step; if ($log < $pow) continue; $text = round($bytes/pow($base,$pow),$round) . $lab; break; } return $text; }
Форматирует число байт в кб, мб и т.д. @param int bytes is the size @param bool base10 enable base 10 representation, otherwise default base 2 is used @param int round number of fractional digits @param array labels strings associated to each 2^10 or 10^3(base10==true) multiple of base units
entailment
public static function curlGet($url) { $defaults = array( CURLOPT_URL => $url, //CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => TRUE, //CURLOPT_TIMEOUT => 4 ); $ch = curl_init(); curl_setopt_array($ch, $defaults); if( ! $result = curl_exec($ch)) { trigger_error(curl_error($ch)); } curl_close($ch); return $result; }
Send a GET requst using cURL @param string $url to request @param array $get values to send @param array $options for cURL @return string
entailment
public static function addslashes($value) { if (is_array($value)) { while (list($_nm,$_vl)=each($value)) { $value[$_nm] = self::addslashes($_vl); } $result = $value; } else { $result = addslashes($value); } return $result; }
/* Если аргумент строка - применяет к ней PHP-функцию addslashes() Если аргумент массив - применяет к каждому элементу массива Util::addslashes() @param mixed $value @return mixed
entailment
public static function copyRecord($table, $id_row, $id, $replace) { $conn = self::getDbConnection(); $row = $conn->fetchAssoc("SELECT * FROM $table WHERE $id_row='$id'"); if (!$row) throw new Exception\CMS('Source record id not found'); foreach ($replace as $name => $value) if (isset($row[$name])) $row[$name] = $value; unset($row[$id_row]); $conn->insert($table, $row); return $conn->lastInsertId(); }
/* Создает дубликат записи в таблице @param string $table имя таблицы @param string $id_row имя primary столбца (должен быть auto_increment) @param integer $id ID записи, которая копируется @param array $replace ассоциативный массив названий и значений столбцов, которые нужно заменить, а не копировать @return int ID новой записи @throws Exception\CMS
entailment
public static function getMysqlVersion() { $conn = self::getDbConnection(); $data = $conn->fetchArray('SELECT VERSION()'); if ($data[0]) { $my_ver = $data[0]; } else { $data = $conn->fetchArray('SHOW VARIABLES LIKE \'version\''); if ($data[0]) { $my_ver = $data[0]; } } if (!isset($my_ver)) $my_ver = '3.21.0'; return preg_replace('/[a-z\-]+/i', '', strtolower($my_ver)); }
/* Возвращает версию MySQL @param string $ver версия в формате x.y.z
entailment
public static function get($name, $int = FALSE) { if ($int) { return (isset($_GET[$name]))?(int)$_GET[$name]:0; } else { return (isset($_GET[$name]))?$_GET[$name]:FALSE; } }
/* Возвращает $_GET[$name] или false, если $_GET[$name] не установлен @param string $name имя параметра @param bool $int возвращать как целое число @return mixed
entailment
public static function post($name, $int = FALSE) { if ($int) { return (isset($_POST[$name]))?(int)$_POST[$name]:0; } else { return (isset($_POST[$name]))?$_POST[$name]:FALSE; } }
/* Возвращает $_POST[$name] или false, если $_POST[$name] не установлен @param string $name имя параметра @param bool $int возвращать как целое число @return mixed
entailment
public static function extErrorMessage($e) { if ($e instanceof Exception\CMS) { return $e->getExtMessage(); } else { return 'In file <b>'.$e->getFile().'</b> on line: '.$e->getLine()."<br /><br /><b>Stack trace:</b><br />".nl2br($e->getTraceAsString()); } }
/* Возвращает расширенное описание ошибки @param Exception $e исключение @return string
entailment
public function add($material, $check = true) { if ($material->objectDefinition->id != $this->objectDefinition->id) { throw new \Exception('Illegal type of material '.$material->objectDefinition->id.'. Must be '.$this->objectDefinition->id); } $this->fetchElements(); return parent::add($material, $check); }
Добавляет произвольный материал в итератор @param \Cetera\DynamicFieldsObject $material @return void
entailment
public function remove(\Cetera\DynamicFieldsObject $material) { if ($material->objectDefinition->id != $this->objectDefinition->id) { throw new \Exception('Illegal type of material '.$material->objectDefinition->id.'. Must be '.$this->objectDefinition->id); } $this->fetchElements(); foreach ($this->elements as $key => $value) { if ($value->id == $material->id) { unset($this->elements[$key]); $this->elements = array_values($this->elements); break; } } return $this; }
Удаляет материал из итератора @param \Cetera\DynamicFieldsObject $material @return void
entailment
public function replace($tableExpression, array $data, array $types = array()) { $this->connect(); if (empty($data)) { return $this->executeUpdate('REPLACE INTO ' . $tableExpression . ' ()' . ' VALUES ()'); } return $this->executeUpdate( 'REPLACE INTO ' . $tableExpression . ' (' . implode(', ', array_keys($data)) . ')' . ' VALUES (' . implode(', ', array_fill(0, count($data), '?')) . ')', array_values($data), is_string(key($types)) ? $this->extractTypeValues($data, $types) : $types ); }
Inserts a table row with specified data. REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. Table expression and columns are not escaped and are not safe for user-input. @param string $tableExpression The expression of the table to insert data into, quoted or unquoted. @param array $data An associative array containing column-value pairs. @param array $types Types of the inserted data. @return integer The number of affected rows.
entailment
public function getModules() { if (!$this->_modules) { $translator = $this->application->getTranslator(); $this->_modules = [ 'structure' => [ 'position' => MENU_SITE, 'name' => $translator->_('Структура и материалы'), 'iconCls' => 'tree-folder-visible', 'class' => 'Cetera.panel.Structure' ], 'materials' => [ 'position' => MENU_SITE, 'name' => $translator->_('Материалы'), 'icon' => 'images/math2.gif', 'iconCls' => 'x-fa fa-file-text', 'class' => 'Cetera.panel.MaterialsByCatalog' ] ]; if ($this->application->getUser() && $this->application->getUser()->allowAdmin()) { $this->_modules['widgets'] = array( 'position' => MENU_SITE, 'name' => $translator->_('Шаблоны виджетов'), 'icon' => 'images/widget_icon.png', 'iconCls' => 'x-fa fa-file-code-o', 'class' => 'Cetera.widget.templates.Panel', 'ext6_compat'=> true ); $this->_modules['widget_areas'] = array( 'position' => MENU_SITE, 'name' => $translator->_('Области'), 'icon' => 'images/widget_icon.png', 'iconCls' => 'x-fa fa-cog', 'class' => 'Cetera.widget.Panel' ); $this->_modules['menus'] = array( 'position' => MENU_SITE, 'name' => $translator->_('Меню'), 'icon' => 'images/icon_menu.png', 'iconCls' => 'x-fa fa-bars', 'class' => 'Cetera.panel.Menu' ); $this->_modules['setup'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Настройки'), 'icon' => 'images/setup_small.gif', 'iconCls' => 'x-fa fa-cogs', 'class' => 'Cetera.panel.Setup' ); $this->_modules['types'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Типы материалов'), 'icon' => 'images/setup_small.gif', 'iconCls' => 'x-fa fa-cogs', 'class' => 'Cetera.panel.MaterialTypes' ); $this->_modules['users'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Пользователи'), 'icon' => 'images/user.gif', 'iconCls' => 'x-fa fa-user', 'class' => 'Cetera.users.MainPanel' ); $this->_modules['groups'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Группы пользователей'), 'url' => 'include/ui_groups.php', 'icon' => 'images/users.gif', 'iconCls' => 'x-fa fa-users', 'class' => 'GroupsPanel' ); $this->_modules['eventlog'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Журнал'), 'icon' => 'images/audit1.gif', 'class' => 'EventlogPanel', 'iconCls' => 'x-fa fa-file-text-o', 'class' => 'Cetera.eventlog.Panel', ); $this->_modules['dbrepair'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Проверка и ремонт БД'), 'icon' => 'images/icon_repair.gif', 'iconCls' => 'x-fa fa-medkit', 'class' => 'Cetera.panel.Repair', 'ext6_compat'=> true ); $this->_modules['mail_templates'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Почтовые шаблоны'), 'icon' => 'images/mail.gif', 'iconCls' => 'x-fa fa-envelope', 'class' => 'Cetera.grid.MailTemplates', ); $this->_modules['plugins'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Плагины'), 'icon' => 'images/plugin.png', 'class' => 'Cetera.plugin.List', 'iconCls' => 'x-fa fa-plug' ); $this->_modules['themes'] = array( 'position' => MENU_SERVICE, 'name' => $translator->_('Темы'), 'icon' => 'images/16X16/gallery.gif', 'iconCls' => 'x-fa fa-picture-o', 'class' => 'Cetera.theme.List', ); } } return $this->_modules + $this->_user_modules; }
/* Возвращает модули @return array
entailment
public function authenticate() { $this->_authenticateResultInfo = array( 'code' => \Zend_Auth_Result::FAILURE, 'identity' => null ); $user = null; if ($this->_username) $user = User::getByLogin($this->_username); if (!$user && $this->_email) $user = User::getByEmail($this->_email); if (!$user || !$user->isEnabled() || (!$user->allowBackOffice() && $this->_backoffice)) { $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; return $this->_authenticateCreateAuthResult(); } if (!$user->checkPassword($this->_password)) { $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; return $this->_authenticateCreateAuthResult(); } $this->_authenticateResultInfo['code'] = \Zend_Auth_Result::SUCCESS; $this->_authenticateResultInfo['identity'] = array( 'uniq' => $user->authorize($this->_remember), 'user_id' => $user->id ); if ($this->_remember) \Zend_Session::rememberMe(REMEMBER_ME_SECONDS); //else \Zend_Session::regenerateId(); return $this->_authenticateCreateAuthResult(); }
Авторизовать пользователя Пример: $result = \Zend_Auth::getInstance()->authenticate(new \Cetera\UserAuthAdapter(array(<br> 'login' => $_POST['login'],<br> 'pass' => $_POST['password'],<br> 'remember' => $_POST['remember']<br> ))); <br> <br> switch ($result->getCode()) {<br> case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:<br> echo 'Пользователь не найден';<br> break;<br> case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:<br> echo 'Неверный пароль';<br> break;<br> case Zend_Auth_Result::SUCCESS:<br> echo 'Добро пожаловать!';<br> break;<br> }<br> @return \Zend_Auth_Result
entailment
public function read($id) { $res = $this->getDbConnection()->fetchColumn('SELECT value FROM session_data WHERE id=?',[$id],0); if (!$res) $res = ''; return $res; }
Read session data @param string $id
entailment
public function write($id, $data) { if (!$data) $this->getDbConnection()->executeQuery('DELETE FROM session_data WHERE id=?',[$id]); else $this->getDbConnection()->executeQuery('REPLACE INTO session_data SET timestamp=?, id=?, value=?',[time(),$id,$data]); return true; }
Write Session - commit data to resource @param string $id @param mixed $data
entailment
public function evaluate() { $node = $this->getNode(); if ($node instanceof NodeInterface) { $contentContext = $node->getContext(); if ($contentContext instanceof \Neos\Neos\Domain\Service\ContentContext) { $site = $contentContext->getCurrentSite(); $siteConfiguration = $this->siteConfigurationRepository->findOneBySite($site); return $siteConfiguration; } } return null; }
Find a SiteConfiguration entity for the current site @return \Neos\GoogleAnalytics\Domain\Model\SiteConfiguration
entailment
public function jsonSerialize() { $totals = $this->result->getTotalsForAllResults(); $sanitizedTotals = []; foreach ($totals as $key => $value) { $replacedKey = str_replace(':', '_', $key); $sanitizedTotals[$replacedKey] = $value; } $columnHeaders = $this->result->getColumnHeaders(); foreach ($columnHeaders as &$columnHeader) { $columnHeader['name'] = str_replace(':', '_', $columnHeader['name']); } $rows = $this->result->getRows(); if (!is_array($rows)) { $rows = []; } $sanitizedRows = []; foreach ($rows as $rowIndex => $row) { foreach ($row as $columnIndex => $columnValue) { $columnName = $columnHeaders[$columnIndex]['name']; if ($columnName === 'ga_date') { $columnValue = substr($columnValue, 0, 4) . '-' . substr($columnValue, 4, 2) . '-' . substr($columnValue, 6, 2); } $sanitizedRows[$rowIndex][$columnName] = $columnValue; } // The simple case that we have 2 columns with 1 dimension and 1 metric if (count($columnHeaders) == 2 && $columnHeaders[0]['columnType'] === 'DIMENSION' && $columnHeaders[1]['columnType'] === 'METRIC') { $sanitizedTotal = $sanitizedTotals[$columnHeaders[1]['name']]; if ($sanitizedTotal > 0) { $sanitizedRows[$rowIndex]['percent'] = round($row[1] / $sanitizedTotal * 100, 2); } else { $sanitizedRows[$rowIndex]['percent'] = 0; } } } return [ 'totals' => $sanitizedTotals, 'rows' => $sanitizedRows ]; }
{@inheritdoc}
entailment
public function getNodeStat(NodeInterface $node, ControllerContext $controllerContext, $statIdentifier, \DateTime $startDate, \DateTime $endDate) { $this->analytics->requireAuthentication(); if (!isset($this->statsSettings[$statIdentifier])) { throw new \InvalidArgumentException(sprintf('Unknown stat identifier "%s"', $statIdentifier), 1416917316); } $statConfiguration = $this->statsSettings[$statIdentifier]; $siteConfiguration = $this->getSiteConfigurationByNode($node); $startDateFormatted = $startDate->format('Y-m-d'); $endDateFormatted = $endDate->format('Y-m-d'); $nodeUri = $this->getLiveNodeUri($node, $controllerContext); $filters = 'ga:pagePath==' . $nodeUri->getPath() . ';ga:hostname==' . $nodeUri->getHost(); $parameters = [ 'filters' => $filters ]; if (isset($statConfiguration['dimensions'])) { $parameters['dimensions'] = $statConfiguration['dimensions']; } if (isset($statConfiguration['sort'])) { $parameters['sort'] = $statConfiguration['sort']; } if (isset($statConfiguration['max-results'])) { $parameters['max-results'] = $statConfiguration['max-results']; } $gaResult = $this->analytics->data_ga->get( 'ga:' . $siteConfiguration->getProfileId(), $startDateFormatted, $endDateFormatted, $statConfiguration['metrics'], $parameters ); return new DataResult($gaResult); }
Get metrics and dimension values for a configured stat TODO Catch "(403) Access Not Configured" (e.g. IP does not match) @param NodeInterface $node @param ControllerContext $controllerContext @param string $statIdentifier @param \DateTime $startDate @param \DateTime $endDate @return DataResult @throws MissingConfigurationException @throws AnalyticsNotAvailableException
entailment
protected function getSiteConfigurationByNode(NodeInterface $node) { $context = $node->getContext(); if (!$context instanceof ContentContext) { throw new \InvalidArgumentException(sprintf('Expected a ContentContext instance in the given node, got %s', get_class($context)), 1415722633); } $site = $context->getCurrentSite(); $siteConfiguration = $this->siteConfigurationRepository->findOneBySite($site); if ($siteConfiguration instanceof SiteConfiguration && $siteConfiguration->getProfileId() !== '') { return $siteConfiguration; } else { if (isset($this->sitesSettings[$site->getNodeName()]['profileId']) && (string)$this->sitesSettings[$site->getNodeName()]['profileId'] !== '') { $siteConfiguration = new SiteConfiguration(); $siteConfiguration->setProfileId($this->sitesSettings[$site->getNodeName()]['profileId']); return $siteConfiguration; } throw new MissingConfigurationException('No profile configured for site', 1415806282); } }
Get a site configuration (which has a Google Analytics profile id) for the given node This will first look for a SiteConfiguration entity and then fall back to site specific settings. @param NodeInterface $node @return SiteConfiguration @throws MissingConfigurationException If no site configuration was found, or the profile was not assigned
entailment
protected function getLiveNodeUri(NodeInterface $node, ControllerContext $controllerContext) { $contextProperties = $node->getContext()->getProperties(); $contextProperties['workspaceName'] = 'live'; $liveContext = $this->contextFactory->create($contextProperties); $liveNode = $liveContext->getNodeByIdentifier($node->getIdentifier()); if ($liveNode === null) { throw new AnalyticsNotAvailableException('Analytics are only available on a published node', 1417450159); } $nodeUriString = $this->linkingService->createNodeUri($controllerContext, $liveNode, null, 'html', true); $nodeUri = new \Neos\Flow\Http\Uri($nodeUriString); return $nodeUri; }
Resolve an URI for the given node in the live workspace (this is where analytics usually are collected) @param NodeInterface $node @param ControllerContext $controllerContext @return \Neos\Flow\Http\Uri @throws AnalyticsNotAvailableException If the node was not yet published and no live workspace URI can be resolved
entailment
public function indexAction() { $siteConfigurations = $this->siteConfigurationRepository->findAll(); $sites = $this->siteRepository->findAll(); $sitesWithConfiguration = []; foreach ($sites as $site) { $item = ['site' => $site]; foreach ($siteConfigurations as $siteConfiguration) { if ($siteConfiguration->getSite() === $site) { $item['configuration'] = $siteConfiguration; } } $sitesWithConfiguration[] = $item; } $this->view->assign('sitesWithConfiguration', $sitesWithConfiguration); $profiles = $this->getGroupedProfiles(); $this->view->assign('groupedProfiles', $profiles); }
Show a list of sites and assigned GA profiles @return void
entailment
public function updateAction(array $siteConfigurations) { foreach ($siteConfigurations as $siteConfiguration) { if ($this->persistenceManager->isNewObject($siteConfiguration)) { $this->siteConfigurationRepository->add($siteConfiguration); } else { $this->siteConfigurationRepository->update($siteConfiguration); } } $this->emitSiteConfigurationChanged(); $this->addFlashMessage('Configuration has been updated.', 'Update', null, [], 1417109043); $this->redirect('index'); }
Update or add site configurations @param array<\Neos\GoogleAnalytics\Domain\Model\SiteConfiguration> $siteConfigurations Array of site configurations @return void
entailment
protected function callActionMethod() { try { parent::callActionMethod(); } catch (\Google_Service_Exception $exception) { $this->addFlashMessage('%1$s', 'Google API error', \Neos\Error\Messages\Message::SEVERITY_ERROR, ['message' => $exception->getMessage(), 1415797974]); $this->forward('errorMessage'); } catch (MissingConfigurationException $exception) { $this->addFlashMessage('%1$s', 'Missing configuration', \Neos\Error\Messages\Message::SEVERITY_ERROR, ['message' => $exception->getMessage(), 1415797974]); $this->forward('errorMessage'); } catch (AuthenticationRequiredException $exception) { $this->redirect('authenticate'); } }
Catch Google service exceptions and forward to the "apiError" action to show an error message. @return void
entailment
protected function getGroupedProfiles() { $this->analytics->requireAuthentication(); $groupedProfiles = []; $accounts = $this->analytics->management_accounts->listManagementAccounts(); foreach ($accounts as $account) { $groupedProfiles[$account->getId()]['label'] = $account->getName(); $groupedProfiles[$account->getId()]['items'] = []; } $webproperties = $this->analytics->management_webproperties->listManagementWebproperties('~all'); $webpropertiesById = []; foreach ($webproperties as $webproperty) { $webpropertiesById[$webproperty->getId()] = $webproperty; } $profiles = $this->analytics->management_profiles->listManagementProfiles('~all', '~all'); foreach ($profiles as $profile) { if (isset($webpropertiesById[$profile->getWebpropertyId()])) { $webproperty = $webpropertiesById[$profile->getWebpropertyId()]; $groupedProfiles[$profile->getAccountId()]['items'][$profile->getId()] = ['label' => $webproperty->getName() . ' > ' . $profile->getName(), 'value' => $profile->getId()]; } } return $groupedProfiles; }
Get profiles grouped by account and webproperty TODO Handle "(403) User does not have any Google Analytics account." @return array
entailment
protected function removeUriQueryArguments($redirectUri) { $uri = new \Neos\Flow\Http\Uri($redirectUri); $uri->setQuery(null); $redirectUri = (string)$uri; return $redirectUri; }
Remove query arguments from the given URI @param string $redirectUri @return string
entailment
public function bind($address, $port = 0) { return static::exceptionOnFalse( $this->resource, function ($resource) use ($address, $port) { return @socket_bind($resource, $address, $port); } ); }
Binds a name to a socket. <p>Binds the name given in address to the php socket resource currently in use. This has to be done before a connection is established using <code>connect()</code> or <code>listen()</code>.</p> @param string $address <p>If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. <code>127.0.0.1</code>).</p> <p>If the socket is of the AF_UNIX family, the address is the path of the Unix-domain socket (e.g. <code>/tmp/my.sock</code>).</p> @param int $port <p>(Optional) The port parameter is only used when binding an AF_INET socket, and designates the port on which to listen for connections.</p> @throws Exception\SocketException If the bind was unsuccessful. @return bool <p>Returns <code>true</code> if the bind was successful.</p>
entailment
public function connect($address, $port = 0) { return static::exceptionOnFalse( $this->resource, function ($resource) use ($address, $port) { return @socket_connect($resource, $address, $port); } ); }
Connect to a socket. <p>Initiate a connection to the address given using the current php socket resource, which must be a valid socket resource created with <code>create()</code>. @param string $address <p>The address parameter is either an IPv4 address in dotted-quad notation (e.g. <code>127.0.0.1</code>) if the socket is AF_INET, a valid IPv6 address (e.g. <code>::1</code>) if IPv6 support is enabled and the socket is AF_INET6, or the pathname of a Unix domain socket, if the socket family is AF_UNIX. </p> @param int $port <p>(Optional) The port parameter is only used and is mandatory when connecting to an AF_INET or an AF_INET6 socket, and designates the port on the remote host to which a connection should be made.</p> @throws Exception\SocketException If the connect was unsuccessful or if the socket is non-blocking. @see Socket::bind() @see Socket::listen() @see Socket::create() @return bool <p>Returns <code>true</code> if the connect was successful.
entailment
public static function create($domain, $type, $protocol) { $return = @socket_create($domain, $type, $protocol); if ($return === false) { throw new SocketException(); } $socket = new self($return); $socket->domain = $domain; $socket->type = $type; $socket->protocol = $protocol; return $socket; }
Create a socket. <p>Creates and returns a Socket. A typical network connection is made up of two sockets, one performing the role of the client, and another performing the role of the server.</p> @param int $domain <p>The domain parameter specifies the protocol family to be used by the socket.</p><p> <code>AF_INET</code> - IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. </p><p><code>AF_INET6</code> - IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family.</p><p><code>AF_UNIX</code> - Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).</p> @param int $type <p>The type parameter selects the type of communication to be used by the socket.</p><p> <code>SOCK_STREAM</code> - Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.</p><p> <code>SOCK_DGRAM</code> - Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.</p><p><code>SOCK_SEQPACKET</code> - Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.</p><p><code>SOCK_RAW</code> - Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping).</p><p><code>SOCK_RDM</code> - Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.</p> @param int $protocol <p>The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using <code>getprotobyname()</code>. If the desired protocol is TCP, or UDP the corresponding constants <code>SOL_TCP</code>, and <code>SOL_UDP</code> can also be used.<p><p>Some of the common protocol types</p><p> icmp - The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.</p><p>udp - The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.</p><p>tcp - The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.</p> @throws Exception\SocketException If there is an error creating the php socket. @return Socket Returns a Socket object based on the successful creation of the php socket.
entailment
public static function createListen($port, $backlog = 128) { $return = @socket_create_listen($port, $backlog); if ($return === false) { throw new SocketException(); } $socket = new self($return); $socket->domain = AF_INET; return $socket; }
Opens a socket on port to accept connections. <p>Creates a new socket resource of type <code>AF_INET</code> listening on all local interfaces on the given port waiting for new connections.</p> @param int $port The port on which to listen on all interfaces. @param int $backlog <p>The backlog parameter defines the maximum length the queue of pending connections may grow to. <code>SOMAXCONN</code> may be passed as the backlog parameter.</p> @throws Exception\SocketException If the socket is not successfully created. @see Socket::create() @see Socket::bind() @see Socket::listen() @return Socket Returns a Socket object based on the successful creation of the php socket.
entailment
public static function createPair($domain, $type, $protocol) { $array = []; $return = @socket_create_pair($domain, $type, $protocol, $array); if ($return === false) { throw new SocketException(); } $sockets = self::constructFromResources($array); foreach ($sockets as $socket) { $socket->domain = $domain; $socket->type = $type; $socket->protocol = $protocol; } return $sockets; }
Creates a pair of indistinguishable sockets and stores them in an array. <p>Creates two connected and indistinguishable sockets. This function is commonly used in IPC (InterProcess Communication).</p> @param int $domain <p>The domain parameter specifies the protocol family to be used by the socket. See <code>create()</code> for the full list.</p> @param int $type <p>The type parameter selects the type of communication to be used by the socket. See <code>create()</code> for the full list.</p> @param int $protocol <p>The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using <code>getprotobyname()</code>. If the desired protocol is TCP, or UDP the corresponding constants <code>SOL_TCP</code>, and <code>SOL_UDP</code> can also be used. See <code>create()</code> for the full list of supported protocols. @throws Exception\SocketException If the creation of the php sockets is not successful. @see Socket::create() @return Socket[] An array of Socket objects containing identical sockets.
entailment
public function getOption($level, $optname) { return static::exceptionOnFalse( $this->resource, function ($resource) use ($level, $optname) { return @socket_get_option($resource, $level, $optname); } ); }
Gets socket options. <p>Retrieves the value for the option specified by the optname parameter for the current socket.</p> @param int $level <p>The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of <code>SOL_SOCKET</code> would be used. Other levels, such as <code>TCP</code>, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the <code>getprotobyname()</code> function. @param int $optname <p><b>Available Socket Options</b></p><p><code>SO_DEBUG</code> - Reports whether debugging information is being recorded. Returns int.</p><p><code>SO_BROADCAST</code> - Reports whether transmission of broadcast messages is supported. Returns int.</p><p><code>SO_REUSERADDR</code> - Reports whether local addresses can be reused. Returns int.</p><p><code>SO_KEEPALIVE</code> - Reports whether connections are kept active with periodic transmission of messages. If the connected socket fails to respond to these messages, the connection is broken and processes writing to that socket are notified with a SIGPIPE signal. Returns int.</p><p> <code>SO_LINGER</code> - Reports whether the socket lingers on <code>close()</code> if data is present. By default, when the socket is closed, it attempts to send all unsent data. In the case of a connection-oriented socket, <code>close()</code> will wait for its peer to acknowledge the data. If <code>l_onoff</code> is non-zero and <code>l_linger</code> is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection-oriented socket. On the other hand, if <code>l_onoff</code> is non-zero and <code>l_linger</code> is non-zero, <code>close()</code> will block until all the data is sent or the time specified in <code>l_linger</code> elapses. If the socket is non-blocking, <code>close()</code> will fail and return an error. Returns an array with two keps: <code>l_onoff</code> and <code>l_linger</code>.</p><p> <code>SO_OOBINLINE</code> - Reports whether the socket leaves out-of-band data inline. Returns int.</p><p> <code>SO_SNDBUF</code> - Reports the size of the send buffer. Returns int.</p><p><code>SO_RCVBUF</code> - Reports the size of the receive buffer. Returns int.</p><p><code>SO_ERROR</code> - Reports information about error status and clears it. Returns int.</p><p><code>SO_TYPE</code> - Reports the socket type (e.g. <code>SOCK_STREAM</code>). Returns int.</p><p><code>SO_DONTROUTE</code> - Reports whether outgoing messages bypass the standard routing facilities. Returns int.</p><p><code>SO_RCVLOWAT</code> - Reports the minimum number of bytes to process for socket input operations. Returns int.</p><p><code>SO_RCVTIMEO</code> - Reports the timeout value for input operations. Returns an array with two keys: <code>sec</code> which is the seconds part on the timeout value and <code>usec</code> which is the microsecond part of the timeout value.</p><p> <code>SO_SNDTIMEO</code> - Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. Returns an array with two keys: <code>sec</code> which is the seconds part on the timeout value and <code>usec</code> which is the microsecond part of the timeout value.</p><p><code>SO_SNDLOWAT</code> - Reports the minimum number of bytes to process for socket output operations. Returns int.</p><p><code>TCP_NODELAY</code> - Reports whether the Nagle TCP algorithm is disabled. Returns int.</p><p><code>IP_MULTICAST_IF</code> - The outgoing interface for IPv4 multicast packets. Returns the index of the interface (int).</p><p><code>IPV6_MULTICAST_IF</code> - The outgoing interface for IPv6 multicast packets. Returns the same thing as <code>IP_MULTICAST_IF</code>.</p><p><code>IP_MULTICAST_LOOP</code> - The multicast loopback policy for IPv4 packets, which determines whether multicast packets sent by this socket also reach receivers in the same host that have joined the same multicast group on the outgoing interface used by this socket. This is the case by default. Returns int.</p><p><code>IPV6_MULTICAST_LOOP</code> - Analogous to <code>IP_MULTICAST_LOOP</code>, but for IPv6. Returns int.</p><p><code>IP_MULTICAST_TTL</code> - The time-to-live of outgoing IPv4 multicast packets. This should be a value between 0 (don't leave the interface) and 255. The default value is 1 (only the local network is reached). Returns int.</p><p> <code>IPV6_MULTICAST_HOPS</code> - Analogous to <code>IP_MULTICAST_TTL</code>, but for IPv6 packets. The value -1 is also accepted, meaning the route default should be used. Returns int.</p> @throws Exception\SocketException If there was an error retrieving the option. @return mixed See the descriptions based on the option being requested above.
entailment
public function getPeerName(&$address, &$port) { return static::exceptionOnFalse( $this->resource, function ($resource) use (&$address, &$port) { return @socket_getpeername($resource, $address, $port); } ); }
Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type. @param string $address <p>If the given socket is of type <code>AF_INET</code> or <code>AF_INET6</code>, <code>getPeerName()</code> will return the peers (remote) IP address in appropriate notation (e.g. <code>127.0.0.1</code> or <code>fe80::1</code>) in the address parameter and, if the optional port parameter is present, also the associated port.</p><p>If the given socket is of type <code>AF_UNIX</code>, <code>getPeerName()</code> will return the Unix filesystem path (e.g. <code>/var/run/daemon.sock</cod>) in the address parameter.</p> @param int $port (Optional) If given, this will hold the port associated to the address. @throws Exception\SocketException <p>If the retrieval of the peer name fails or if the socket type is not <code>AF_INET</code>, <code>AF_INET6</code>, or <code>AF_UNIX</code>.</p> @return bool <p>Returns <code>true</code> if the retrieval of the peer name was successful.</p>
entailment
public function getSockName(&$address, &$port) { if (!in_array($this->domain, [AF_UNIX, AF_INET, AF_INET6])) { return false; } return static::exceptionOnFalse( $this->resource, function ($resource) use (&$address, &$port) { return @socket_getsockname($resource, $address, $port); } ); }
Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type. <p><b>Note:</b> <code>getSockName()</code> should not be used with <code>AF_UNIX</code> sockets created with <code>connect()</code>. Only sockets created with <code>accept()</code> or a primary server socket following a call to <code>bind()</code> will return meaningful values.</p> @param string $address <p>If the given socket is of type <code>AF_INET</code> or <code>AF_INET6</code>, <code>getSockName()</code> will return the local IP address in appropriate notation (e.g. <code>127.0.0.1</code> or <code>fe80::1</code>) in the address parameter and, if the optional port parameter is present, also the associated port.</p><p>If the given socket is of type <code>AF_UNIX</code>, <code>getSockName()</code> will return the Unix filesystem path (e.g. <code>/var/run/daemon.sock</cod>) in the address parameter.</p> @param int $port If provided, this will hold the associated port. @throws Exception\SocketException <p>If the retrieval of the socket name fails or if the socket type is not <code>AF_INET</code>, <code>AF_INET6</code>, or <code>AF_UNIX</code>.</p> @return bool <p>Returns <code>true</code> if the retrieval of the socket name was successful.</p>
entailment
public function listen($backlog = 0) { return static::exceptionOnFalse( $this->resource, function ($resource) use ($backlog) { return @socket_listen($resource, $backlog); } ); }
Listens for a connection on a socket. <p>After the socket has been created using <code>create()</code> and bound to a name with <code>bind()</code>, it may be told to listen for incoming connections on socket.</p> @param int $backlog <p>A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.</p><p> <b>Note:</b> The maximum number passed to the backlog parameter highly depends on the underlying platform. On Linux, it is silently truncated to <code>SOMAXCONN</code>. On win32, if passed <code>SOMAXCONN</code>, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.</p> @throws Exception\SocketException If the listen fails. @return bool <p>Returns <code>true</code> on success.
entailment
public function read($length, $type = PHP_BINARY_READ) { return static::exceptionOnFalse( $this->resource, function ($resource) use ($length, $type) { return @socket_read($resource, $length, $type); } ); }
reads a maximum of length bytes from a socket. <p>Reads from the socket created by the <code>create()</code> or <code>accept()</code> functions.</p> @param int $length <p>The maximum number of bytes read is specified by the length parameter. Otherwise you can use <code>\r</code>, <code>\n</code>, or <code>\0</code> to end reading (depending on the type parameter, see below).</p> @param int $type <p>(Optional) type parameter is a named constant:<ul><li><code>PHP_BINARY_READ</code> (Default) - use the system <code>recv()</code> function. Safe for reading binary data.</li><li> <code>PHP_NORMAL_READ</code> - reading stops at <code>\n</code> or <code>\r</code>.</li></ul></p> @throws Exception\SocketException If there was an error reading or if the host closed the connection. @see Socket::create() @see Socket::accept() @return string Returns the data as a string. Returns a zero length string ("") when there is no more data to read.
entailment
public function receive(&$buffer, $length, $flags) { return static::exceptionOnFalse( $this->resource, function ($resource) use (&$buffer, $length, $flags) { return @socket_recv($resource, $buffer, $length, $flags); } ); }
Receives data from a connected socket. <p>Receives length bytes of data in buffer from the socket. <code>receive()</code> can be used to gather data from connected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.</p><p>buffer is passed by reference, so it must be specified as a variable in the argument list. Data read from socket by <code>receive()</code> will be returned in buffer.</p> @param string $buffer <p>The data received will be fetched to the variable specified with buffer. If an error occurs, if the connection is reset, or if no data is available, buffer will be set to <code>NULL</code>.</p> @param int $length Up to length bytes will be fetched from remote host. @param int $flags <p>The value of flags can be any combination of the following flags, joined with the binary OR (<code>|</code>) operator.<ul><li><code>MSG_OOB</code> - Process out-of-band data.</li><li><code>MSG_PEEK</code> - Receive data from the beginning of the receive queue without removing it from the queue.</li><li> <code>MSG_WAITALL</code> - Block until at least length are received. However, if a signal is caught or the remote host disconnects, the function may return less data.</li><li><code>MSG_DONTWAIT</code> - With this flag set, the function returns even if it would normally have blocked.</li></ul></p> @throws Exception\SocketException If there was an error receiving data. @return int Returns the number of bytes received.
entailment
public static function select( &$read, &$write, &$except, $timeoutSeconds, $timeoutMilliseconds = 0 ) { $readSockets = null; $writeSockets = null; $exceptSockets = null; if (!is_null($read)) { $readSockets = self::mapClassToRawSocket($read); } if (!is_null($write)) { $writeSockets = self::mapClassToRawSocket($write); } if (!is_null($except)) { $exceptSockets = self::mapClassToRawSocket($except); } $return = @socket_select( $readSockets, $writeSockets, $exceptSockets, $timeoutSeconds, $timeoutMilliseconds ); if ($return === false) { throw new SocketException(); } $read = []; $write = []; $except = []; if ($readSockets) { $read = static::mapRawSocketToClass($readSockets); } if ($writeSockets) { $write = static::mapRawSocketToClass($writeSockets); } if ($exceptSockets) { $except = static::mapRawSocketToClass($exceptSockets); } return $return; }
Runs the select() system call on the given arrays of sockets with a specified timeout. <p>accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.</p><p><b>WARNING:</b> On exit, the arrays are modified to indicate which socket resource actually changed status.</p><p>ou do not need to pass every array to <code>select()</code>. You can leave it out and use an empty array or <code>NULL</code> instead. Also do not forget that those arrays are passed by reference and will be modified after <code>select()</code> returns. @param Socket[] &$read <p>The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a <code>read()</code> will return a zero length string).</p> @param Socket[] &$write The sockets listed in the write array will be watched to see if a write will not block. @param Socket[] &$except he sockets listed in the except array will be watched for exceptions. @param int $timeoutSeconds The seconds portion of the timeout parameters (in conjunction with timeoutMilliseconds). The timeout is an upper bound on the amount of time elapsed before <code>select()</code> returns. timeoutSeconds may be zero, causing the <code>select()</code> to return immediately. This is useful for polling. If timeoutSeconds is <code>NULL</code> (no timeout), the <code>select()</code> can block indefinitely.</p> @param int $timeoutMilliseconds See the description for timeoutSeconds. @throws SocketException If there was an error. @return int Returns the number of socket resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens.
entailment
protected static function exceptionOnFalse($resource, callable $closure) { $result = $closure($resource); if ($result === false) { throw new SocketException($resource); } return $result; }
Performs the closure function. If it returns false, throws a SocketException using the provided resource. @param resource $resource Socket Resource @param callable $closure A function that takes 1 parameter (a socket resource) @throws SocketException
entailment
public function write($buffer, $length = null) { if (null === $length) { $length = strlen($buffer); } // make sure everything is written do { $return = @socket_write($this->resource, $buffer, $length); if (false !== $return && $return < $length) { $buffer = substr($buffer, $return); $length -= $return; } else { break; } } while (true); if ($return === false) { throw new SocketException($this->resource); } return $return; }
Write to a socket. <p>The function <code>write()</code> writes to the socket from the given buffer.</p> @param string $buffer The buffer to be written. @param int $length The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater than the buffer length, it is silently truncated to the length of the buffer. @throws Exception\SocketException If there was a failure. @return int Returns the number of bytes successfully written to the socket.
entailment
public function send($buffer, $flags = 0, $length = null) { if (null === $length) { $length = strlen($buffer); } // make sure everything is written do { $return = @socket_send($this->resource, $buffer, $length, $flags); if (false !== $return && $return < $length) { $buffer = substr($buffer, $return); $length -= $return; } else { break; } } while (true); if ($return === false) { throw new SocketException($this->resource); } return $return; }
Sends data to a connected socket. <p>Sends length bytes to the socket from buffer.</p> @param string $buffer A buffer containing the data that will be sent to the remote host. @param int $flags <p>The value of flags can be any combination of the following flags, joined with the binary OR (<code>|</code>) operator.<ul><li><code>MSG_OOB</code> - Send OOB (out-of-band) data.</li><li> <code>MSG_EOR</code> - Indicate a record mark. The sent data completes the record.</li><li><code>MSG_EOF</code> - Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.</li><li><code>MSG_DONTROUTE</code> - Bypass routing, use direct interface.</li></ul></p> @param int $length The number of bytes that will be sent to the remote host from buffer. @throws Exception\SocketException If there was a failure. @return int Returns the number of bytes sent.
entailment
protected function renderOptionTags($options) { $output = ''; if ($this->hasArgument('prependOptionLabel')) { $value = $this->hasArgument('prependOptionValue') ? $this->arguments['prependOptionValue'] : ''; if ($this->hasArgument('translate')) { $label = $this->getTranslatedLabel($value, $this->arguments['prependOptionLabel']); } else { $label = $this->arguments['prependOptionLabel']; } $output .= $this->renderOptionTag($value, $label) . chr(10); } $output .= $this->renderOptionTagsInternal($options); return $output; }
Render the option tags. @param array $options the options for the form. @return string rendered tags.
entailment
protected function loopOnce() { // Get all the Sockets we should be reading from $read = array_merge([$this->masterSocket], $this->clients); // Set up a block call to socket_select $write = null; $except = null; $ret = Socket::select($read, $write, $except, $this->timeout); if (!is_null($this->timeout) && $ret == 0) { if ($this->triggerHooks(self::HOOK_TIMEOUT, $this->masterSocket) === false) { // This only happens when a hook tells the server to shut itself down. return false; } } // If there is a new connection, add it if (in_array($this->masterSocket, $read)) { unset($read[array_search($this->masterSocket, $read)]); $socket = $this->masterSocket->accept(); $this->clients[] = $socket; if ($this->triggerHooks(self::HOOK_CONNECT, $socket) === false) { // This only happens when a hook tells the server to shut itself down. return false; } unset($socket); } // Check for input from each client foreach ($read as $client) { $input = $this->read($client); if ($input === '') { if ($this->disconnect($client) === false) { // This only happens when a hook tells the server to shut itself down. return false; } } else { if ($this->triggerHooks(self::HOOK_INPUT, $client, $input) === false) { // This only happens when a hook tells the server to shut itself down. return false; } } unset($input); } // Unset the variables we were holding on to unset($read); unset($write); unset($except); // Tells self::run to Continue the Loop return true; }
This is the main server loop. This code is responsible for adding connections and triggering hooks. @throws \Navarr\Socket\Exception\SocketException @return bool Whether or not to shutdown the server
entailment
public function disconnect(Socket $client, $message = '') { $clientIndex = array_search($client, $this->clients); $return = $this->triggerHooks( self::HOOK_DISCONNECT, $this->clients[$clientIndex], $message ); $this->clients[$clientIndex]->close(); unset($this->clients[$clientIndex]); unset($client); if ($return === false) { return false; } unset($return); return true; }
Disconnect the supplied Client Socket. @param Socket $client @param string $message Disconnection Message. Could be used to trigger a disconnect with a status code @return bool Whether or not to continue running the server (true: continue, false: shutdown)
entailment
protected function triggerHooks($command, Socket $client, $input = null) { if (isset($this->hooks[$command])) { foreach ($this->hooks[$command] as $callable) { $continue = call_user_func($callable, $this, $client, $input); if ($continue === self::RETURN_HALT_HOOK) { break; } if ($continue === self::RETURN_HALT_SERVER) { return false; } unset($continue); } } return true; }
Triggers the hooks for the supplied command. @param string $command Hook to listen for (e.g. HOOK_CONNECT, HOOK_INPUT, HOOK_DISCONNECT, HOOK_TIMEOUT) @param Socket $client @param string $input Message Sent along with the Trigger @return bool Whether or not to continue running the server (true: continue, false: shutdown)
entailment
public function addHook($command, $callable) { if (!isset($this->hooks[$command])) { $this->hooks[$command] = []; } else { $k = array_search($callable, $this->hooks[$command]); if ($k !== false) { return; } unset($k); } $this->hooks[$command][] = $callable; }
Attach a Listener to a Hook. @param string $command Hook to listen for @param callable $callable A callable with the signature (Server, Socket, string). Callable should return false if it wishes to stop the server, and true if it wishes to continue. @return void
entailment
public function removeHook($command, $callable) { if (isset($this->hooks[$command]) && array_search($callable, $this->hooks[$command]) !== false ) { $hook = array_search($callable, $this->hooks[$command]); unset($this->hooks[$command][$hook]); unset($hook); } }
Remove the provided Callable from the provided Hook. @param string $command Hook to remove callable from @param callable $callable The callable to be removed @return void
entailment
private function shutDownEverything() { foreach ($this->clients as $client) { $this->disconnect($client); } $this->masterSocket->close(); unset( $this->hooks, $this->address, $this->port, $this->timeout, $this->domain, $this->masterSocket, $this->maxClients, $this->maxRead, $this->clients, $this->readType ); }
Disconnect all the Clients and shut down the server. @return void
entailment
public function getData(NodeInterface $node = null, array $arguments) { if (!isset($arguments['stat'])) { throw new \InvalidArgumentException('Missing "stat" argument', 1416864525); } $startDateArgument = isset($arguments['startDate']) ? $arguments['startDate'] : '3 months ago'; $endDateArgument = isset($arguments['endDate']) ? $arguments['endDate'] : '1 day ago'; try { $startDate = new \DateTime($startDateArgument); } catch (\Exception $exception) { return ['error' => ['message' => 'Invalid date format for argument "startDate"', 'code' => 1417435564]]; } try { $endDate = new \DateTime($endDateArgument); } catch (\Exception $exception) { return ['error' => ['message' => 'Invalid date format for argument "endDate"', 'code' => 1417435581]]; } try { $stats = $this->reporting->getNodeStat($node, $this->controllerContext, $arguments['stat'], $startDate, $endDate); $data = [ 'data' => $stats ]; return $data; } catch (\Google_Service_Exception $exception) { $errors = $exception->getErrors(); return [ 'error' => [ 'message' => isset($errors[0]['message']) ? $errors[0]['message'] : 'Google API returned error', 'code' => isset($errors[0]['reason']) ? $errors[0]['reason'] : 1417606128 ] ]; } catch (Exception $exception) { return [ 'error' => [ 'message' => $exception->getMessage(), 'code' => $exception->getCode() ] ]; } }
Get analytics stats for the given node {@inheritdoc}
entailment
public function up() { if (! Schema::hasTable($this->table)) { Schema::create($this->table, function (Blueprint $table) { $table->increments('id'); $table->string('original_filename')->nullable(); $table->string('original_filepath')->nullable(); $table->string('original_filedir')->nullable(); $table->string('original_extension', 4)->nullable(); $table->string('original_mime', 10)->nullable(); $table->integer('original_filesize')->unsigned()->nullable(); $table->smallInteger('original_width')->unsigned()->nullable(); $table->smallInteger('original_height')->unsigned()->nullable(); $table->string('path')->nullable(); $table->string('dir')->nullable(); $table->string('filename')->nullable(); $table->string('basename')->nullable(); $table->text('exif')->nullable(); foreach (Config::get('imageupload.dimensions') as $key => $dimension) { $table->string($key.'_path')->nullable(); $table->string($key.'_dir')->nullable(); $table->string($key.'_filename')->nullable(); $table->string($key.'_filepath')->nullable(); $table->string($key.'_filedir')->nullable(); $table->integer($key.'_filesize')->unsigned()->nullable(); $table->smallInteger($key.'_width')->unsigned()->nullable(); $table->smallInteger($key.'_height')->unsigned()->nullable(); $table->boolean($key.'_is_squared')->unsigned()->nullable(); } $table->timestamps(); }); } }
Run the migrations.
entailment
public function upload(UploadedFile $uploadedFile, $newFilename = null, $path = null) { $this->prepareTargetUploadPath($path); $this->getUploadedOriginalFileProperties($uploadedFile); $this->setNewFilename($newFilename); $this->saveOriginalFile($uploadedFile); $this->createThumbnails($uploadedFile); return $this->returnOutput(); }
The main method, upload the file. @access public @param UploadedFile $uploadedFile @param string $newFilename (default: null) @param string $path (default: null) @return array
entailment
private function prepareConfigs() { $this->library = Config::get('imageupload.library', 'gd'); $this->quality = Config::get('imageupload.quality', 90); $this->uploadpath = Config::get('imageupload.path', public_path('uploads/images')); $this->newfilename = Config::get('imageupload.newfilename', 'original'); $this->dimensions = Config::get('imageupload.dimensions'); $this->suffix = Config::get('imageupload.suffix', true); $this->exif = Config::get('imageupload.exif', false); $this->output = Config::get('imageupload.output', 'array'); $this->intervention->configure(['driver' => $this->library]); return $this; }
Get and prepare configs. @access private
entailment
private function createDirectoryIfNotExists($absoluteTargetPath) { if (File::isDirectory($absoluteTargetPath) && File::isWritable($absoluteTargetPath)) { return true; } try { @File::makeDirectory($absoluteTargetPath, 0777, true); return true; } catch (Exception $e) { throw new ImageuploadException($e->getMessage()); } }
Check and create directory if not exists. @access private @param string $absoluteTargetPath @return bool
entailment
private function prepareTargetUploadPath($path = null) { $absoluteTargetPath = implode('/', array_filter([ rtrim($this->uploadpath, '/'), trim(dirname($path), '/'), ])); $this->results['path'] = $absoluteTargetPath; $this->results['dir'] = $this->getRelativePath($absoluteTargetPath); return $this->createDirectoryIfNotExists($absoluteTargetPath); }
Set target upload path. @access private @param string $path (default: null) @return bool
entailment
private function getThumbnailsTargetUploadFilepath($key) { $absoluteThumbnailTargetPath = implode('/', array_filter([ rtrim($this->results['path'], '/'), (! $this->suffix ? trim($key) : ''), ])); $this->createDirectoryIfNotExists($absoluteThumbnailTargetPath); $resizedBasename = implode('_', [ $this->results['basename'], $key, ]); if (! $this->suffix) { $resizedBasename = $this->results['basename']; } $resizedBasename .= '.'.$this->results['original_extension']; return implode('/', [$absoluteThumbnailTargetPath, $resizedBasename]); }
Set thumbnail target upload file path. @access private @param string $key @return string
entailment
private function setNewFilename($newfilename = null) { $extension = $this->results['original_extension']; $originalFilename = $this->results['original_filename']; $timestamp = Carbon::now()->getTimestamp(); switch ($this->newfilename) { case 'hash': $newfilename = md5($originalFilename.$timestamp); break; case 'random': $newfilename = Str::random(16); break; case 'timestamp': $newfilename = $timestamp; break; case 'custom': $newfilename = (! empty($newfilename) ? $newfilename : $originalFilename); break; default: $newfilename = pathinfo($originalFilename, PATHINFO_FILENAME); } $this->results['basename'] = (string) $newfilename; $this->results['filename'] = $newfilename.'.'.$extension; return $this; }
Set new file name from config. @access private @param string $newfilename (default: null)
entailment
private function saveOriginalFile(UploadedFile $uploadedFile) { try { $targetFilepath = implode('/', [ $this->results['path'], $this->results['filename'], ]); $image = $this->intervention->make($uploadedFile); if ($this->exif && ! empty($image->exif())) { $this->results['exif'] = $image->exif(); } $image->save($targetFilepath, $this->quality); // Save to s3 $s3_url = $this->saveToS3($image, $targetFilepath); $this->results['original_width'] = (int) $image->width(); $this->results['original_height'] = (int) $image->height(); $this->results['original_filepath'] = $targetFilepath; $this->results['original_filedir'] = $this->getRelativePath($targetFilepath); $this->results['s3_url'] = $s3_url; } catch (Exception $e) { throw new ImageuploadException($e->getMessage()); } return $this; }
Upload and save original file. @access private @param UploadedFile $uploadedFile
entailment
private function getUploadedOriginalFileProperties(UploadedFile $uploadedFile) { $this->results['original_filename'] = $uploadedFile->getClientOriginalName(); $this->results['original_filepath'] = $this->getRelativePath($uploadedFile->getRealPath()); $this->results['original_filedir'] = $uploadedFile->getRealPath(); $this->results['original_extension'] = $uploadedFile->getClientOriginalExtension(); $this->results['original_filesize'] = (int) $uploadedFile->getSize(); $this->results['original_mime'] = $uploadedFile->getMimeType(); return $this; }
Prepare original file properties. @access private @param UploadedFile $uploadedFile
entailment
private function resizeCropImage(UploadedFile $uploadedFile, $targetFilepath, $width, $height = null, $squared = false) { try { $height = (! empty($height) ? $height : $width); $squared = (isset($squared) ? $squared : false); $image = $this->intervention->make($uploadedFile); if ($squared) { $width = ($height < $width ? $height : $width); $height = $width; $image->fit($width, $height, function ($image) { $image->upsize(); }); } else { $image->resize($width, $height, function ($image) { $image->aspectRatio(); }); } $image->save($targetFilepath, $this->quality); // Save to s3 $s3_url = $this->saveToS3($image, $targetFilepath); return [ 'path' => dirname($targetFilepath), 'dir' => $this->getRelativePath($targetFilepath), 'filename' => pathinfo($targetFilepath, PATHINFO_BASENAME), 'filepath' => $targetFilepath, 'filedir' => $this->getRelativePath($targetFilepath), 's3_url' => $s3_url, 'width' => (int) $image->width(), 'height' => (int) $image->height(), 'filesize' => (int) $image->filesize(), 'is_squared' => (bool) $squared, ]; } catch (Exception $e) { throw new ImageuploadException($e->getMessage()); } }
Resize file to create thumbnail. @access private @param UploadedFile $uploadedFile @param string $targetFilepath @param int $width @param int $height (default: null) @param bool $squared (default: false) @return array
entailment
private function createThumbnails(UploadedFile $uploadedFile) { if (empty($this->dimensions)) { return $this; } foreach ($this->dimensions as $key => $dimension) { if (empty($dimension) || ! is_array($dimension)) { continue; } list($width, $height, $squared) = $dimension; $targetFilepath = $this->getThumbnailsTargetUploadFilepath($key); $image = $this->resizeCropImage($uploadedFile, $targetFilepath, $width, $height, $squared); if (! $image) { continue; } $this->results['dimensions'][$key] = $image; } return $this; }
Create thumbnails. @access private @param UploadedFile $uploadedFile
entailment
private function returnOutput() { $collection = new Collection($this->results); switch ($this->output) { case 'db': return $this->saveToDatabase($collection); break; case 'collection': return $collection; break; case 'json': return $collection->toJson(); break; case 'array': default: return $collection->toArray(); } }
Return output. @access private @return mixed
entailment
private function saveToDatabase(Collection $collection) { $model = new ImageuploadModel(); $fillable = $model->getFillable(); $input = $collection->only($fillable)->toArray(); $dimensions = $collection['dimensions']; foreach ($dimensions as $key => $dimension) { foreach ($dimension as $k => $v) { $input[$key.'_'.$k] = $v; } } return $model->firstOrCreate($input); }
Save output to database and return Model collection. @access private @param Collection $collection @return ImageuploadModel
entailment
public function getDimensionKeys() { $dimensions = Config::get('imageupload.dimensions'); $fillable = []; if (empty($dimensions) || ! is_array($dimensions)) { return $fillable; } foreach ($dimensions as $name => $dimension) { foreach ($this->thumbnailKeys as $key => $cast) { array_push($fillable, $name.'_'.$key); } } return $fillable; }
Get dimension fillable field. @return array
entailment
public function getCasts() { $this->casts = parent::getCasts(); $dimensions = Config::get('imageupload.dimensions'); if (empty($dimensions) || ! is_array($dimensions)) { return $this->casts; } foreach ($dimensions as $name => $dimension) { foreach ($this->thumbnailKeys as $key => $cast) { $this->casts[$name.'_'.$key] = $cast; } } return $this->casts; }
Get the casts array. @return array
entailment
public function register() { $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'imageupload'); $this->app->singleton('imageupload', function ($app) { return new Imageupload(new ImageManager()); }); }
Register the service provider.
entailment
public function getCurrentLanguage() { if ($this->getStorageMethod() == 'session') { return Session::get($this->getLanguageKey(), Config::get('app.locale')); } return Request::cookie($this->getLanguageKey()) ?: Config::get('app.locale'); }
Returns the current language set in the session/cookie @return string
entailment
public function setLanguage($language) { if ($this->getStorageMethod() == 'cookie') { return cookie()->forever($this->getLanguageKey(), $language); } if ( interface_exists( \Illuminate\Contracts\Session\Session::class ) && method_exists(\Illuminate\Contracts\Session\Session::class, 'put') ) { Session::put($this->getLanguageKey(), $language); } else { Session::set($this->getLanguageKey(), $language); } $this->registerLanguage(); return cookie('dummy-cookie', FALSE, 1); //just for cleaner code in the controller }
Sets the language flag and returns the cookie to be created on the redirect @param $language @return mixed | null
entailment
public function getLocalBack($language) { $backUrl = redirect()->back()->getTargetUrl(); $current = $this->getCurrentLanguage(); $start = strpos($backUrl, $current); $count = strlen($current); if ($backUrl[$start - 1] == '/' && (!isset($backUrl[$start + $count])) || $backUrl[$start + $count] == '/') { $backUrl = substr_replace($backUrl, $language, $start, $count); } return $backUrl; }
Gets the back route with the correct language @param string $language Language to be replaced @return string string for back url
entailment
public function setLanguage($language) { if (Switcher::getRedirect() == 'route') { return redirect(Switcher::getRedirectRoute())->withCookie(Switcher::setLanguage($language)); } if (Switcher::getRedirect() == 'locale') { return redirect(Switcher::getLocalBack($language))->withCookie(Switcher::setLanguage($language)); } return back()->withCookie(Switcher::setLanguage($language)); }
Set the language and redirect @param $language @return mixed
entailment
public function load($id = null) { if(is_null($id) && Mage::getSingleton('customer/session')->isLoggedIn()) { $this->customer = Mage::getSingleton('customer/session')->getCustomer(); } else if(is_int($id)) { $this->customer = Mage::getModel('customer/customer')->load($id); // TODO: Implement } if(!$this->customer->getId()) { return $this; } if(!($socialconnectLid = $this->customer->getInchooSocialconnectTid()) || !($socialconnectTtoken = $this->customer->getInchooSocialconnectTtoken())) { return $this; } $this->setAccessToken($socialconnectTtoken); $this->_load(); return $this; }
Load customer user info @param null|int $id Customer Id @return Inchoo_SocialConnect_Model_Twitter_Userinfo
entailment
public function load($id = null) { if(is_null($id) && Mage::getSingleton('customer/session')->isLoggedIn()) { $this->customer = Mage::getSingleton('customer/session')->getCustomer(); } else if(is_int($id)){ $this->customer = Mage::getModel('customer/customer')->load($id); // TODO: Implement } if(!$this->customer->getId()) { return $this; } if(!($socialconnectFid = $this->customer->getInchooSocialconnectFid()) || !($socialconnectFtoken = $this->customer->getInchooSocialconnectFtoken())) { return $this; } $this->setAccessToken(unserialize($socialconnectFtoken)); $this->_load(); return $this; }
Load customer user info @param null|int $id Customer Id @return Inchoo_SocialConnect_Model_Facebook_Userinfo
entailment
public function installCustomerAttributes() { foreach ($this->_customerAttributes as $code => $attr) { $this->addAttribute('customer', $code, $attr); } return $this; }
Add our custom attributes @return Mage_Eav_Model_Entity_Setup
entailment
public function removeCustomerAttributes() { foreach ($this->_customerAttributes as $code => $attr) { $this->removeAttribute('customer', $code); } return $this; }
Remove custom attributes @return Mage_Eav_Model_Entity_Setup
entailment
protected function _loginPostRedirect() { $session = $this->_getCustomerSession(); if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl()) { // Set default URL to redirect customer to $session->setBeforeAuthUrl($session->getSocialConnectRedirect()); // Redirect customer to the last page visited after logging in if ($session->isLoggedIn()) { if (!Mage::getStoreConfigFlag( Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD )) { $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME); if ($referer) { // Rebuild referer URL to handle the case when SID was changed $referer = $this->_getModel('core/url') ->getRebuiltUrl( $this->_getHelper('core')->urlDecode($referer)); if ($this->_isUrlInternal($referer)) { $session->setBeforeAuthUrl($referer); } } } else if ($session->getAfterAuthUrl()) { $session->setBeforeAuthUrl($session->getAfterAuthUrl(true)); } } else { $session->setBeforeAuthUrl( $this->_getHelper('customer')->getLoginUrl()); } } else if ($session->getBeforeAuthUrl() == $this->_getHelper('customer')->getLogoutUrl()) { $session->setBeforeAuthUrl( $this->_getHelper('customer')->getDashboardUrl()); } else { if (!$session->getAfterAuthUrl()) { $session->setAfterAuthUrl($session->getBeforeAuthUrl()); } if ($session->isLoggedIn()) { $session->setBeforeAuthUrl($session->getAfterAuthUrl(true)); } } $this->_redirectUrl($session->getBeforeAuthUrl(true)); }
Define target URL and redirect customer after logging in
entailment
public function load($id = null) { if(is_null($id) && Mage::getSingleton('customer/session')->isLoggedIn()) { $this->customer = Mage::getSingleton('customer/session')->getCustomer(); } else if(is_int($id)){ $this->customer = Mage::getModel('customer/customer')->load($id); // TODO: Implement } if(!$this->customer->getId()) { return $this; } if(!($socialconnectGid = $this->customer->getInchooSocialconnectGid()) || !($socialconnectGtoken = $this->customer->getInchooSocialconnectGtoken())) { return $this; } $this->setAccessToken($socialconnectGtoken); $this->_load(); return $this; }
Load customer user info @param null|int $id Customer Id @return Inchoo_SocialConnect_Model_Google_Userinfo
entailment
public function load($id = null) { if(is_null($id) && Mage::getSingleton('customer/session')->isLoggedIn()) { $this->customer = Mage::getSingleton('customer/session')->getCustomer(); } else if(is_int($id)){ $this->customer = Mage::getModel('customer/customer')->load($id); // TODO: Implement } if(!$this->customer->getId()) { return $this; } if(!($socialconnectLid = $this->customer->getInchooSocialconnectLid()) || !($socialconnectLtoken = $this->customer->getInchooSocialconnectLtoken())) { return $this; } $this->setAccessToken($socialconnectLtoken); $this->_load(); return $this; }
Load customer user info @param null|int $id Customer Id @return Inchoo_SocialConnect_Model_Linkedin_Userinfo
entailment