PageRenderTime 80ms CodeModel.GetById 59ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 0ms

/library/content.php

https://github.com/alugo/Goteo
PHP | 362 lines | 247 code | 59 blank | 56 comment | 25 complexity | a7a1b2d03378f3846bf7e4cd07c4b806 MD5 | raw file
  1<?php
  2/*
  3 *  Copyright (C) 2012 Platoniq y Fundación Fuentes Abiertas (see README for details)
  4 *	This file is part of Goteo.
  5 *
  6 *  Goteo is free software: you can redistribute it and/or modify
  7 *  it under the terms of the GNU Affero General Public License as published by
  8 *  the Free Software Foundation, either version 3 of the License, or
  9 *  (at your option) any later version.
 10 *
 11 *  Goteo is distributed in the hope that it will be useful,
 12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 14 *  GNU Affero General Public License for more details.
 15 *
 16 *  You should have received a copy of the GNU Affero General Public License
 17 *  along with Goteo.  If not, see <http://www.gnu.org/licenses/agpl.txt>.
 18 *
 19 */
 20
 21namespace Goteo\Library {
 22
 23	use Goteo\Core\Model,
 24        Goteo\Core\Exception;
 25
 26	/*
 27	 * Clase para gestionar la traducción de registros de tablas de contenido
 28     *
 29     * Ojo, todos los campos de traduccion son texto (a ver como sabemos si corto o largo...)
 30     *
 31	 */
 32    class Content {
 33
 34        public static function _tables() {
 35         return array(
 36                'promote'   => Text::_('Proyectos destacados'),
 37                'patron'    => Text::_('Proyectos apadrinados'),
 38                'icon'      => Text::_('Tipos de retorno/recompensa'),
 39                'license'   => Text::_('Licencias'),
 40                'category'  => Text::_('Categorías'),
 41                'news'      => Text::_('Noticias'),
 42                'faq'       => Text::_('Faq'),
 43                'post'      => Text::_('Blog'),
 44                'banner'    => Text::_('Banners'),
 45                'tag'       => Text::_('Tags'),
 46                'criteria'  => Text::_('Criterios de evaluación'),
 47                'worthcracy'=> Text::_('Meritocrácia'),
 48                'template'  => Text::_('Plantillas emails automáticos'),
 49                'glossary'  => Text::_('Glosario de términos'),
 50                'info'      => Text::_('Ideas de about')
 51            );
 52        }
 53
 54        public static function _fields() {
 55
 56            return array(
 57                'banner' => array (
 58                    'title' => Text::_('Título'),
 59                    'description' => Text::_('Descripción')
 60                ),
 61                'promote' => array (
 62                    'title' => Text::_('Título'),
 63                    'description' => Text::_('Descripción')
 64                ),
 65                'patron' => array (
 66                    'title' => Text::_('Título'),
 67                    'description' => Text::_('Descripción')
 68                ),
 69                'icon' => array (
 70                    'name' => Text::_('Nombre'),
 71                    'description' => Text::_('Descripción')
 72                ),
 73                'license' => array (
 74                    'name' => Text::_('Nombre'),
 75                    'description' => Text::_('Descripción'),
 76                    'url' => 'Enlace'
 77                ),
 78                'category' => array (
 79                    'name' => Text::_('Nombre'),
 80                    'description' => Text::_('Descripción')
 81                ),
 82                'news' => array (
 83                    'title' => Text::_('Título'),
 84                    'description' => Text::_('Entradilla')
 85                ),
 86                'faq' => array (
 87                    'title' => Text::_('Título'),
 88                    'description' => Text::_('Descripción')
 89                ),
 90                'post' => array (
 91                    'title' => Text::_('Título'),
 92                    'text' => Text::_('Texto entrada'),
 93                    'legend' => Text::_('Leyenda media')
 94                ),
 95                'tag' => array (
 96                    'name' => Text::_('Nombre')
 97                ),
 98                'criteria' => array (
 99                    'title' => Text::_('Título')
100                ),
101                'worthcracy' => array (
102                    'name' => Text::_('Nombre')
103                ),
104                'template' => array (
105                    'title' => Text::_('Título'),
106                    'text' => Text::_('Contenido')
107                ),
108                'glossary' => array (
109                    'title' => Text::_('Título'),
110                    'text' => Text::_('Contenido'),
111                    'legend' => Text::_('Leyenda media')
112                ),
113                'info' => array (
114                    'title' => Text::_('Título'),
115                    'text' => Text::_('Contenido'),
116                    'legend' => Text::_('Leyenda media')
117                )
118            );
119        }
120
121        public static function _types() {
122            return array(
123                'description' => Text::_('Descripción'),
124                'url'         => Text::_('Enlace'),
125                'name'        => Text::_('Nombre'),
126                'text'        => Text::_('Texto extenso'),
127                'legend'      => Text::_('Leyenda'),
128                'title'       => Text::_('Título')
129            );
130        }
131
132        /*
133         * Para sacar un registro
134         */
135        static public function get ($table, $id, $lang = 'original') {
136
137            $fields = static::_fields();
138
139            // buscamos el contenido para este registro de esta tabla
140			$sql = "SELECT  
141                        {$table}.id as id,
142                        ";
143
144            foreach ($fields[$table] as $field=>$fieldName) {
145                $sql .= "IFNULL({$table}_lang.$field, {$table}.$field) as $field,
146                         {$table}.$field as original_$field,
147                        ";
148            }
149
150            $sql .= "IFNULL({$table}_lang.lang, '$lang') as lang
151                     FROM {$table}
152                     LEFT JOIN {$table}_lang
153                        ON {$table}_lang.id = {$table}.id
154                        AND {$table}_lang.lang = :lang
155                     WHERE {$table}.id = :id
156                ";
157
158			$query = Model::query($sql, array(
159                                            ':id' => $id,
160                                            ':lang' => $lang
161                                        )
162                                    );
163			$content = $query->fetchObject(__CLASS__);
164            $content->table = $table;
165            
166            return $content;
167		}
168
169		/*
170		 *  Metodo para la lista de registros de las tablas de contenidos
171		 */
172		public static function getAll($filters = array(), $lang = 'original') {
173
174            $tables = static::_tables();
175            $fields = static::_fields();
176
177            $contents = array(
178                'ready' => array(),
179                'pending' => array()
180            );
181
182            /// filters:  type  //tipo de campo
183            //          , table //tabla o modelo o concepto
184            //          , text //cadena de texto
185
186            // si hay filtro de tabla solo sacamos de una tabla
187
188            // si hay filtro de tipo, solo las tablas que tengan ese tipo y solo ese tipo en los resultados
189
190            // si hay filtro de texto es para todas las sentencias
191
192            // y todos los campos sacan el contenido "purpose" si no tienen del suyo
193
194            try {
195
196                \asort($tables);
197                
198                foreach ($tables as $table=>$tableName) {
199                    if (!self::checkLangTable($table)) continue;
200                    if (!empty($filters['type']) && !isset($fields[$table][$filters['type']])) continue;
201                    if (!empty($filters['table']) && $table != $filters['table']) continue;
202
203                    $sql = "";
204                    $primercampo = "";
205                    $values = array();
206
207                    $sql .= "SELECT
208                                {$table}.id as id,
209                                ";
210
211                    foreach ($fields[$table] as $field=>$fieldName) {
212                        $sql .= "IFNULL({$table}_lang.$field, {$table}.$field) as $field,
213                                IF({$table}_lang.$field IS NULL, 0, 1) as {$field}ready,
214                                ";
215                        $primercampo = ($primercampo == '') ?: "{$field}ready";
216                    }
217
218                    $sql .= "CONCAT('{$table}') as `table`
219                            ";
220
221                    $sql .= "FROM {$table}
222                             LEFT JOIN {$table}_lang
223                                ON {$table}_lang.id = {$table}.id
224                                AND {$table}_lang.lang = '$lang'
225                             WHERE {$table}.id IS NOT NULL
226                        ";
227
228                        // solo entradas de goteo en esta gestión
229                        if ($table == 'post') {
230                            $sql .= "AND post.blog = 1
231                                ";
232                        }
233                        if ($table == 'info') {
234                            $sql .= "AND info.node = '".\GOTEO_NODE."'
235                                ";
236                        }
237
238                    // para cada campo
239                        $and = "AND";
240                    if (!empty($filters['text'])) {
241                        foreach ($fields[$table] as $field=>$fieldName) {
242                            $sql .= " $and ( {$table}_lang.{$field} LIKE :text{$field} OR ({$table}_lang.{$field} IS NULL AND {$table}.{$field} LIKE :text{$field} ))
243                                ";
244                            $values[":text{$field}"] = "%{$filters['text']}%";
245                            $and = "OR";
246                        }
247                    }
248
249                    // ojo originales vacios
250                    foreach ($fields[$table] as $field=>$fieldName) {
251                        $sql .= " AND {$table}.{$field} IS NOT NULL
252                            ";
253                    }
254
255                    // pendientes de traducir
256                    if (!empty($filters['pending'])) {
257                        $sql .= " HAVING $primercampo = 0";
258                    }
259
260                    $sql .= " ORDER BY id ASC";
261
262                    /*
263                    echo $sql . '<br /><br />';
264                    var_dump($values);
265                    echo '<br /><br />';
266                     *
267                     */
268                    
269                    $query = Model::query($sql, $values);
270                    foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $content) {
271
272                        foreach ($fields[$table] as $field=>$fieldName) {
273                            if (!empty($filters['type']) && $field != $filters['type']) continue;
274
275                            $data = array(
276                                'table' => $table,
277                                'tableName' => $tableName,
278                                'id' => $content->id,
279                                'field' => $field,
280                                'fieldName' => $fieldName,
281                                'value' => $content->$field
282                            );
283
284                            $campoready = $field . 'ready';
285
286                            $group = $content->$campoready == 1 ? 'ready' : 'pending';
287
288                            $contents[$group][] = (object) $data;
289
290                        }
291
292                    }
293
294                }
295
296                return $contents;
297            } catch (\PDOException $e) {
298                throw new Exception('FATAL ERROR SQL: ' . $e->getMessage() . "<br />$sql<br /><pre>" . print_r($values, 1) . "</pre>");
299            }
300		}
301
302        public function validate(&$errors = array()) {
303            return true;
304        }
305
306		/*
307		 *  Esto se usa para actualizar datos en cualquier tabla de contenido
308		 */
309		public static function save($data, &$errors = array()) {
310
311            $fields = static::_fields();
312
313            if (empty($data)) {
314                $errors[] = "Sin datos";
315                return false;
316            }
317            if (empty($data['lang']) || $data['lang'] == 'original') {
318                $errors[] = "No se peude traducir el contenido original, seleccionar un idioma para traducir";
319                return false;
320            }
321
322  			try {
323                // tenemos el id en $this->id  (el campo id siempre se llama id)
324                // tenemos el lang en $this->lang
325                // tenemos el nombre de la tabla en $this->table
326                // tenemos los campos en $fields[$table] y el contenido de cada uno en $this->$field
327
328                $set = '`id` = :id, `lang` = :lang ';
329                $values = array(
330                    ':id' => $data['id'],
331                    ':lang' => $data['lang']
332                );
333
334                foreach ($fields[$data['table']] as $field=>$fieldDesc) {
335                    if ($set != '') $set .= ", ";
336                    $set .= "`$field` = :$field ";
337                    $values[":$field"] = $data[$field];
338                }
339
340				$sql = "REPLACE INTO {$data['table']}_lang SET $set";
341				if (Model::query($sql, $values)) {
342                    return true;
343                } else {
344                    $errors[] = "Ha fallado $sql con <pre>" . print_r($values, 1) . "</pre>";
345                    return false;
346                }
347                
348			} catch(\PDOException $e) {
349                $errors[] = 'Error sql al grabar el contenido multiidioma. ' . $e->getMessage();
350                return false;
351			}
352
353		}
354
355
356        public static function checkLangTable($table) {
357            //assume yes
358            return true;
359        }
360
361	}
362}