Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hierarchical relations across tags #2435

Merged
merged 12 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions config/Migrations/20200828235617_CreateTagsLinks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
use Migrations\AbstractMigration;

class CreateExports extends AbstractMigration
AlexandreMagueresse marked this conversation as resolved.
Show resolved Hide resolved
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('tagsLinks');
$table->addColumn('parent', 'integer', [
'default' => null,
'limit' => 11,
'null' => false,
]);
$table->addColumn('child', 'integer', [
'default' => null,
'limit' => 11,
'null' => false,
]);
$table->addColumn('user_id', 'integer', [
'default' => null,
'limit' => 11,
'null' => true,
]);
$table->addColumn('added_time', 'datetime', [
'default' => 'CURRENT_TIMESTAMP',
'null' => true,
]);
$table->create();
}
}
1 change: 1 addition & 0 deletions config/auth_actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
],
'sentences_lists' => [ '*' => User::ROLE_CONTRIBUTOR_OR_HIGHER ],
'tags' => [ '*' => User::ROLE_ADV_CONTRIBUTOR_OR_HIGHER ],
'tags_links' => [ '*' => User::ROLE_ADV_CONTRIBUTOR_OR_HIGHER ],
'transcriptions' => [ '*' => User::ROLE_CONTRIBUTOR_OR_HIGHER ],
'user' => [ '*' => User::ROLE_CONTRIBUTOR_OR_HIGHER ],
'users' => [ '*' => [ User::ROLE_ADMIN ] ],
Expand Down
14 changes: 14 additions & 0 deletions docs/database/tables/tags_links.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
--
-- Table structure for table `tags_links`
--
-- This table stores the tags relations.
--

DROP TABLE IF EXISTS `tags_links`;
CREATE TABLE `tags_links` (
`parent` int(11) NOT NULL,
`child` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`added_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`parent`, `child`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
16 changes: 1 addition & 15 deletions src/Controller/TagsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,23 +242,9 @@ public function search()
]);
}

/**
* Display list of tags for autocompletion.
*
* @param String $filter Filters the tags list with only those that contain the
* search string.
*/
public function autocomplete($search)
{
$this->helpers[] = 'Tags';

$query = $this->Tags->find();
$query->select(['name', 'id', 'nbrOfSentences']);
if (!empty($search)) {
$pattern = str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $search).'%';
$query->where(['name LIKE :search'])->bind(':search', $pattern, 'string');
}
$allTags = $query->order(['nbrOfSentences' => 'DESC'])->limit(10)->all();
$allTags = $this->Tags->Autocomplete($search);

$this->loadComponent('RequestHandler');
$this->set('allTags', $allTags);
Expand Down
118 changes: 118 additions & 0 deletions src/Controller/TagsLinksController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
/**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2010 Allan SIMON <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Controller;

use App\Controller\AppController;
use App\Event\SuggestdListener;
use Cake\Event\Event;
use App\Model\CurrentUser;


class TagsLinksController extends AppController
{
/**
* Controller name
*
* @var string
* @access public
*/
public $name = 'TagsLinks';
public $components = ['CommonSentence', 'Flash'];
public $helpers = ['Pagination'];

public function manage(){
$all_tags = array();
$links = array();
$temp = array();
$s = 0;
$this->loadModel('Tags');
foreach ($this->Tags->find('all', array('order' => 'id DESC'))->select(['id', 'name', 'nbrOfSentences']) as $key => $value){
$all_tags[$value['id']] = array($value['name'], $value['nbrOfSentences']);
$links[$value['id']] = array();
$temp[$value['id']] = array();
}
foreach ($this->TagsLinks->find('all')->select(['parent', 'child']) as $key => $value){
$s += 1;
array_push($links[$value['child']], $value['parent']);
array_push($temp[$value['parent']], $value['child']);
}

$tree = array();
foreach ($temp as $parent => $children){
if (!count($children))
$tree[$parent] = array();
}
while ($s) {
foreach ($links as $child => $parents) {
if (count($parents) && array_key_exists($child, $tree)){
// 1. copy
$subtree = $tree[$child];
// 2. remove
unset($tree[$child]);
// 3. replace
foreach ($parents as $parent) {
if (!array_key_exists($parent, $tree))
$tree[$parent] = [];
$tree[$parent][$child] = $subtree;
}
// 4. remove used links
$s -= count($parents);
$links[$child] = [];
}
}
}

$this->set('all_tags', $all_tags);
$this->set('tree', $tree);
}

/**
* Add a link
*
* @return void
*/

public function add()
{
$parent = $this->request->data('parentTag');
$child = $this->request->data('childTag');
$userId = CurrentUser::get("id");
$username = CurrentUser::get("username");
$link = $this->TagsLinks->addLink($parent, $child, $userId);
return $this->redirect([
'controller' => 'tags_links',
'action' => 'manage'
]);
}

/**
* Remove a link
*
* @return void
*/

public function remove($parent, $child)
{
$link = $this->TagsLinks->removeLink($parent, $child);
return $this->redirect([
'controller' => 'tags_links',
'action' => 'manage'
]);
}
}
70 changes: 70 additions & 0 deletions src/Model/Behavior/AutocompletableBehavior.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* Tatoeba Project, free collaborative creation of languages corpuses project
* Copyright (C) 2020 Tatoeba Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Model\Behavior;

use Cake\ORM\Behavior;
use Cake\ORM\Query;

/**
* Behavior for handling autocompletion
*
* This behavior adds the method 'Autocomplete' to a table which returns
* the top n results that contain a given query
*/
class AutocompletableBehavior extends Behavior
{
/**
* Default config
*
* index column to search from
* fields columns to return
*
* @var array
*/
protected $_defaultConfig = [
'implementedMethods' =>
['Autocomplete' => 'Autocomplete'],
'index' => ['name' => 'name', 'type' => 'string'],
'fields' => ['name', 'id', 'nbrOfSentences'],
'order' => ['nbrOfSentences' => 'DESC'],
'limit' => 10
];

public function Autocomplete($search)
{
$query = $this->getTable()->find();
$query->select($this->config('fields'));
AlexandreMagueresse marked this conversation as resolved.
Show resolved Hide resolved

if (!empty($search)) {
$pattern = str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $search).'%';
$query->where([$this->config('index')['name'].' LIKE :search'])
->bind(':search', $pattern, $this->config('index')['type']);
AlexandreMagueresse marked this conversation as resolved.
Show resolved Hide resolved
}

if (count($this->config('order'))) {
$query->order($this->config('order'));
}
AlexandreMagueresse marked this conversation as resolved.
Show resolved Hide resolved

if ($this->config('limit') > 0) {
$query->limit($this->config('limit'));
}
AlexandreMagueresse marked this conversation as resolved.
Show resolved Hide resolved

return $query->all();
}
}
93 changes: 93 additions & 0 deletions src/Model/Table/TagsLinksTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php
/**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2010 SIMON Allan <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Model\Table;

use App\Model\CurrentUser;
use Cake\Database\Schema\TableSchema;
use Cake\ORM\Table;
use Cake\Event\Event;

class TagsLinksTable extends Table
{
public function initialize(array $config)
{
// $this->hasMany('Tags');
$this->belongsToMany('Tags');
$this->belongsTo('Users');
$this->addBehavior('Timestamp');
}

/**
* Add a link
*
* @param String $parent
* @param String $child
* @param int $userId
*
* @return bool
*/
public function addLink($parent, $child, $userId)
{
// parent and child must reference the Tag database
$id_parent = $this->Tags->getIdFromName($parent);
$id_child = $this->Tags->getIdFromName($child);
if ($id_parent == null || $id_child == null){
return false;
}
// parent and child must be different
if ($id_parent == $id_child)
return false;

// prevent cycles: there must not exist a path from $child to $parent
$candidates = array($id_child);
$cycle = false;
while (!$cycle && count($candidates)) {
$new_candidates = array();
foreach ($this->find('all')->where(['parent IN' => $candidates])->select(['child']) as $key => $value){
array_push($new_candidates, $value['child']);
}
$candidates = $new_candidates;
$cycle = in_array($id_parent, $candidates);
}
if ($cycle)
return false;

$data = $this->newEntity([
'parent' => $id_parent,
'child' => $id_child,
'user_id' => $userId
]);
$added = $this->save($data);
return $added;
}

/**
* Remove a link
*
* @param int $parent
* @param int $child
*/
public function removeLink($parent, $child)
{
$this->deleteAll([
'parent' => $parent,
'child' => $child
]);
}
}
1 change: 1 addition & 0 deletions src/Model/Table/TagsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function initialize(array $config)
$this->belongsTo('Users');

$this->addBehavior('Timestamp');
$this->addBehavior('Autocompletable');
}

public function beforeMarshal($event, $data, $options)
Expand Down
Loading