Exemplo n.º 1
0
 /**
  * Añade el producto a la base de datos con el nombre, medida, descripcion, rutaimagen, categoria y familia.
  *
  * @param $nombreprod string.
  * @param $precioprod string.
  * @param $medidas string.
  * @param $descripcionprod string.
  * @param $rutaimagen string.
  * @param $idcategoria int.
  * @param $idfamilia int.
  * @return boolean.
  */
 public function agregarProducto($nombreprod, $precioprod, $medidas, $descripcionprod, $rutaimagen, $idcategoria, $idfamilia)
 {
     $Markdown = new Markdown();
     $my_html = $Markdown->transform($descripcionprod);
     $query = "INSERT INTO producto(nombreprod, precioprod, medidas, descripcionprod, rutaimagen, categoria_idcategoria, categoria_familia_idfamilia)" . "VALUES('{$nombreprod}', '{$precioprod}', '{$medidas}','{$my_html}', '{$rutaimagen}', '{$idcategoria}', '{$idfamilia}');";
     $this->logger->getLogger($query);
     $result = $this->connection->query($query);
     return $result;
 }
Exemplo n.º 2
0
function markdown($string)
{
    #
    # Initialize the parser and return the result of its transform method.
    #
    # Setup static parser variable.
    static $parser;
    if (!isset($parser)) {
        $parser = new Markdown();
    }
    # Transform text using parser.
    return $parser->transform($string);
}
Exemplo n.º 3
0
 public function parse($filenames)
 {
     if (!is_array($filenames)) {
         $filenames = array($filenames);
     }
     $template = false;
     foreach ($filenames as $filename) {
         $template = self::findTemplate($filename);
         if ($template !== false) {
             break;
         }
     }
     if ($template === false) {
         ErrorHandler::error(404, null, implode(", ", $filenames));
     }
     return Markdown::transform(file_get_contents($template));
 }
function parse($str, $markdown = true)
{
    // process tags
    $pattern = '/[\\{\\{]{1}([a-z]+)[\\}\\}]{1}/i';
    if (preg_match_all($pattern, $str, $matches)) {
        list($search, $replace) = $matches;
        foreach ($replace as $index => $key) {
            $replace[$index] = Config::meta($key);
        }
        $str = str_replace($search, $replace, $str);
    }
    $str = html_entity_decode($str, ENT_NOQUOTES, System\Config::app('encoding'));
    //  Parse Markdown as well?
    if ($markdown === true) {
        $md = new Markdown();
        $str = $md->transform($str);
    }
    return $str;
}
Exemplo n.º 5
0
 protected function get_item($r)
 {
     Input::ensureRequest($r, array("id"));
     $id = $r["id"];
     $item = $this->model->getBy(PostsModel::SLUG, $id);
     Logger::debug("Fetch {$id}");
     $values = array();
     $values["id"] = $item->get("id");
     $values["slug"] = $item->get("slug");
     $values["created"] = $item->get("created");
     $values["name"] = $item->get("name");
     $values["content"] = Markdown::transform($item->get("content"));
     $cats = new CategoriesModel();
     $cat = $cats->getById($item->get("category_id"));
     $values["category"] = $cat->get("name");
     $values["category_slug"] = $cat->get("slug");
     $users = new UsersModel();
     $user = $users->getById($item->get("user_id"));
     $values["user"] = $user->get("username");
     Output::success(array(self::ID => $id, "foreigns" => array(), "data" => $values));
 }
Exemplo n.º 6
0
 public static function value($extend, $value = null)
 {
     switch ($extend->field) {
         case 'text':
             if (!empty($extend->value->text)) {
                 $value = $extend->value->text;
             }
             break;
         case 'html':
             if (!empty($extend->value->html)) {
                 $md = new Markdown();
                 $value = $md->transform($extend->value->html);
             }
             break;
         case 'image':
         case 'file':
             if (!empty($extend->value->filename)) {
                 $value = asset('content/' . $extend->value->filename);
             }
             break;
     }
     return $value;
 }
Exemplo n.º 7
0
            $input['comments'] = 0;
        }
        if (empty($input['html'])) {
            $input['status'] = 'draft';
        }
        $post = Post::create($input);
        Extend::process('post', $post->id);
        Notify::success(__('posts.created'));
        return Response::redirect('admin/posts');
    });
    /*
    	Preview post
    */
    Route::post('admin/posts/preview', function () {
        $html = Input::get('html');
        // apply markdown processing
        $md = new Markdown();
        $output = Json::encode(array('html' => $md->transform($html)));
        return Response::create($output, 200, array('content-type' => 'application/json'));
    });
    /*
    	Delete post
    */
    Route::get('admin/posts/delete/(:num)', function ($id) {
        Post::find($id)->delete();
        Comment::where('post', '=', $id)->delete();
        Query::table(Base::table('post_meta'))->where('post', '=', $id)->delete();
        Notify::success(__('posts.deleted'));
        return Response::redirect('admin/posts');
    });
});
Exemplo n.º 8
0
 /**
  * @param string $text
  *
  * @return string
  */
 protected function parse_markdown($text)
 {
     static $markdown = null;
     if (is_null($markdown)) {
         $markdown = new Markdown();
     }
     return $markdown->transform($text);
 }
Exemplo n.º 9
0
 /**
  * Get the description as markdown
  * @Developer brandon
  * @Date Oct 13, 2010
  */
 public function content_formatted()
 {
     $markdown = new Markdown();
     return $markdown->transform($this->content);
 }
Exemplo n.º 10
0
        $post = Post::create($input);
        $id = $post->id;
        Extend::process('post', $id);
        // Notify::success(__('posts.created'));
        if (Input::get('autosave') === 'true') {
            return Response::json(array('id' => $id, 'notification' => __('posts.updated')));
        } else {
            return Response::json(array('id' => $id, 'notification' => __('posts.created'), 'redirect' => Uri::to('admin/posts/edit/' . $id)));
        }
    });
    /*
        Preview post
    */
    Route::post('admin/posts/preview', function () {
        $markdown = Input::get('markdown');
        // apply markdown processing
        $md = new Markdown();
        $output = Json::encode(array('markdown' => $md->transform($markdown)));
        return Response::create($output, 200, array('content-type' => 'application/json'));
    });
    /*
        Delete post
    */
    Route::get('admin/posts/delete/(:num)', function ($id) {
        Post::find($id)->delete();
        Comment::where('post', '=', $id)->delete();
        Query::table(Base::table('post_meta'))->where('post', '=', $id)->delete();
        Notify::success(__('posts.deleted'));
        return Response::redirect('admin/posts');
    });
});
Exemplo n.º 11
0
 /**
  * Get the description as markdown
  * @Developer brandon
  * @Date Oct 13, 2010
  */
 public function description_formatted()
 {
     $markdown = new Markdown();
     return $markdown->transform($this->description);
 }
Exemplo n.º 12
0
 /**
  * Get the description as markdown
  * @Developer brandon
  * @Date Oct 13, 2010
  */
 public function synopsis_formatted()
 {
     $markdown = new Markdown();
     return $markdown->transform($this->synopsis);
 }
function AdminUpdateCheck()
{
    global $updates_folder;
    $selected_file = '';
    // Выбранное имя файла обновления
    // Выбираем файл обновления и читаем метаданные
    if (!isset($_FILES['upload_file'])) {
        System::admin()->AddCenterBox('Ошибка');
        System::admin()->HighlightError('Неизвестная ошибка.');
        return;
    }
    $uploaded_file = $_FILES['upload_file'];
    // Загруженный файл
    // Сохраняем загруженный файл
    if ($uploaded_file['error'] != 4) {
        if ($uploaded_file['error'] != 0) {
            System::admin()->AddTextBox('Ошибка', 'Ошибка при загрузке файла. Код ошибки: ' . $_FILES['upload_file'] . '.');
            return;
        }
        if (!is_writable($updates_folder)) {
            System::admin()->AddCenterBox('Ошибка');
            System::admin()->HighlightError('Папка "' . SafeDB($updates_folder, 255, str) . '" не доступна для записи. Не удалось загрузить обновление.');
        } else {
            if (is_file($uploaded_file['tmp_name'])) {
                // Был загружен файл
                // Проверяем тип файла и сохраняем в папку updates
                if (strtolower(GetFileExt($_FILES['upload_file']['name'])) == '.zip') {
                    $selected_file = $updates_folder . $_FILES['upload_file']['name'];
                    copy($_FILES['upload_file']['tmp_name'], $selected_file);
                    Audit('Обновление системы: Загружен архив обновления "' . $selected_file . '"');
                } else {
                    System::admin()->AddCenterBox('Ошибка');
                    System::admin()->HighlightError('Разрешено загружать только ZIP файлы.');
                }
            }
        }
    } else {
        // Берем выбранный ранее загруженный файл
        if (isset($_POST['select_file'])) {
            $selected_file = $updates_folder . $_POST['select_file'];
        } else {
            System::admin()->AddCenterBox('Ошибка');
            System::admin()->HighlightError('Файл обновления не выбран.');
            return;
        }
    }
    // Проверяем select_file, пытаемся открыть и прочитать метаданные
    $zip = new ZipArchive();
    if ($zip->open($selected_file) !== true) {
        System::admin()->AddCenterBox('Ошибка');
        System::admin()->HighlightError('Не удалось открыть файл обновления, возможно архив повреждён.');
        return;
    }
    // Читаем метаданные
    $metadata = $zip->getFromName('metadata');
    $metadata = JsonDecode($metadata);
    if (!isset($metadata) || !isset($metadata['product']) || $metadata['product'] != CMS_UPDATE_PRODUCT || !isset($metadata['type']) || $metadata['type'] != 'update' || !isset($metadata['from_version']) || $metadata['from_version'] != CMS_VERSION || !isset($metadata['to_version']) || !isset($metadata['changelog'])) {
        System::admin()->AddCenterBox('Ошибка');
        System::admin()->HighlightError('Файл не является файлом обновления или не подходит к вашей версии системы.');
        return;
    }
    System::admin()->AddCenterBox('Обновление системы ' . SafeDB($metadata['from_version'], 20, str) . ' › ' . SafeDB($metadata['to_version'], 20, str));
    UseLib('markdown');
    $md = new Markdown();
    $metadata['changelog'] = $md->transform(SafeDB($metadata['changelog'], 0, str, false));
    // Проверяем разрешения на запись в файлы
    $update_files = '<h2>Обновляемые файлы:</h2><ul>';
    $numFiles = $zip->numFiles;
    $create = false;
    $reason = '';
    $create_dirs = array();
    $errors = false;
    for ($i = 0; $i < $numFiles; $i++) {
        $reason = '';
        $fn = $zip->getNameIndex($i);
        if ($fn == 'metadata') {
            continue;
        }
        if (substr($fn, -1) != '/') {
            // Файл
            if (is_file($fn)) {
                // Существует
                $create = is_writable($fn);
                $reason = 'Нет прав на запись';
            } else {
                $fn_path = GetPathName($fn, false);
                if (isset($create_dirs[$fn_path . '/'])) {
                    $create = $create_dirs[$fn_path . '/'];
                    $reason = 'Невозможно создать папку ' . $fn_path . '';
                } else {
                    $create = is_writable($fn_path);
                    $reason = 'Нет прав на запись в папку ' . $fn_path . '';
                }
            }
        } else {
            // Папка
            $create = IsPossiblyCreated($fn);
            $create_dirs[$fn] = $create;
            $reason = 'Невозможно создать, нет прав на запись';
        }
        if ($create) {
            $update_files .= '<li>' . SafeDB($fn, 255, str) . '</li>';
        } else {
            $update_files .= '<li style="color: red;">' . SafeDB($fn, 255, str) . ' (' . $reason . ')</li>';
            $errors = true;
        }
    }
    $update_files .= '</ul>';
    $zip->close();
    // Вывод информации
    System::site()->AddOnLoadJS(Indent('
		AdminUpdateShowChangelog = function(){
			$("#update_changelog").show();
			$("#update_files").hide();
		}
		AdminUpdateShowFiles = function(){
			$("#update_files").show();
			$("#update_changelog").hide();
		}
	'));
    if ($errors) {
        System::admin()->HighlightError('Невозможно обновить некоторые файлы и папки. Смотрите список файлов для более детальной информации.<br>');
    } else {
        System::admin()->Highlight('Ошибок не обнаружено, нажмите кнопку "Обновить" для обновления системы.');
    }
    $html = '
		<div style="margin: 10px 0 10px;">
			<a href="#" onclick="AdminUpdateShowChangelog(); return false;" class="button">Показать изменения</a>
			<a href="#" onclick="AdminUpdateShowFiles(); return false;" class="button">Показать файлы</a>
			' . ($errors ? '' : System::admin()->SpeedButton('Обновить', ADMIN_FILE . '?exe=update&a=apply&file=' . GetFileName($selected_file), '', true, true)) . '
		</div>
		<div id="update_changelog" style="' . ($errors ? 'display: none;' : '') . '">' . $metadata['changelog'] . '</div>
		<div id="update_files" style="' . ($errors ? '' : 'display: none;') . '">' . $update_files . '</div>
';
    System::admin()->AddText($html);
}