PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 0ms 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
Possible License(s): AGPL-1.0
  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. namespace Goteo\Library {
  21. use Goteo\Core\Model,
  22. Goteo\Core\Exception;
  23. /*
  24. * Clase para gestionar la traducción de registros de tablas de contenido
  25. *
  26. * Ojo, todos los campos de traduccion son texto (a ver como sabemos si corto o largo...)
  27. *
  28. */
  29. class Content {
  30. public static function _tables() {
  31. return array(
  32. 'promote' => Text::_('Proyectos destacados'),
  33. 'patron' => Text::_('Proyectos apadrinados'),
  34. 'icon' => Text::_('Tipos de retorno/recompensa'),
  35. 'license' => Text::_('Licencias'),
  36. 'category' => Text::_('Categorías'),
  37. 'news' => Text::_('Noticias'),
  38. 'faq' => Text::_('Faq'),
  39. 'post' => Text::_('Blog'),
  40. 'banner' => Text::_('Banners'),
  41. 'tag' => Text::_('Tags'),
  42. 'criteria' => Text::_('Criterios de evaluación'),
  43. 'worthcracy'=> Text::_('Meritocrácia'),
  44. 'template' => Text::_('Plantillas emails automáticos'),
  45. 'glossary' => Text::_('Glosario de términos'),
  46. 'info' => Text::_('Ideas de about')
  47. );
  48. }
  49. public static function _fields() {
  50. return array(
  51. 'banner' => array (
  52. 'title' => Text::_('Título'),
  53. 'description' => Text::_('Descripción')
  54. ),
  55. 'promote' => array (
  56. 'title' => Text::_('Título'),
  57. 'description' => Text::_('Descripción')
  58. ),
  59. 'patron' => array (
  60. 'title' => Text::_('Título'),
  61. 'description' => Text::_('Descripción')
  62. ),
  63. 'icon' => array (
  64. 'name' => Text::_('Nombre'),
  65. 'description' => Text::_('Descripción')
  66. ),
  67. 'license' => array (
  68. 'name' => Text::_('Nombre'),
  69. 'description' => Text::_('Descripción'),
  70. 'url' => 'Enlace'
  71. ),
  72. 'category' => array (
  73. 'name' => Text::_('Nombre'),
  74. 'description' => Text::_('Descripción')
  75. ),
  76. 'news' => array (
  77. 'title' => Text::_('Título'),
  78. 'description' => Text::_('Entradilla')
  79. ),
  80. 'faq' => array (
  81. 'title' => Text::_('Título'),
  82. 'description' => Text::_('Descripción')
  83. ),
  84. 'post' => array (
  85. 'title' => Text::_('Título'),
  86. 'text' => Text::_('Texto entrada'),
  87. 'legend' => Text::_('Leyenda media')
  88. ),
  89. 'tag' => array (
  90. 'name' => Text::_('Nombre')
  91. ),
  92. 'criteria' => array (
  93. 'title' => Text::_('Título')
  94. ),
  95. 'worthcracy' => array (
  96. 'name' => Text::_('Nombre')
  97. ),
  98. 'template' => array (
  99. 'title' => Text::_('Título'),
  100. 'text' => Text::_('Contenido')
  101. ),
  102. 'glossary' => array (
  103. 'title' => Text::_('Título'),
  104. 'text' => Text::_('Contenido'),
  105. 'legend' => Text::_('Leyenda media')
  106. ),
  107. 'info' => array (
  108. 'title' => Text::_('Título'),
  109. 'text' => Text::_('Contenido'),
  110. 'legend' => Text::_('Leyenda media')
  111. )
  112. );
  113. }
  114. public static function _types() {
  115. return array(
  116. 'description' => Text::_('Descripción'),
  117. 'url' => Text::_('Enlace'),
  118. 'name' => Text::_('Nombre'),
  119. 'text' => Text::_('Texto extenso'),
  120. 'legend' => Text::_('Leyenda'),
  121. 'title' => Text::_('Título')
  122. );
  123. }
  124. /*
  125. * Para sacar un registro
  126. */
  127. static public function get ($table, $id, $lang = 'original') {
  128. $fields = static::_fields();
  129. // buscamos el contenido para este registro de esta tabla
  130. $sql = "SELECT
  131. {$table}.id as id,
  132. ";
  133. foreach ($fields[$table] as $field=>$fieldName) {
  134. $sql .= "IFNULL({$table}_lang.$field, {$table}.$field) as $field,
  135. {$table}.$field as original_$field,
  136. ";
  137. }
  138. $sql .= "IFNULL({$table}_lang.lang, '$lang') as lang
  139. FROM {$table}
  140. LEFT JOIN {$table}_lang
  141. ON {$table}_lang.id = {$table}.id
  142. AND {$table}_lang.lang = :lang
  143. WHERE {$table}.id = :id
  144. ";
  145. $query = Model::query($sql, array(
  146. ':id' => $id,
  147. ':lang' => $lang
  148. )
  149. );
  150. $content = $query->fetchObject(__CLASS__);
  151. $content->table = $table;
  152. return $content;
  153. }
  154. /*
  155. * Metodo para la lista de registros de las tablas de contenidos
  156. */
  157. public static function getAll($filters = array(), $lang = 'original') {
  158. $tables = static::_tables();
  159. $fields = static::_fields();
  160. $contents = array(
  161. 'ready' => array(),
  162. 'pending' => array()
  163. );
  164. /// filters: type //tipo de campo
  165. // , table //tabla o modelo o concepto
  166. // , text //cadena de texto
  167. // si hay filtro de tabla solo sacamos de una tabla
  168. // si hay filtro de tipo, solo las tablas que tengan ese tipo y solo ese tipo en los resultados
  169. // si hay filtro de texto es para todas las sentencias
  170. // y todos los campos sacan el contenido "purpose" si no tienen del suyo
  171. try {
  172. \asort($tables);
  173. foreach ($tables as $table=>$tableName) {
  174. if (!self::checkLangTable($table)) continue;
  175. if (!empty($filters['type']) && !isset($fields[$table][$filters['type']])) continue;
  176. if (!empty($filters['table']) && $table != $filters['table']) continue;
  177. $sql = "";
  178. $primercampo = "";
  179. $values = array();
  180. $sql .= "SELECT
  181. {$table}.id as id,
  182. ";
  183. foreach ($fields[$table] as $field=>$fieldName) {
  184. $sql .= "IFNULL({$table}_lang.$field, {$table}.$field) as $field,
  185. IF({$table}_lang.$field IS NULL, 0, 1) as {$field}ready,
  186. ";
  187. $primercampo = ($primercampo == '') ?: "{$field}ready";
  188. }
  189. $sql .= "CONCAT('{$table}') as `table`
  190. ";
  191. $sql .= "FROM {$table}
  192. LEFT JOIN {$table}_lang
  193. ON {$table}_lang.id = {$table}.id
  194. AND {$table}_lang.lang = '$lang'
  195. WHERE {$table}.id IS NOT NULL
  196. ";
  197. // solo entradas de goteo en esta gestión
  198. if ($table == 'post') {
  199. $sql .= "AND post.blog = 1
  200. ";
  201. }
  202. if ($table == 'info') {
  203. $sql .= "AND info.node = '".\GOTEO_NODE."'
  204. ";
  205. }
  206. // para cada campo
  207. $and = "AND";
  208. if (!empty($filters['text'])) {
  209. foreach ($fields[$table] as $field=>$fieldName) {
  210. $sql .= " $and ( {$table}_lang.{$field} LIKE :text{$field} OR ({$table}_lang.{$field} IS NULL AND {$table}.{$field} LIKE :text{$field} ))
  211. ";
  212. $values[":text{$field}"] = "%{$filters['text']}%";
  213. $and = "OR";
  214. }
  215. }
  216. // ojo originales vacios
  217. foreach ($fields[$table] as $field=>$fieldName) {
  218. $sql .= " AND {$table}.{$field} IS NOT NULL
  219. ";
  220. }
  221. // pendientes de traducir
  222. if (!empty($filters['pending'])) {
  223. $sql .= " HAVING $primercampo = 0";
  224. }
  225. $sql .= " ORDER BY id ASC";
  226. /*
  227. echo $sql . '<br /><br />';
  228. var_dump($values);
  229. echo '<br /><br />';
  230. *
  231. */
  232. $query = Model::query($sql, $values);
  233. foreach ($query->fetchAll(\PDO::FETCH_CLASS, __CLASS__) as $content) {
  234. foreach ($fields[$table] as $field=>$fieldName) {
  235. if (!empty($filters['type']) && $field != $filters['type']) continue;
  236. $data = array(
  237. 'table' => $table,
  238. 'tableName' => $tableName,
  239. 'id' => $content->id,
  240. 'field' => $field,
  241. 'fieldName' => $fieldName,
  242. 'value' => $content->$field
  243. );
  244. $campoready = $field . 'ready';
  245. $group = $content->$campoready == 1 ? 'ready' : 'pending';
  246. $contents[$group][] = (object) $data;
  247. }
  248. }
  249. }
  250. return $contents;
  251. } catch (\PDOException $e) {
  252. throw new Exception('FATAL ERROR SQL: ' . $e->getMessage() . "<br />$sql<br /><pre>" . print_r($values, 1) . "</pre>");
  253. }
  254. }
  255. public function validate(&$errors = array()) {
  256. return true;
  257. }
  258. /*
  259. * Esto se usa para actualizar datos en cualquier tabla de contenido
  260. */
  261. public static function save($data, &$errors = array()) {
  262. $fields = static::_fields();
  263. if (empty($data)) {
  264. $errors[] = "Sin datos";
  265. return false;
  266. }
  267. if (empty($data['lang']) || $data['lang'] == 'original') {
  268. $errors[] = "No se peude traducir el contenido original, seleccionar un idioma para traducir";
  269. return false;
  270. }
  271. try {
  272. // tenemos el id en $this->id (el campo id siempre se llama id)
  273. // tenemos el lang en $this->lang
  274. // tenemos el nombre de la tabla en $this->table
  275. // tenemos los campos en $fields[$table] y el contenido de cada uno en $this->$field
  276. $set = '`id` = :id, `lang` = :lang ';
  277. $values = array(
  278. ':id' => $data['id'],
  279. ':lang' => $data['lang']
  280. );
  281. foreach ($fields[$data['table']] as $field=>$fieldDesc) {
  282. if ($set != '') $set .= ", ";
  283. $set .= "`$field` = :$field ";
  284. $values[":$field"] = $data[$field];
  285. }
  286. $sql = "REPLACE INTO {$data['table']}_lang SET $set";
  287. if (Model::query($sql, $values)) {
  288. return true;
  289. } else {
  290. $errors[] = "Ha fallado $sql con <pre>" . print_r($values, 1) . "</pre>";
  291. return false;
  292. }
  293. } catch(\PDOException $e) {
  294. $errors[] = 'Error sql al grabar el contenido multiidioma. ' . $e->getMessage();
  295. return false;
  296. }
  297. }
  298. public static function checkLangTable($table) {
  299. //assume yes
  300. return true;
  301. }
  302. }
  303. }