TODO: убрать преобразование, типа UNIXTIME(`Date`) as create_time … ORDER BY create_time там, где можно без него обойтись
439121
function order($order)
	{
		$parsed_order = array();
		foreach(explode(',', $order) as $property_name)
		{
			$property_name = trim($property_name);
			if(preg_match('/^-(.+)/', $property_name, $m))
			{
				$property_name = $m[1];
				$dir = ' DESC';
			}
			else
				$dir = '';

			$property_name = $this->first_parse($property_name);
			$property_name = $this->stack_parse($property_name);
			$property_name = $this->class_parse($property_name);

			$parsed_order[] = "$property_name$dir";
		}

		$this->_where['*raw_order'] = "ORDER BY ".join(', ', $parsed_order);

		return $this;
	}
736388
public function toDateTime()
    {
        $datetime = new \DateTime();
        $datetime->setTimestamp($this->sec);

        $microSeconds = $this->truncateMicroSeconds($this->usec);
        if ($microSeconds > 0) {
            $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad($microSeconds, 6, '0', STR_PAD_LEFT));
        }

        $datetime->setTimezone(new \DateTimeZone("UTC"));

        return $datetime;
    }
1129122
public function init()
	{
		if ($this->conf['timezone'])
		{
			date_default_timezone_set($this->conf['timezone']);
		}
		# Определение путей
		$this->init_resolve();
		# Инициализация сессии
		$this->init_session();
		# Изменяем путь поиска подключаемых файлов
		set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path());
		# Читаем настройки
		$this->initSettings();
		# Первичный разбор запроса
		$this->init_request();
		# Настройка локали
		$this->initLocale();
		# Подключение базовых классов
		$this->initClasses();
		# Инициализация расширений
		$this->init_extensions();
		# Подключение к источнику данных
		$this->initDataSource();
        $this->plugins = Eresus_Plugin_Registry::getInstance();
        $this->plugins->init();
		# Проверка сессии
		$this->check_session();
		# Проверка логина/логаута
		$this->check_loginout();
		# Попытка cookie-логина
		$this->check_cookies();
		# Обновление данных о пользователе
		$this->reset_login();
		$this->sections = new Sections;
		$GLOBALS['KERNEL']['loaded'] = true; # Флаг загрузки ядра
	}
117529
public function start()
    {
        $file_info = (new FileToken($this->dic))->getFileInfo($this->request->get('token'));

        if (isset($file_info['errors'])) {
            $this->response->setData($file_info);
            $this->response->send();
        }

        $filepath = SettingsFile::FILE_FOLDER . $file_info['data']['path'];

        if (is_readable($filepath) && is_file($filepath)) {
            $response = new BinaryFileResponse($filepath);
            $response->headers->set('Content-type', mime_content_type($filepath));
            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file_info['data']['name']);
            $response->send();
        } else {
            $this->response->setData(Response::error404('Файл не найден'));
            $this->response->send();
        }
    }
515386
public function getCreationDate()
    {
        //DateTimeOriginal to najlepsze źródło
        if (isset($this->_exif['DateTimeOriginal']) && substr($this->_exif['DateTimeOriginal'], 0, 4) != '0000') {
            return date('Y-m-d H:i:s', strtotime($this->_exif['DateTimeOriginal']));
        }
        //brak DateTimeOriginal, próba z DateTime
        if (isset($this->_exif['DateTime']) && substr($this->_exif['DateTime'], 0, 4) != '0000') {
            return date('Y-m-d H:i:s', strtotime($this->_exif['DateTime']));
        }
        //w pozostałych przypadkach - data utworzenia pliku
        if (!isset($this->_exif['FileDateTime']) && substr($this->_exif['DateTime'], 0, 4) != '0000') {
            return date('Y-m-d H:i:s', strtotime($this->_exif['FileDateTime']));
        }
    }
454818
public function getDateCreated() : DateTime
     {
        $rtn = $this->data['date_created'];

        if (!empty($rtn)) {
            $rtn = new DateTime($rtn);
        }

        return $rtn;
     }
377956
def created(self):
        
        timestamp, current = self._created
        if timestamp.endswith('ago'):
            quantity, kind, ago = timestamp.split()
            quantity = int(quantity)
            if 'sec' in kind:
                current -= quantity
            elif 'min' in kind:
                current -= quantity * 60
            elif 'hour' in kind:
                current -= quantity * 60 * 60
            return datetime.datetime.fromtimestamp(current)
        current = datetime.datetime.fromtimestamp(current)
        timestamp = timestamp.replace(
            'Y-day', str(current.date() - datetime.timedelta(days=1)))
        timestamp = timestamp.replace('Today', current.date().isoformat())
        try:
            return dateutil.parser.parse(timestamp)
        except:
            return current
552593
public function run() {
		$this->resetParser();
		if(function_exists('pcntl_signal')) {
			if(! $this->signal_handlers_installed) {
				pcntl_signal(SIGTERM, array($this, 'handleSignal'), false);
				pcntl_signal(SIGINT, array($this, 'handleSignal'), false);
				pcntl_signal(SIGHUP, array($this, 'handleSignal'), false);
				pcntl_signal(SIGUSR1, array($this, 'handleSignal'), false);
			}
			pcntl_signal_dispatch();
			// Следующее нужно, если обработчик сигнала надумал нас отключить
			if($this->disconnect) {
				return $this->result = 0; // Если мы сами отключились, то это можно считать успехом по определению
			}
		}
		
		if(!$this->socket = @ socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) {
			$this->result = socket_last_error($this->socket);
			$errstr = socket_strerror($this->result);
			@ socket_clear_error($this->socket);
			$this->log("error {$this->result}: $errstr", PHP_COMPONENT_MESSAGE_ERROR, true);
			return $this->result;
		}
		
		if(! @ socket_connect($this->socket, $this->hostname, $this->port)) {
			$this->result = socket_last_error($this->socket);
			$errstr = socket_strerror($this->result);
			@ socket_clear_error($this->socket);
			$this->log("error {$this->result}: $errstr", PHP_COMPONENT_MESSAGE_ERROR, true);
			@ socket_close($this->socket);
			return $this->result;
		}
		
		$this->send('<stream:stream xmlns="jabber:component:accept" xmlns:stream="http://etherx.jabber.org/streams" to="' . $this->component_name . '">');
		
		socket_set_nonblock($this->socket);
		
		while(true) {
			$read = array($this->socket);
			$write = $except = NULL;
			
			if(($socket = @ socket_select($read, $write, $except, 1)) === false) {
				if(function_exists('pcntl_signal_dispatch')) {
					pcntl_signal_dispatch();
				}
				@ socket_close($this->socket);
				return $this->result;
			}
			
			if($socket === 0) {
				if(function_exists('pcntl_signal_dispatch')) {
					pcntl_signal_dispatch();
				}
				$this->checkTimers();
				continue;
			}
			
			if(($buf = @ socket_read($this->socket, 1024, PHP_BINARY_READ)) === false) {
				if(function_exists('pcntl_signal_dispatch')) {
					pcntl_signal_dispatch();
				}
				if(($this->result = socket_last_error($this->socket)) === 4) {
					@ socket_clear_error($this->socket);
					$this->result = 0;
					break; // корректное отключение
				}
				if(($this->result = socket_last_error($this->socket)) === 11) {
					continue; // системный вызов прерван по сигналу
				}
				$errstr = socket_strerror($this->result);
				$this->log("error {$this->result}: $errstr", PHP_COMPONENT_MESSAGE_ERROR, true);
				@ socket_clear_error($this->socket);
				@ socket_close($this->socket);
				return $this->result;
			}
			if($buf == '') {
				// Не совсем понятно, почему при закрытии соединения сервером не генерируется никакая ошибка
				// Возможно, это некорректный способ определить, отключили ли нас, надо ещё уточнить
				$this->log('the remote server has dropped the connection', PHP_COMPONENT_MESSAGE_ERROR, true);
				return 104; // код ошибки connection reset by peer
			}
			$this->feed($buf);
			// Следующее сработает, если мы отключились в обработчике некоторой станзы
			if($this->disconnect) {
				$this->result = 0;
				break;
			}
		}
		
		@ socket_close($this->socket);
		return $this->result;
	}
171696
function file($new = null, $root = false)
    {
        // Установка нового файла
        if (isset($new)){
            if (empty($new)){
                $this->change('file', '');
            }else{
                if (is_string($new)){
                    $new = [
                        'tmp_name'	=> $new,
                        'name' => basename($new),
                        'size' => @filesize($new),
                        'error'	=> is_file($new)? 0 : true
                    ];
                }
                if (empty($new['name']) && $this->is_file()){
                    $new['name'] = $this->name().'.'.File::fileExtention($this->file());
                }
                $this->change('file', $new);
            }
            $this->change('is_default_file', false);
            $this->_def_file = null;
        }
        // Возврат пути к текущему файлу, если есть
        if ($this->is_file()){
            if (($proto = $this->is_default_file(null, true)) && $proto->is_exists()){
                return $proto->file(null, $root);
            }else{
                if (is_array($this->_attributes['file'])){
                    return $this->_attributes['file'];
                }
                return $this->dir($root).$this->_attributes['file'];
            }
        }
        return null;
    }
49911
public function save()
    {
        $this->_slug = trim(trim($this->_slug), '/');
        if (is_null($this->_slugModel) || $this->_slugModel->slug !== $this->_slug) {
            //Если уже есть запись с таким slug то обновим её присвоев её максимальный id + 1
            $model = SeoSlug::find()
                ->where([
                    'AND',
                    ['=', 'model', $this->owner->className()],
                    ['=', 'model_id', $this->owner->getPrimaryKey()],
                    ['=', 'slug', $this->_slug],
                ])
                ->one();
            if ($model) {
                $maxId = SeoSlug::find()
                    ->max('id');
                $oldId = $model->id;
                $model->id = ++$maxId;
                $model->save();
                SeoSlug::updateAllCounters(['id' => -1], [
                    'AND',
                    ['>', SeoSlug::tableName() . '.id', $oldId],
                ]);
            } else {
                $model = new SeoSlug();
                $model->model = $this->owner->className();
                $model->model_id = $this->owner->getPrimaryKey();
            }
            $model->slug = $this->_slug;
            $model->save();
            if (is_callable($this->afterSave)) {
                call_user_func($this->afterSave, $this);
            }
        }
    }
903819
function date() {
  const date = new Date()
  return (
    pad(date.getUTCMonth() + 1) +
    pad(date.getUTCDate()) +
    pad(date.getUTCHours()) +
    pad(date.getUTCMinutes()) +
    pad(date.getUTCSeconds())
  )
}
283529
private function init_request()
	{
		global $request;

		# Значения по умолчанию
		$request = array(
			'method' => $_SERVER['REQUEST_METHOD'],
			'scheme' => isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http',
			'host' => strtolower($_SERVER['HTTP_HOST']),
			'port' => '',
			'user' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
			'pass' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '',
			'path' => '',
			'query' => '',
			'fragment' => '',
			'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
		);

		$request['url'] = $request['scheme'] . '://' . $request['host'] . $_SERVER['REQUEST_URI'];

		$request = array_merge($request, parse_url($request['url']));
		$request['file'] = substr($request['path'], strrpos($request['path'], '/')+1);
		if ($request['file'])
		{
			$request['path'] = substr($request['path'], 0, -strlen($request['file']));
		}

		# Создаем заготовку URL для GET-запросов с параметрами
		$request['link'] = $request['url'];
		if (substr($request['link'], -1) == '/')
		{
			$request['link'] .= '?';
		}
		elseif (strpos($request['link'], '?') === false)
		{
			$request['link'] .= '?';
		}
		else
		{
			$request['link'] .= '&';
		}

		if (is_null($this->path))
		{
			$s = $this->froot;
			$s = substr($s,
				strlen(realpath($_SERVER['DOCUMENT_ROOT'])) - (Eresus_Kernel::isWindows() ? 2 : 0));
			if (!strlen($s) || substr($s, -1) != '/')
			{
				$s .= '/';
			}
			$this->path = (substr($s, 0, 1) != '/' ? '/' : '').$s;
		}

		/*
		 * Установка свойств объекта $Eresus
		 * Должна выполняться ДО вызова __clearargs
		 */
		$root = $request['scheme'] . '://' . $request['host'] .
			($request['port'] ? ':'.$request['port'] : '');
		$this->root = $root.$this->path;
		$this->data = $this->root.'data/';
		$this->style = $this->root.'style/';


		# Сбор аргументов вызова
		$request['arg'] = __clearargs(array_merge($_GET, $_POST));
		# Разбивка параметров вызова скрипта
		$s = substr($request['path'], strlen($this->path));
		$request['params'] = $s ? explode('/', substr($s, 0, -1)) : array();

		$request['path'] = $root.$request['path'];

		# Обратная совместимость
		# <= 2.9
		$this->request = &$request;
        /**
         * @deprecated с 3.01
         */
		define('httpPath', $this->path);
        /**
         * @deprecated с 3.01
         */
		define('httpHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
        define('httpRoot', $this->root);
        /**
         * @deprecated с 3.01
         */
		define('styleRoot', $this->style);
        /**
         * @deprecated с 3.01
         */
		define('dataRoot', $this->data);
        /**
         * @deprecated с 3.01
         */
		define('cookieHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
		define('cookiePath', $this->path);
	}
670195
def set_timestamps
        if self.errors.empty?
          self.created_at = DateTime.now.utc if self.respond_to?(:created_at=) && self.created_at.nil?
          self.updated_at = DateTime.now.utc if self.respond_to?(:updated_at=)
        end
      end
392972
public function getCreatedDate()
    {
        $rtn    = $this->data['created_date'];

        if (!empty($rtn)) {
            $rtn    = new \DateTime($rtn);
        }
        
        return $rtn;
    }
532043
function get_lock($time = -1) {
            $tmp_time = microtime(true);
            if ($this->_lock_acquired) {
                return true;
            }

            self::create_folders_in_path(dirname($this->filename));
            if (!is_dir(dirname($this->filename))) {
                throw new MutexException('Folder "'.dirname($this->filename).'" is not a folder', 4);
            } elseif (!is_writable(dirname($this->filename))) {
                throw new MutexException('Folder "'.dirname($this->filename).'" is not writable', 2);
            } elseif (file_exists($this->filename) and !is_writable($this->filename)) {
                throw new MutexException('File "'.$this->filename.'" is not writable', 3);
            }

            // Открываем файл
            $this->_file_handler = fopen($this->filename, file_exists($this->filename) ? 'ab' : 'wb');
            while (($this->_file_handler === false) and (
                    ($tmp_time + $time >= microtime(true)) or ($time == -1)
                )) {
                usleep(10000);
                $this->_file_handler = fopen($this->filename, 'ab');
            }
            if ($this->_file_handler === false) {
                return false;
            }

            // Блочим файл
            if ($time >= 0) {
                $result = flock($this->_file_handler, LOCK_EX | LOCK_NB);
                while (!$result and ($tmp_time + $time >= microtime(true))) {
                    // U MAD?
                    usleep(10000);
                    $result = flock($this->_file_handler, LOCK_EX | LOCK_NB);
                }
            } else {
                $result = flock($this->_file_handler, LOCK_EX);
            }

            if ($result) {
                $this->_lock_acquired_time = microtime(true);
                // @todo Не работает под Windows
                fwrite($this->_file_handler, posix_getpid()."\n".microtime(true)."\n".posix_getuid()."\n\n");
                fflush($this->_file_handler);
                $this->_lock_acquired = true;
            } else {
                fclose($this->_file_handler);
                $this->_file_handler = false;
            }

            return $result;
        }
186654
private function actionCreate()
    {
        $forms = $this->plugin->getForms();
        $name = arg('name');
        if ($forms->get($name) === false)
        {
            $forms->add($name, arg('code'), arg('title'));
            HTTP::redirect(arg('submitURL'));
        }
        ErrorMessage('Форма с таким именем уже есть! Укажите другое имя.');
        return $this->actionAddDialog();
    }
67204
def set_created_at
      self.created_at ||= DateTime.now.in_time_zone(Time.zone) if Dynamoid::Config.timestamps
    end