Merge branch '163-export' into dev

Conflicts:
	app/layout/aside_feed.phtml
pull/474/head
Marien Fressinaud 11 years ago
commit 5f974c2567
  1. 2
      README.md
  2. 1
      app/Controllers/configureController.php
  3. 86
      app/Controllers/feedController.php
  4. 378
      app/Controllers/importExportController.php
  5. 6
      app/Exceptions/OpmlException.php
  6. 13
      app/Models/CategoryDAO.php
  7. 30
      app/Models/EntryDAO.php
  8. 30
      app/Models/FeedDAO.php
  9. 6
      app/i18n/en.php
  10. 6
      app/i18n/fr.php
  11. 4
      app/layout/aside_feed.phtml
  12. 71
      app/views/helpers/export/articles.phtml
  13. 41
      app/views/helpers/export/opml.phtml
  14. 12
      app/views/importExport/index.phtml
  15. 2
      lib/Minz/View.php
  16. 277
      lib/lib_opml.php
  17. 4
      lib/lib_rss.php

@ -27,7 +27,7 @@ Privilégiez pour cela des demandes sur GitHub
* Serveur Web Apache2 ou Nginx (non testé sur les autres)
* PHP 5.2.1+ (PHP 5.3.7+ recommandé)
* Requis : [PDO_MySQL](http://php.net/pdo-mysql), [cURL](http://php.net/curl), [LibXML](http://php.net/xml), [PCRE](http://php.net/pcre), [ctype](http://php.net/ctype)
* Recommandés : [JSON](http://php.net/json), [zlib](http://php.net/zlib), [mbstring](http://php.net/mbstring), [iconv](http://php.net/iconv)
* Recommandés : [JSON](http://php.net/json), [zlib](http://php.net/zlib), [mbstring](http://php.net/mbstring), [iconv](http://php.net/iconv), [Zip](http://php.net/zip)
* MySQL 5.0.3+ (ou SQLite 3.7.4+ à venir)
* Un navigateur Web récent tel Firefox 4+, Chrome, Opera, Safari, Internet Explorer 9+
* Fonctionne aussi sur mobile

@ -62,7 +62,6 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
$this->view->categories = $catDAO->listCategories (false);
$this->view->defaultCategory = $catDAO->getDefault ();
$this->view->feeds = $feedDAO->listFeeds ();
$this->view->flux = false;
Minz_View::prependTitle (Minz_Translate::t ('categories_management') . ' · ');
}

@ -368,80 +368,6 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
}
}
public function massiveImportAction () {
@set_time_limit(300);
$this->catDAO = new FreshRSS_CategoryDAO ();
$this->catDAO->checkDefault ();
$entryDAO = new FreshRSS_EntryDAO ();
$feedDAO = new FreshRSS_FeedDAO ();
$categories = Minz_Request::param ('categories', array (), true);
$feeds = Minz_Request::param ('feeds', array (), true);
// on ajoute les catégories en masse dans une fonction à part
$this->addCategories ($categories);
// on calcule la date des articles les plus anciens qu'on accepte
$nb_month_old = $this->view->conf->old_entries;
$date_min = time () - (3600 * 24 * 30 * $nb_month_old);
// la variable $error permet de savoir si une erreur est survenue
// Le but est de ne pas arrêter l'import même en cas d'erreur
// L'utilisateur sera mis au courant s'il y a eu des erreurs, mais
// ne connaîtra pas les détails. Ceux-ci seront toutefois logguées
$error = false;
$i = 0;
foreach ($feeds as $feed) {
try {
$values = array (
'id' => $feed->id (),
'url' => $feed->url (),
'category' => $feed->category (),
'name' => $feed->name (),
'website' => $feed->website (),
'description' => $feed->description (),
'lastUpdate' => 0,
'httpAuth' => $feed->httpAuth ()
);
// ajout du flux que s'il n'est pas déjà en BDD
if (!$feedDAO->searchByUrl ($values['url'])) {
$id = $feedDAO->addFeed ($values);
if ($id) {
$feed->_id ($id);
$feed->faviconPrepare();
} else {
$error = true;
}
}
} catch (FreshRSS_Feed_Exception $e) {
$error = true;
Minz_Log::record ($e->getMessage (), Minz_Log::WARNING);
}
}
if ($error) {
$res = Minz_Translate::t ('feeds_imported_with_errors');
} else {
$res = Minz_Translate::t ('feeds_imported');
}
$notif = array (
'type' => 'good',
'content' => $res
);
Minz_Session::_param ('notification', $notif);
Minz_Session::_param ('actualize_feeds', true);
// et on redirige vers la page d'accueil
Minz_Request::forward (array (
'c' => 'index',
'a' => 'index'
), true);
}
public function deleteAction () {
if (Minz_Request::isPost ()) {
$type = Minz_Request::param ('type', 'feed');
@ -485,16 +411,4 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
}
}
}
private function addCategories ($categories) {
foreach ($categories as $cat) {
if (!$this->catDAO->searchByName ($cat->name ())) {
$values = array (
'id' => $cat->id (),
'name' => $cat->name (),
);
$catDAO->addCategory ($values);
}
}
}
}

@ -3,84 +3,345 @@
class FreshRSS_importExport_Controller extends Minz_ActionController {
public function firstAction() {
if (!$this->view->loginOk) {
Minz_Error::error (
Minz_Error::error(
403,
array ('error' => array (Minz_Translate::t ('access_denied')))
array('error' => array(Minz_Translate::t('access_denied')))
);
}
require_once(LIB_PATH . '/lib_opml.php');
$this->catDAO = new FreshRSS_CategoryDAO();
$this->entryDAO = new FreshRSS_EntryDAO();
$this->feedDAO = new FreshRSS_FeedDAO();
}
public function indexAction() {
$catDAO = new FreshRSS_CategoryDAO ();
$this->view->categories = $catDAO->listCategories ();
$feedDAO = new FreshRSS_FeedDAO ();
$this->view->feeds = $feedDAO->listFeeds ();
// au niveau de la vue, permet de ne pas voir un flux sélectionné dans la liste
$this->view->flux = false;
$this->view->categories = $this->catDAO->listCategories();
$this->view->feeds = $this->feedDAO->listFeeds();
Minz_View::prependTitle (Minz_Translate::t ('import_export') . ' · ');
Minz_View::prependTitle(Minz_Translate::t('import_export') . ' · ');
}
public function importAction() {
if (Minz_Request::isPost() && $_FILES['file']['error'] == 0) {
invalidateHttpCache();
// on parse le fichier OPML pour récupérer les catégories et les flux associés
try {
list ($categories, $feeds) = opml_import (
file_get_contents ($_FILES['file']['tmp_name'])
@set_time_limit(300);
$file = $_FILES['file'];
$type_file = $this->guessFileType($file['name']);
$list_files = array(
'opml' => array(),
'json_starred' => array(),
'json_feed' => array()
);
// We try to list all files according to their type
// A zip file is first opened and then its files are listed
$list = array();
if ($type_file === 'zip') {
$zip = zip_open($file['tmp_name']);
while (($zipfile = zip_read($zip)) !== false) {
$type_zipfile = $this->guessFileType(
zip_entry_name($zipfile)
);
if ($type_file !== 'unknown') {
$list_files[$type_zipfile][] = zip_entry_read(
$zipfile,
zip_entry_filesize($zipfile)
);
}
}
zip_close($zip);
} elseif ($type_file !== 'unknown') {
$list_files[$type_file][] = file_get_contents(
$file['tmp_name']
);
}
// On redirige vers le controller feed qui va se charger d'insérer les flux en BDD
// les flux sont mis au préalable dans des variables de Request
Minz_Request::_param ('categories', $categories);
Minz_Request::_param ('feeds', $feeds);
Minz_Request::forward (array ('c' => 'feed', 'a' => 'massiveImport'));
} catch (FreshRSS_Opml_Exception $e) {
Minz_Log::record ($e->getMessage (), Minz_Log::WARNING);
$notif = array (
'type' => 'bad',
'content' => Minz_Translate::t ('bad_opml_file')
// Import different files.
// OPML first(so categories and feeds are imported)
// Starred articles then so the "favourite" status is already set
// And finally all other files.
$error = false;
foreach ($list_files['opml'] as $opml_file) {
$error = $this->importOpml($opml_file);
}
foreach ($list_files['json_starred'] as $article_file) {
$error = $this->importArticles($article_file, true);
}
foreach ($list_files['json_feed'] as $article_file) {
$error = $this->importArticles($article_file);
}
// And finally, we get import status and redirect to the home page
$notif = null;
if ($error === true) {
$content_notif = Minz_Translate::t(
'feeds_imported_with_errors'
);
Minz_Session::_param ('notification', $notif);
} else {
$content_notif = Minz_Translate::t(
'feeds_imported'
);
}
Minz_Session::_param('notification', array(
'type' => 'good',
'content' => $content_notif
));
Minz_Session::_param('actualize_feeds', true);
Minz_Request::forward(array(
'c' => 'index',
'a' => 'index'
), true);
}
// What are you doing? you have to call this controller
// with a POST request!
Minz_Request::forward(array(
'c' => 'importExport',
'a' => 'index'
));
}
private function guessFileType($filename) {
// A *very* basic guess file type function. Only based on filename
// That's could be improved but should be enough, at least for a first
// implementation.
// TODO: improve this function?
Minz_Request::forward (array (
'c' => 'configure',
'a' => 'importExport'
), true);
if (substr_compare($filename, '.zip', -4) === 0) {
return 'zip';
} elseif (substr_compare($filename, '.opml', -5) === 0 ||
substr_compare($filename, '.xml', -4) === 0) {
return 'opml';
} elseif (strcmp($filename, 'starred.json') === 0) {
return 'json_starred';
} elseif (substr_compare($filename, '.json', -5) === 0 &&
strpos($filename, 'feed_') === 0) {
return 'json_feed';
} else {
return 'unknown';
}
}
private function importOpml($opml_file) {
$opml_array = array();
try {
$opml_array = libopml_parse_string($opml_file);
} catch (LibOPML_Exception $e) {
Minz_Log::warning($e->getMessage());
return true;
}
$this->catDAO->checkDefault();
return $this->addOpmlElements($opml_array['body']);
}
private function addOpmlElements($opml_elements, $parent_cat = null) {
$error = false;
foreach ($opml_elements as $elt) {
$res = false;
if (isset($elt['xmlUrl'])) {
$res = $this->addFeedOpml($elt, $parent_cat);
} else {
$res = $this->addCategoryOpml($elt, $parent_cat);
}
if (!$error && $res) {
// oops: there is at least one error!
$error = $res;
}
}
return $error;
}
private function addFeedOpml($feed_elt, $parent_cat) {
if (is_null($parent_cat)) {
// This feed has no parent category so we get the default one
$parent_cat = $this->catDAO->getDefault()->name();
}
$cat = $this->catDAO->searchByName($parent_cat);
if (!$cat) {
return true;
}
// We get different useful information
$url = html_chars_utf8($feed_elt['xmlUrl']);
$name = html_chars_utf8($feed_elt['text']);
$website = '';
if (isset($feed_elt['htmlUrl'])) {
$website = html_chars_utf8($feed_elt['htmlUrl']);
}
$description = '';
if (isset($feed_elt['description'])) {
$description = html_chars_utf8($feed_elt['description']);
}
$error = false;
try {
// Create a Feed object and add it in DB
$feed = new FreshRSS_Feed($url);
$feed->_category($cat->id());
$feed->_name($name);
$feed->_website($website);
$feed->_description($description);
// addFeedObject checks if feed is already in DB so nothing else to
// check here
$id = $this->feedDAO->addFeedObject($feed);
$error = ($id === false);
} catch (FreshRSS_Feed_Exception $e) {
Minz_Log::warning($e->getMessage());
$error = true;
}
return $error;
}
private function addCategoryOpml($cat_elt, $parent_cat) {
// Create a new Category object
$cat = new FreshRSS_Category(html_chars_utf8($cat_elt['text']));
$id = $this->catDAO->addCategoryObject($cat);
$error = ($id === false);
if (isset($cat_elt['@outlines'])) {
// Our cat_elt contains more categories or more feeds, so we
// add them recursively.
// Note: FreshRSS does not support yet category arborescence
$res = $this->addOpmlElements($cat_elt['@outlines'], $cat->name());
if (!$error && $res) {
$error = true;
}
}
return $error;
}
private function importArticles($article_file, $starred = false) {
$article_object = json_decode($article_file, true);
if (is_null($article_object)) {
Minz_Log::warning('Try to import a non-JSON file');
return true;
}
$is_read = $this->view->conf->mark_when['reception'] ? 1 : 0;
$google_compliant = (
strpos($article_object['id'], 'com.google') !== false
);
$error = false;
foreach ($article_object['items'] as $item) {
$feed = $this->addFeedArticles($item['origin'], $google_compliant);
if (is_null($feed)) {
$error = true;
continue;
}
$author = isset($item['author']) ? $item['author'] : '';
$key_content = ($google_compliant && !isset($item['content'])) ?
'summary' : 'content';
$tags = $item['categories'];
if ($google_compliant) {
$tags = array_filter($tags, function($var) {
return strpos($var, '/state/com.google') === false;
});
}
$entry = new FreshRSS_Entry(
$feed->id(), $item['id'], $item['title'], $author,
$item[$key_content]['content'], $item['alternate'][0]['href'],
$item['published'], $is_read, $starred
);
$entry->_tags($tags);
$id = $this->entryDAO->addEntryObject(
$entry, $this->view->conf, $feed->keepHistory()
);
if (!$error && ($id === false)) {
$error = true;
}
}
return $error;
}
private function addFeedArticles($origin, $google_compliant) {
$default_cat = $this->catDAO->getDefault();
$return = null;
$key = $google_compliant ? 'htmlUrl' : 'feedUrl';
$url = $origin[$key];
$name = $origin['title'];
$website = $origin['htmlUrl'];
$error = false;
try {
// Create a Feed object and add it in DB
$feed = new FreshRSS_Feed($url);
$feed->_category($default_cat->id());
$feed->_name($name);
$feed->_website($website);
// addFeedObject checks if feed is already in DB so nothing else to
// check here
$id = $this->feedDAO->addFeedObject($feed);
if ($id !== false) {
$feed->_id($id);
$return = $feed;
}
} catch (FreshRSS_Feed_Exception $e) {
Minz_Log::warning($e->getMessage());
}
return $return;
}
public function exportAction() {
if (Minz_Request::isPost()) {
$this->view->_useLayout (false);
$this->view->_useLayout(false);
$export_opml = Minz_Request::param('export_opml', false);
$export_starred = Minz_Request::param('export_starred', false);
$export_all = Minz_Request::param('export_all', false);
$export_feeds = Minz_Request::param('export_feeds', false);
// code from https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
// From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
$file = tempnam('tmp', 'zip');
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
// Stuff with content
if ($export_opml) {
$zip->addFromString('feeds.opml', $this->generate_opml());
$zip->addFromString(
'feeds.opml', $this->generateOpml()
);
}
if ($export_starred) {
$zip->addFromString('starred.json', $this->generate_articles('starred'));
$zip->addFromString(
'starred.json', $this->generateArticles('starred')
);
}
if ($export_all) {
$zip->addFromString('all.json', $this->generate_articles('all'));
foreach ($export_feeds as $feed_id) {
$feed = $this->feedDAO->searchById($feed_id);
$zip->addFromString(
'feed_' . $feed->category() . '_' . $feed->id() . '.json',
$this->generateArticles('feed', $feed)
);
}
// Close and send to users
// Close and send to user
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
@ -90,22 +351,39 @@ class FreshRSS_importExport_Controller extends Minz_ActionController {
}
}
private function generate_opml() {
$feedDAO = new FreshRSS_FeedDAO ();
$catDAO = new FreshRSS_CategoryDAO ();
$list = array ();
foreach ($catDAO->listCategories () as $key => $cat) {
$list[$key]['name'] = $cat->name ();
$list[$key]['feeds'] = $feedDAO->listByCategory ($cat->id ());
private function generateOpml() {
$list = array();
foreach ($this->catDAO->listCategories() as $key => $cat) {
$list[$key]['name'] = $cat->name();
$list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id());
}
$this->view->categories = $list;
return $this->view->helperToString('export/opml');
}
private function generate_articles($type) {
// TODO: we should get articles according to $type
private function generateArticles($type, $feed = NULL) {
$this->view->categories = $this->catDAO->listCategories();
if ($type == 'starred') {
$this->view->list_title = Minz_Translate::t('starred_list');
$this->view->type = 'starred';
$this->view->entries = $this->entryDAO->listWhere(
's', '', 'all', 'ASC',
$this->entryDAO->countUnreadReadFavorites()['all']
);
} elseif ($type == 'feed' && !is_null($feed)) {
$this->view->list_title = Minz_Translate::t(
'feed_list', $feed->name()
);
$this->view->type = 'feed/' . $feed->id();
$this->view->entries = $this->entryDAO->listWhere(
'f', $feed->id(), 'all', 'ASC',
$this->view->conf->posts_per_page
);
$this->view->feed = $feed;
}
return $this->view->helperToString('export/articles');
}
}

@ -1,6 +0,0 @@
<?php
class FreshRSS_Opml_Exception extends FreshRSS_Feed_Exception {
public function __construct ($name_file) {
parent::__construct ('OPML file is invalid');
}
}

@ -18,6 +18,19 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
}
}
public function addCategoryObject($category) {
$cat = $this->searchByName($category->name());
if (!$cat) {
// Category does not exist yet in DB so we add it before continue
$values = array(
'name' => $category->name(),
);
return $this->addCategory($values);
}
return $cat->id();
}
public function updateCategory ($id, $valuesTmp) {
$sql = 'UPDATE `' . $this->prefix . 'category` SET name=? WHERE id=?';
$stm = $this->bd->prepare ($sql);

@ -35,6 +35,36 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
}
}
public function addEntryObject($entry, $conf, $feedHistory) {
$existingGuids = array_fill_keys(
$this->listLastGuidsByFeed($entry->feed(), 20), 1
);
$nb_month_old = max($conf->old_entries, 1);
$date_min = time() - (3600 * 24 * 30 * $nb_month_old);
$eDate = $entry->date(true);
if ($feedHistory == -2) {
$feedHistory = $conf->keep_history_default;
}
if (!isset($existingGuids[$entry->guid()]) &&
($feedHistory != 0 || $eDate >= $date_min)) {
$values = $entry->toArray();
$useDeclaredDate = empty($existingGuids);
$values['id'] = ($useDeclaredDate || $eDate < $date_min) ?
min(time(), $eDate) . uSecString() :
uTimeString();
return $this->addEntry($values);
}
// We don't return Entry object to avoid a research in DB
return -1;
}
public function markFavorite($ids, $is_favorite = true) {
if (!is_array($ids)) {
$ids = array($ids);

@ -24,6 +24,36 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
}
}
public function addFeedObject($feed) {
// TODO: not sure if we should write this method in DAO since DAO
// should not be aware about feed class
// Add feed only if we don't find it in DB
$feed_search = $this->searchByUrl($feed->url());
if (!$feed_search) {
$values = array(
'id' => $feed->id(),
'url' => $feed->url(),
'category' => $feed->category(),
'name' => $feed->name(),
'website' => $feed->website(),
'description' => $feed->description(),
'lastUpdate' => 0,
'httpAuth' => $feed->httpAuth()
);
$id = $this->addFeed($values);
if ($id) {
$feed->_id($id);
$feed->faviconPrepare();
}
return $id;
}
return $feed_search->id();
}
public function updateFeed ($id, $valuesTmp) {
$set = '';
foreach ($valuesTmp as $key => $v) {

@ -138,9 +138,13 @@ return array (
'auto_share' => 'Share',
'auto_share_help' => 'If there is only one sharing mode, it is used. Else modes are accessible by their number.',
'file_to_import' => 'File to import',
'file_to_import' => 'File to import (OPML)',
'import' => 'Import',
'export' => 'Export',
'export_opml' => 'Export list of feeds (OPML)',
'export_starred' => 'Export your favourites',
'starred_list' => 'List of favourite articles',
'feed_list' => 'List of %s articles',
'or' => 'or',
'informations' => 'Information',

@ -138,9 +138,13 @@ return array (
'auto_share' => 'Partager',
'auto_share_help' => 'Si il n’y a qu’un mode de partage, celui ci est utilisé automatiquement. Sinon ils sont accessibles par leur numéro.',
'file_to_import' => 'Fichier à importer',
'file_to_import' => 'Fichier à importer (OPML)',
'import' => 'Importer',
'export' => 'Exporter',
'export_opml' => 'Exporter la liste des flux (OPML)',
'export_starred' => 'Exporter les favoris',
'starred_list' => 'Liste des articles favoris',
'feed_list' => 'Liste des articles de %s',
'or' => 'ou',
'informations' => 'Informations',

@ -49,7 +49,7 @@
</a>
</li>
<li class="item<?php echo Minz_Request::actionName () == 'importExport' ? ' active' : ''; ?>">
<li class="item<?php echo Minz_Request::controllerName () == 'importExport' ? ' active' : ''; ?>">
<a href="<?php echo _url ('importExport', 'index'); ?>"><?php echo Minz_Translate::t ('import_export'); ?></a>
</li>
@ -62,7 +62,7 @@
<?php if (!empty ($this->feeds)) { ?>
<?php foreach ($this->feeds as $feed) { ?>
<?php $nbEntries = $feed->nbEntries (); ?>
<li class="item<?php echo ($this->flux && $this->flux->id () == $feed->id ()) ? ' active' : ''; ?><?php echo $feed->inError () ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>">
<li class="item<?php echo (isset($this->flux) && $this->flux->id () == $feed->id ()) ? ' active' : ''; ?><?php echo $feed->inError () ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>">
<a href="<?php echo _url ('configure', 'feed', 'id', $feed->id ()); ?>">
<img class="favicon" src="<?php echo $feed->favicon (); ?>" alt="✇" />
<?php echo $feed->name (); ?>

@ -1,30 +1,47 @@
<?php
// TODO: A lot have to be done!
$username = Minz_Session::param('currentUser', '_');
$type_id = "TODO";
$title = Minz_Translate::t("TODO");
$entries = [];
?>{
"id": "user/<?php echo str_replace("\"", "", $username); ?>/state/org.freshrss/<?php echo $type_id; ?>",
"title": "<?php echo addslashes($title); ?>",
"author": "<?php echo addslashes($username); ?>",
"items": [
<?php $i = 0; foreach($entries as $entry) { $i++;
echo $i > 1 ? ', ': ''; ?>{
"id": "<?php echo $entry->id(); ?>",
"categories": [<?php /* TODO */ ?>],
"title": "<?php echo addslashes($entry->title()); ?>",
"published": <?php echo $entry->date(true); ?>,
"updated": <?php echo $entry->date(true); ?>,
"content": "<?php echo addslashes($entry->content()); ?>",
"origin": {
<?php /* TODO */ ?>
"streamId": "",
"title": "",
"htmlUrl": "",
"feedUrl": ""
}
$articles = array(
'id' => 'user/' . str_replace('/', '', $username) . '/state/org.freshrss/' . $this->type,
'title' => $this->list_title,
'author' => $username,
'items' => array()
);
foreach ($this->entries as $entry) {
if (!isset($this->feed)) {
$feed = FreshRSS_CategoryDAO::findFeed($this->categories, $entry->feed ());
} else {
$feed = $this->feed;
}
<?php } ?>
]
}
$articles['items'][] = array(
'id' => $entry->guid(),
'categories' => array_values($entry->tags()),
'title' => $entry->title(),
'author' => $entry->author(),
'published' => $entry->date(true),
'updated' => $entry->date(true),
'alternate' => array(array(
'href' => $entry->link(),
'type' => 'text/html'
)),
'content' => array(
'content' => $entry->content()
),
'origin' => array(
'streamId' => $feed->id(),
'title' => $feed->name(),
'htmlUrl' => $feed->website(),
'feedUrl' => $feed->url()
)
);
}
$options = 0;
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
$options = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
}
echo json_encode($articles, $options);
?>

@ -1,15 +1,28 @@
<?php
require_once(LIB_PATH . '/lib_opml.php');
echo '<?xml version="1.0" encoding="UTF-8" ?>';
?>
<!-- Generated by <?php echo Minz_Configuration::title (); ?> -->
<opml version="2.0">
<head>
<title><?php echo Minz_Configuration::title (); ?> OPML Feed</title>
<dateCreated><?php echo date('D, d M Y H:i:s'); ?></dateCreated>
</head>
<body>
<?php echo opml_export ($this->categories); ?>
</body>
</opml>
$opml_array = array(
'head' => array(
'title' => Minz_Configuration::title(),
'dateCreated' => date('D, d M Y H:i:s')
),
'body' => array()
);
foreach ($this->categories as $key => $cat) {
$opml_array['body'][$key] = array(
'text' => $cat['name'],
'@outlines' => array()
);
foreach ($cat['feeds'] as $feed) {
$opml_array['body'][$key]['@outlines'][] = array(
'text' => htmlspecialchars_decode($feed->name()),
'type' => 'rss',
'xmlUrl' => $feed->url(),
'htmlUrl' => $feed->website(),
'description' => $feed->description()
);
}
}
echo libopml_render($opml_array);

@ -19,6 +19,7 @@
</div>
</form>
<?php if (count($this->feeds) > 0) { ?>
<form method="post" action="<?php echo _url('importExport', 'export'); ?>">
<legend><?php echo Minz_Translate::t ('export'); ?></legend>
<div class="form-group">
@ -33,11 +34,11 @@
<?php echo Minz_Translate::t ('export_starred'); ?>
</label>
<label class="checkbox" for="export_all">
<input type="checkbox" name="export_all" id="export_all" value="1" />
<?php echo Minz_Translate::t ('export_all'); ?>
<?php echo FreshRSS_Themes::icon('help'); ?> <?php echo Minz_Translate::t('export_all_is_long'); ?>
</label>
<select name="export_feeds[]" size="<?php echo min(10, count($this->feeds)); ?>" multiple="multiple">
<?php foreach ($this->feeds as $feed) { ?>
<option value="<?php echo $feed->id(); ?>"><?php echo $feed->name(); ?></option>
<?php } ?>
</select>
</div>
</div>
@ -47,4 +48,5 @@
</div>
</div>
</form>
<?php } ?>
</div>

@ -108,7 +108,7 @@ class Minz_View {
*/
public function helperToString($helper) {
ob_start();
renderHelper($helper);
$this->renderHelper($helper);
return ob_get_clean();
}

@ -1,23 +1,86 @@
<?php
function opml_export ($cats) {
$txt = '';
foreach ($cats as $cat) {
$txt .= '<outline text="' . $cat['name'] . '">' . "\n";
foreach ($cat['feeds'] as $feed) {
$txt .= "\t" . '<outline text="' . $feed->name () . '" type="rss" xmlUrl="' . $feed->url () . '" htmlUrl="' . $feed->website () . '" description="' . htmlspecialchars($feed->description(), ENT_COMPAT, 'UTF-8') . '" />' . "\n";
/* *
* lib_opml is a free library to manage OPML format in PHP.
* It takes in consideration only version 2.0 (http://dev.opml.org/spec2.html).
* Basically it means "text" attribute for outline elements is required.
*
* lib_opml requires SimpleXML (http://php.net/manual/en/book.simplexml.php)
*
* Usages:
* > include('lib_opml.php');
* > $filename = 'my_opml_file.xml';
* > $opml_array = libopml_parse_file($filename);
* > print_r($opml_array);
*
* > $opml_string = [...];
* > $opml_array = libopml_parse_string($opml_string);
* > print_r($opml_array);
*
* > $opml_array = [...];
* > $opml_string = libopml_render($opml_array);
* > $opml_object = libopml_render($opml_array, true);
* > echo $opml_string;
* > print_r($opml_object);
*
* If parsing fails for any reason (e.g. not an XML string, does not match with
* the specifications), a LibOPML_Exception is raised.
*
* Author: Marien Fressinaud <dev@marienfressinaud.fr>
* Url: https://github.com/marienfressinaud/lib_opml
* Version: 0.1
* Date: 2014-03-29
* License: public domain
*
* */
class LibOPML_Exception extends Exception {}
// These elements are optional
define('HEAD_ELEMENTS', serialize(array(
'title', 'dateCreated', 'dateModified', 'ownerName', 'ownerEmail',
'ownerId', 'docs', 'expansionState', 'vertScrollState', 'windowTop',
'windowLeft', 'windowBottom', 'windowRight'
)));
function libopml_parse_outline($outline_xml) {
$outline = array();
// An outline may contain any kind of attributes but "text" attribute is
// required !
$text_is_present = false;
foreach ($outline_xml->attributes() as $key => $value) {
$outline[$key] = (string)$value;
if ($key === 'text') {
$text_is_present = true;
}
}
$txt .= '</outline>' . "\n";
if (!$text_is_present) {
throw new LibOPML_Exception(
'Outline does not contain any text attribute'
);
}
return $txt;
foreach ($outline_xml->children() as $key => $value) {
// An outline may contain any number of outline children
if ($key === 'outline') {
$outline['@outlines'][] = libopml_parse_outline($value);
} else {
throw new LibOPML_Exception(
'Body can contain only outline elements'
);
}
}
return $outline;
}
function opml_import ($xml) {
$xml = html_only_entity_decode($xml); //!\ Assume UTF-8
function libopml_parse_string($xml) {
$dom = new DOMDocument();
$dom->recover = true;
$dom->strictErrorChecking = false;
@ -27,94 +90,142 @@ function opml_import ($xml) {
$opml = simplexml_import_dom($dom);
if (!$opml) {
throw new FreshRSS_Opml_Exception ();
throw new LibOPML_Exception();
}
$catDAO = new FreshRSS_CategoryDAO();
$catDAO->checkDefault();
$defCat = $catDAO->getDefault();
$array = array(
'version' => (string)$opml['version'],
'head' => array(),
'body' => array()
);
// First, we get all "head" elements. Head is required but its sub-elements
// are optional.
foreach ($opml->head->children() as $key => $value) {
if (in_array($key, unserialize(HEAD_ELEMENTS), true)) {
$array['head'][$key] = (string)$value;
} else {
throw new LibOPML_Exception(
$key . 'is not part of OPML format'
);
}
}
$categories = array ();
$feeds = array ();
// Then, we get body oulines. Body must contain at least one outline
// element.
$at_least_one_outline = false;
foreach ($opml->body->children() as $key => $value) {
if ($key === 'outline') {
$at_least_one_outline = true;
$array['body'][] = libopml_parse_outline($value);
} else {
throw new LibOPML_Exception(
'Body can contain only outline elements'
);
}
}
if (!$at_least_one_outline) {
throw new LibOPML_Exception(
'Body must contain at least one outline element'
);
}
foreach ($opml->body->outline as $outline) {
if (!isset ($outline['xmlUrl'])) {
// Catégorie
$title = '';
return $array;
}
if (isset ($outline['text'])) {
$title = (string) $outline['text'];
} elseif (isset ($outline['title'])) {
$title = (string) $outline['title'];
}
if ($title) {
// Permet d'éviter les soucis au niveau des id :
// ceux-ci sont générés en fonction de la date,
// un flux pourrait être dans une catégorie X avec l'id Y
// alors qu'il existe déjà la catégorie X mais avec l'id Z
// Y ne sera pas ajouté et le flux non plus vu que l'id
// de sa catégorie n'exisera pas
$title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
$catDAO = new FreshRSS_CategoryDAO ();
$cat = $catDAO->searchByName ($title);
if ($cat == null) {
$cat = new FreshRSS_Category ($title);
$values = array (
'name' => $cat->name ()
);
$cat->_id ($catDAO->addCategory ($values));
}
$feeds = array_merge ($feeds, getFeedsOutline ($outline, $cat->id ()));
function libopml_parse_file($filename) {
$file_content = file_get_contents($filename);
if ($file_content === false) {
throw new LibOPML_Exception(
$filename . ' cannot be found'
);
}
return libopml_parse_string($file_content);
}
function libopml_render_outline($parent_elt, $outline) {
// Outline MUST be an array!
if (!is_array($outline)) {
throw new LibOPML_Exception(
'Outline element must be defined as array'
);
}
$outline_elt = $parent_elt->addChild('outline');
$text_is_present = false;
foreach ($outline as $key => $value) {
// Only outlines can be an array and so we consider children are also
// outline elements.
if ($key === '@outlines' && is_array($value)) {
foreach ($value as $outline_child) {
libopml_render_outline($outline_elt, $outline_child);
}
} elseif (is_array($value)) {
throw new LibOPML_Exception(
'Type of outline elements cannot be array: ' . $key
);
} else {
// Flux rss sans catégorie, on récupère l'ajoute dans la catégorie par défaut
$feeds[] = getFeed ($outline, $defCat->id());
// Detect text attribute is present, that's good :)
if ($key === 'text') {
$text_is_present = true;
}
$outline_elt->addAttribute($key, $value);
}
}
return array ($categories, $feeds);
if (!$text_is_present) {
throw new LibOPML_Exception(
'You must define at least a text element for all outlines'
);
}
}
/**
* import all feeds of a given outline tag
*/
function getFeedsOutline ($outline, $cat_id) {
$feeds = array ();
foreach ($outline->children () as $child) {
if (isset ($child['xmlUrl'])) {
$feeds[] = getFeed ($child, $cat_id);
} else {
$feeds = array_merge(
$feeds,
getFeedsOutline ($child, $cat_id)
);
function libopml_render($array, $as_xml_object = false) {
$opml = new SimpleXMLElement('<opml version="2.0"></opml>');
// Create head element. $array['head'] is optional but head element will
// exist in the final XML object.
$head = $opml->addChild('head');
if (isset($array['head'])) {
foreach ($array['head'] as $key => $value) {
if (in_array($key, unserialize(HEAD_ELEMENTS), true)) {
$head->addChild($key, $value);
}
}
}
return $feeds;
}
// Check body is set and contains at least one element
if (!isset($array['body'])) {
throw new LibOPML_Exception(
'$array must contain a body element'
);
}
if (count($array['body']) <= 0) {
throw new LibOPML_Exception(
'Body element must contain at least one element (array)'
);
}
function getFeed ($outline, $cat_id) {
$url = (string) $outline['xmlUrl'];
$url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8');
$title = '';
if (isset ($outline['text'])) {
$title = (string) $outline['text'];
} elseif (isset ($outline['title'])) {
$title = (string) $outline['title'];
}
$title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
$feed = new FreshRSS_Feed ($url);
$feed->_category ($cat_id);
$feed->_name ($title);
if (isset($outline['htmlUrl'])) {
$feed->_website(htmlspecialchars((string)$outline['htmlUrl'], ENT_COMPAT, 'UTF-8'));
}
if (isset($outline['description'])) {
$feed->_description(sanitizeHTML((string)$outline['description']));
}
return $feed;
// Create outline elements
$body = $opml->addChild('body');
foreach ($array['body'] as $outline) {
libopml_render_outline($body, $outline);
}
// And return the final result
if ($as_xml_object) {
return $opml;
} else {
$dom = dom_import_simplexml($opml)->ownerDocument;
$dom->formatOutput = true;
$dom->encoding = 'UTF-8';
return $dom->saveXML();
}
}

@ -244,3 +244,7 @@ function cryptAvailable() {
}
return false;
}
function html_chars_utf8($str) {
return htmlspecialchars($str, ENT_COMPAT, 'UTF-8');
}

Loading…
Cancel
Save