require_once("ecTpl.php");
// 2010-08-26 Hay algunas plantillas del contento nuevo y/o viejo que manejan grabar en vez de aceptar
if ( $_REQUEST["grabar"] || $_REQUEST["grabar_x"] || $_REQUEST["grabar_y"] )
{
if ( !isset( $_REQUEST["grabar"] ) )
$_REQUEST["grabar"] = $_REQUEST["grabar_x"];
$_REQUEST["aceptar"] = $_REQUEST["grabar"];
$_POST["aceptar"] = $_REQUEST["grabar"];
$_GET["aceptar"] = $_REQUEST["grabar"];
}
/**
* ecInputWidget
* Classes for input object management.
* @package ecAPI
*/
/**
* class ecInputWidget
* Container class for Input Widgets.
*/
class contentoComponent {
/**
* @var string $name Object's name
*/
var $name;
/**
* @var string $type
* Type of input widget. The actual class will be loaded from
* ecInputWidget/$type.php
* on start-up.
*/
var $type;
var $db;
var $id;
var $cachePath;
var $cacheable;
var $templatePath;
var $template;
var $data;
var $adminMode;
var $url;
var $headerScripts;
var $footerScripts;
var $disabledBinding = false;
/**
* ecInputWidget Constructor Method.
* @param object $fieldinfo An ecTableField object.
* @param object $db An ecAPP object (Config+DB).
* @param string $name This widget's name.
* @param string $table This widget's source table within the model.
* @param mixed $default initial default value stored (optional)
*/
var $tpl;
/* Documentación del componente */
var $description = "";
var $priority = 0;
function init(){
global $app;
global $globalParams;
$descripciones = array(
"template" => array(6, 'Plantilla HTML, para incrustar otros componentes y crear containers.'),
"HTML" => array(5, 'Permite ingresar un texto formateado (HTML)'),
"contenido" => array(5, 'Despliega uno o varios contenidos desde un nodo de taxonomía.'),
"detalle_contenido" => array(5, 'Muestra un contenido en particular desde la tabla de contenidos.'),
"buscar" => array(4, 'Implementa un buscador de contenidos dentro del sitio. Este componente genera la página de resultados de búsqueda.'),
"menu" => array(4, 'Muestra un menú basado en la estructura de páginas.'),
"menu_taxonomia" => array(4, 'Muestra un menú basado en la taxonomía de contenidos.'),
"galeria" => array(4, 'Galería de imágenes generalizada.'),
"image" => array(4, 'Permite incluír una imagen, opcionalmente con un enlace y/o eventos onclick.'),
"contacto" => array(4, 'Implementa un formulario de contacto.'),
"passwordReminder" => array(4, 'Permite recuperar la contraseña de un usuario, enviándola por correo.'),
"banner" => array(4, 'Especifica la ubicación de un banner administrable. Requiere las tablas BANNER, FORMATO_BANNER y AVISADOR_BANNER.'),
"redirectToFirstChild" => array(4, 'Redirige a la primera página hija dentro del árbol de páginas.'),
"xmlSitemap" => array(4, 'Genera un sitemap.xml para Google.'),
"ddlForm" => array(3, 'Permite el ingreso de datos a una tabla de la base de datos.'),
"multiRecordView" => array(3, 'Muestra una lista de registros de una tabla de datos.'),
"recordView" => array(3, 'Muestra un registro desde una tabla de datos.'),
"arbol_desplegable" => array(2, 'Despliega registros en forma de árbol.'),
"authenticateByRol" => array(2, 'Permite autenticar en contra de varias tablas de usuario, según un rol seleccionado. Se enlaza a otros componentes usando el tipo de enlace AUTH.'),
"authenticate" => array(2, 'Permite autenticar usuarios. Se enlaza a otros componentes usando el tipo de enlace AUTH.'),
"boton" => array(2, 'Genera un enlace como un botón con dos imágenes (normal y hover)'),
"calendario" => array(2, 'Implementa un calendario de eventos.'),
"calRanged" => array(2, 'Implementa un calendario de eventos que cubren un periodo de tiempo.'),
"clima" => array(2, 'Obtiene el pronóstico del tiempo para una ciudad de Chile.'),
"componentByRol" => array(2, 'Muestra un componente condicionalmente según el rol del usuario autenticado.'),
"evangelio" => array(2, 'Muestra el evangelio del día (http://www.evangeliodeldia.org/)'),
"fbILike" => array(2, 'Implementa el botón "Me gusta" de Facebook.'),
"htmlTab" => array(2, 'Permite incluír varios componentes dentro de una vista tabulada. Los componentes se enlazan a éste usando el tipo de enlace TAB.'),
"indicadores" => array(2, 'Muestra uno o varios indicadores económicos.'),
"linkTree" => array(2, 'Muestra un menú de enlaces en forma de árbol.'),
"loginBox" => array(2, 'Si el usuario está autenticado, muestra una pantalla de bienvenida. Si no, muestra una pantalla de login'),
"multiFileView" => array(2, 'Muestra una lista administrable de archivos descargables.'),
"redirect" => array(2, 'Redirige a otra página.'),
"rss" => array(2, 'Permite compartir contenido vía RSS.'),
"showDate" => array(2, 'Muestra la fecha de hoy.'),
"tagCloud" => array(2, 'Muestra datos desde una tabla como una nube de tags.'),
"TEXT" => array(2, 'Permite ingresar un texto plano.'),
"TEXTPaginate" => array(2, 'Permite ingresar un texto formateado (HTML) paginable.'),
"tracking" => array(2, 'Permite registrar visitas en una tabla llamada TRACKING.'),
"twTweets" => array(2, 'Muestra los últimos tweets de un usuario'),
"vista_diaria" => array(2, 'Ordena una lista de registros según un campo de fecha, mostrando los que corresponden a un día.'),
"vista_semanal" => array(2, 'Ordena una lista de registros según un campo de fecha, mostrando los que corresponden a una semana.'),
"ajaxGrid" => array(1, 'Muestra una grilla editable de datos (por ahora sólo para ADN)'),
"clickCounter" => array(1, 'Contador de clicks para el nuevo sistema de banners'),
"dataSheet" => array(1, 'T.B.A.'),
"disponibilidad" => array(1, 'Calendario de disponibilidad por rango de fecha y hora. Soporta múltiples tablas de datos.'),
"emailPage" => array(1, 'Envía una página de Contento por correo electrónico.'),
"facebookLogin" => array(1, 'Implementa login de Facebook, creando usuarios en la tabla PERSONA.'),
"filteredView" => array(1, 'Vista de registros con columnas filtrables.'),
"googlemap" => array(1, 'Agrega un mapa de Google a la página.'),
"jsonQuery" => array(1, 'Realiza una consulta de datos y devuelve los datos en formato JSON.'),
"jsonWrapper" => array(1, 'Convierte los datos cualquier componente a formato JSON.'),
"mapa_completo" => array(1, 'Mapa completo de las páginas de un sitio, en formato de árbol.'),
"pageFlip" => array(1, 'Genera un pageFlip a partir de las páginas de un archivo PDF.'),
"printPage" => array(1, 'Permite imprimir una página cualquiera de Contento.'),
"stripWraps" => array(1, 'Toma una página de Contento y la devuelve sin su container.'),
"treeMultiRecordView" => array(1, 'Implementa un árbol recursivo sobre una tabla, opcionalmente mostrando datos desde otra tabla asociados a un nodo del árbol.'),
"wkhtmltopdf" => array(1, 'Convierte los resultados de un componente a PDF.'),
);
if(!$this->description) {
$this->description = $descripciones[get_class($this)][1];
}
if(!$this->priority) {
$this->priority = $descripciones[get_class($this)][0];
}
$this->configurations=$configurations;
$this->id = $this->name;
$this->cacheable=0;
$this->cachePath = $app->settings["ecAPI"]["INSTALL_ROOT"] . "/classes/cache";
$this->templatePath = $app->settings["ecAPI"]["INSTALL_ROOT"] . "/classes/templates";
$this->data = "";
$this->bindings=array();
$this->contents=array();
// pasar este objeto al componente.. asi se tiene acceso a datos del sistema que pueden ser necesarios
$this->tplData=new ecTpl();
$this->tplData->systemURI = $globalParams[0];
$this->tplData->sysBaseURL = $app->settings["Contento"]["COMPONENT_BASE_URL"];
$this->tpl = new ecTpl();
if (!isset($this->template))
$this->template = $this->name . ".html";
// print "inicializando " . $this->name . "
";
// print "template: ". $this->template."
";
}
function setParent(&$parent) {
$this->parent = $parent;
}
//seguramente ahorrara lineas de codigo ?
function prepareTemplate($tpl) {
if($opt) {
return new HTML_Template_Flexy($opt);
}
if(!$tpl) {
return "prepareTemplate called without a template";
}
$opt = array(
'templateDir' => $this->templatePath,
'compileDir' => $this->cachePath
);
$t = new HTML_Template_Flexy($opt);
$t->compile($tpl);
return $t;
}
function getConfigurationParameters(){
return array();
}
/* Opcional, isomorfo a getConfigurationParameters,
* determina si es necesario ingresar los parametros de
* manera especial */
function getConfigurationWidgets(){
return array();
}
/*
Entrega informacion acerca de los parametros de configuracion
*/
function getConfigurationHelp(){
return array();
}
function contentoComponent($configurations=array())
{
$this->init;
}
function getScriptletList()
{
$scriptlets = array(
"ajaxGrid" => array("afterLoadingData", "afterSavingData", "beforeLoadingData", "beforeSavingData", "preProcess"),
"arbol_desplegable" => array("postProcess", "preProcess"),
"authenticate" => array("postProcess", "preProcess"),
"buscar" => array("postProcess", "preProcess"),
"calendario" => array("postProcess", "preProcess"),
"calRanged" => array("postProcess", "preProcess"),
"clima" => array("postProcess", "preProcess"),
"contacto" => array("afterSending", "beforeSending", "postProcess", "preProcess"),
"contenido" => array("postProcess", "preProcess"),
"dataSheet" => array("postProcess", "preProcess"),
"ddlForm" => array("postProcess", "preProcess"),
"detalle_contenido" => array("postProcess", "preProcess"),
"disponibilidad" => array("postProcess", "preProcess"),
"filteredView" => array("postProcess", "preProcess"),
"galeria" => array("postProcess", "preProcess"),
"HTML" => array("preProcess"),
"image" => array("postProcess"),
"indicadores" => array("postProcess"),
"jsonQuery" => array("postProcess", "preProcess"),
"linkTree" => array("postProcess", "preProcess"),
"loginBox" => array("postProcess", "preProcess"),
"mapa_completo" => array("postProcess", "preProcess"),
"menu" => array("postProcess", "preProcess"),
"menu_taxonomia" => array("postProcess", "preProcess"),
"multiFileView" => array("postProcess", "preProcess"),
"multiRecordView" => array("postProcess", "preProcess"),
"pageFlip" => array("postProcess", "preProcess"),
"passwordReminder" => array("postProcess", "preProcess"),
"recordView" => array("postProcess", "preProcess"),
"rss" => array("postProcess", "preProcess"),
"stripWraps" => array("postProcess", "preProcess"),
"tagCloud" => array("postProcess", "preProcess"),
"template" => array("postProcess", "preProcess"),
"treeMultiRecordView" => array("postProcess", "preProcess"),
"vista_diaria" => array("postProcess", "preProcess"),
"vista_semanal" => array("postProcess", "preProcess"),
"xmlSitemap" => array("postProcess", "preProcess")
);
$sc = $scriptlets[get_class($this)];
if(!$sc) {
$sc = array();
}
return $sc;
}
function getTemplateTagList()
{
$taglist = array();
$taglist['ajaxGrid']['componentName'] = 'Nombre de la instancia';
$taglist['ajaxGrid']['fields'] = 'Lista de Campos';
$taglist['ajaxGrid']['{$k1."_".$k}'] = 'globalParams';
$taglist['ajaxGrid']['{"SESSION_".$k}'] = 'Variables de Sesión';
$taglist['ajaxGrid']['{"rol_" . $rol }'] = 'Rol';
$taglist['ajaxGrid']['ADMINBUTTONS'] = 'Botones de Administración';
$taglist['ajaxGrid']['AJAXGRID_JS'] = 'Javascript necesario para la Operación';
$taglist['ajaxGrid']['items'] = 'Plantilla para tabla dinámica';
$taglist['arbol_desplegable']['items'] = 'Lista plana de elementos, generada con linealizar()';
$taglist['arbol_desplegable']['cols'] = 'Columnas de la tabla usada para armar el árbol gráficamente';
$taglist['arbol_desplegable']['rwidth'] = 'Espacio disponible para mostrar los datos';
$taglist['buscar']['optItemsPerPage'] = 'Opciones de items por página para el paginador estándar';
$taglist['buscar']['itemsperpage'] = 'Items por página';
$taglist['buscar']['name'] = 'Nombre de la instancia';
$taglist['buscar']['paginaactual'] = 'Página actual';
$taglist['buscar']['{$k}'] = 'getPageNavigation';
$taglist['buscar']['firstPage'] = 'Nº de primera página';
$taglist['buscar']['firstPageLink'] = 'Link a primera página';
$taglist['buscar']['prevPage'] = 'Nº de página anterior';
$taglist['buscar']['prevPageLink'] = 'Link a página anterior';
$taglist['buscar']['nextPage'] = 'Nº de página siguiente';
$taglist['buscar']['nextPageLink'] = 'Link a página siguiente';
$taglist['buscar']['lastPage'] = 'Nº de página final';
$taglist['buscar']['lastPageLink'] = 'Link a página final';
$taglist['buscar']['pages'] = 'Lista completa de páginas';
$taglist['buscar']['totalPages'] = 'Cantidad total de páginas';
$taglist['buscar']['pagewindowmoreleft'] = 'Aparece si hay más páginas anteriores a las en la ventana';
$taglist['buscar']['pagewindowmoreright'] = 'Aparece si hay más páginas siguientes a las en la ventana';
$taglist['buscar']['pagewindow'] = 'Ventana de páginas alrededor de la actual';
$taglist['buscar']['pagewindowfixed'] = '?';
$taglist['buscar']['items'] = 'Resultados de búsqueda';
$taglist['buscar']['busqueda'] = 'Parámetros de búsqueda';
$taglist['calendario']['mes["month"]'] = 'Nombre del mes seleccionado';
$taglist['calendario']['mes["mes"]'] = 'Número del mes seleccionado';
$taglist['calendario']['mes["year"]'] = 'Año seleccionado';
$taglist['calendario']['{"rol_" . $rol }'] = 'Rol';
$taglist['calendario']['semanas'] = 'Lista de semanas $data->semanas[$numsem][$diasem]: c, eshoy, events, evento (si tiene), weekend_evento, weekend, week, clase, nada';
$taglist['calendario']['nombre_calendario'] = 'Nombre configurado del calendario';
$taglist['calendario']['meses'] = 'Seis meses hacia adelante';
$taglist['calendario']['mes_actual'] = 'Mes actual';
$taglist['calendario']['selected'] = 'Fecha actual (getDate)';
$taglist['calendario']['prev_month'] = 'Mes anterior';
$taglist['calendario']['next_month'] = 'Mes siguiente';
$taglist['calendario']['calendar_name'] = 'Nombre de la instancia';
$taglist['calendario']['pre_link'] = 'Prefijo para el enlace (incluye parámetros de la página)';
$taglist['calRanged']['semana_individual'] = 'Días de la semana referente a la fecha general';
$taglist['calRanged']['prev_week'] = 'Semana anterior';
$taglist['calRanged']['next_week'] = 'Semana siguiente';
$taglist['clima']['climaobj'] = 'Objeto con información de clima (desde indicadores.ecweb.cl/clima)';
$taglist['clima']['clima'] = 'Clima para la ciudad seleccionada';
$taglist['contacto']['configs'] = 'Configuraciones del componente';
$taglist['contacto']['enviado'] = 'Si fue enviado el correo';
$taglist['contacto']['messages'] = 'Errores';
$taglist['contacto']['id'] = 'ID del componente';
$taglist['contacto']['fields'] = 'Campos configurados';
$taglist['contenido']['URL'] = 'URL de la página (según contento)';
$taglist['contenido']['items'] = 'Lista de contenidos (destacado, destacado_principal, NUMBER)';
$taglist['contenido']['urlDetalle'] = 'URL de la página de detalle configurada';
$taglist['contenido']['name'] = 'Nombre de la instancia';
$taglist['contenido']['{$inst."_".$k}'] = 'globalParams';
$taglist['contenido']['THISNODE'] = 'ID de nodo de Taxonomía seleccionado';
$taglist['contenido']['disabledBinding'] = 'Si el componente está apagado para la página actual';
$taglist['dataSheet']['total'] = 'Total de registros';
$taglist['dataSheet']['tiene_paginacion'] = 'Si tiene paginación';
$taglist['dataSheet']['numPageLink'] = 'Enlaces a páginas';
$taglist['dataSheet']['numPage'] = 'Números de páginas';
$taglist['dataSheet']['firstPrev'] = 'Si tiene página primera y anterior';
$taglist['dataSheet']['prevNext'] = 'Si tiene página anterior y siguiente';
$taglist['dataSheet']['nextLast'] = 'Si tiene página siguiente y última';
$taglist['dataSheet']['currPage'] = 'Página actual';
$taglist['dataSheet']['totalPages'] = 'Total de páginas';
$taglist['dataSheet']['allPages'] = 'Todas las páginas';
$taglist['dataSheet']['hasPagination'] = 'Tiene paginación';
$taglist['dataSheet']['menu'] = 'Menú generado con lo items (label, active)';
$taglist['dataSheet']['items'] = 'Items (rows, active)';
$taglist['ddlForm']['EXTRAVARS'] = 'Variables ocultas adicionales';
$taglist['ddlForm']['isUpdate'] = 'Si es una actualización';
$taglist['ddlForm']['messages'] = 'Mensajes de error';
$taglist['ddlForm']['GOBACK'] = 'Botón volver';
$taglist['detalle_contenido']['{$k}'] = 'Datos del contenido';
$taglist['detalle_contenido']['{$inst."_".$k}'] = 'globalParams';
$taglist['detalle_contenido']['THISNODE'] = 'Nodo actual por defecto';
$taglist['detalle_contenido']['campos'] = 'Lista de campos obtenidos';
$taglist['multiRecordView']['{$k1."_".$k}'] = 'globalParams';
$taglist['multiRecordView']['items'] = 'Lista de items obtenidos. Si se especifica el parámetro columns, será una matriz.';
$taglist['pageFlip']['xmlFileJS'] = 'Vínculo a archivo XML para Javascript';
$taglist['pageFlip']['*'] = 'Datos del registro';
$taglist['passwordReminder']['form'] = '1 si debe mostrar el formulario, 0 al procesar';
$taglist['passwordReminder']['listo'] = '1 si fue enviado correctamente';
$taglist['passwordReminder']['error'] = 'Mensaje de error';
$taglist['recordView']['*'] = 'Datos del registro';
$taglist['rss']['configurations'] = 'Configuraciones del componente';
$taglist['rss']['global_title'] = 'Título global';
$taglist['rss']['global_link'] = 'Enlace global a sitio';
$taglist['rss']['global_description'] = 'Descripción global';
$taglist['rss']['selfLink'] = 'Enlace a sí mismo';
$taglist['rss']['items[]'] = 'Ítems del RSS';
$taglist['rss']['{$k}'] = 'Reemplazos configurados';
$taglist['rss']['{$inst."_".$k}'] = 'globalParams';
$taglist['template']['*'] = 'Reemplazos configurados';
$taglist['template']['{"SESSION_".$k}'] = 'Variables de Sesión';
$taglist['template']['{"rol_" . $rol }'] = 'Rol';
$taglist['template']['{$k}'] = 'Configuración';
$taglist['template']['{$inst."_".$k}'] = 'globalParams';
$taglist['template']['ADMINBUTTONS'] = 'Botones de administración';
$taglist['template']['disabledBinding'] = 'Si el componente está apagado para la página actual';
$taglist['stripWraps']['CONTENT'] = 'Contenido de la página obtenida';
$sc = $taglist[get_class($this)];
if(!$sc) {
$sc = array();
}
return $sc;
}
function getScriptlet($id)
{
global $app;
$filename = $app->settings["Contento"]["SCRIPTLET_DIR"] . "/$id/" . $this->name . ".php";
if(file_exists($filename)) {
return $filename;
}
$filename = $app->settings["Contento"]["SCRIPTLET_DIR"] . "/" . $this->name . "/$id.php";
if(file_exists($filename)) {
return $filename;
}
return $app->settings["Contento"]["COMPONENT_DIR"] . "/noop.php";
}
function setConfigFromRecord($id)
{
global $app;
global $adminMode;
// print "CC: seteando config de $id\n
";
if(is_array($id)) {
# Así evitamos algunas de las lecturas innecesarias que plagan Contento
$myRecord = $id;
$id = $myRecord["ID______IST"];
} elseif(is_numeric($id)) {
$myRecord = $app->readRecord("INSTANCE","ID______IST='$id'");
} else {
$myRecord = $app->readRecord("INSTANCE","NAME____IST='" . $app->quotesql($id) . "'");
$id = $myRecord["ID______IST"];
}
$this->id=$myRecord["ID______IST"];
$this->name =$myRecord["NAME____IST"];
// print "leido desde la DB: " . $myRecord["CONFIG__IST"] . "\n
";
$this->setConfigurations(unserialize($myRecord["CONFIG__IST"]));
// print "CC: configuraciones seteadas:" . print_r($this->configurations,1) . "\n
";
$this->setContents(unserialize($myRecord["CONTENT_IST"]));
// print "CC: Contenidos seteadas\n
";
/* Local PDR */
$this->editProfile = $myRecord["CATEGORIIST"];
$qid = $app->initReadLoop("BINDING,INSTANCE","ID______IST = CHILD___BND AND PARENT__BND='".$app->quotesql($id)."'");
while($r = $qid->fetchRow(DB_FETCHMODE_ASSOC)) {
$this->bindings[$r["ID______BND"]] = array("child" => $r["CHILD___BND"], "type" => $r["TYPE____BND"],"data" => $r["DATA____BND"], "class" => $r["CLASS___IST"], "childName" => $r["NAME____IST"]);
}
if(isset($this->contents)) {
$this->adminButtons['contenido'] = true;
}
if($this->configurations['template'] && $adminMode) {
$this->adminButtons['editTemplate'] = true;
}
if($adminMode) {
$this->adminButtons['adminOptions'] = true;
}
// NO. Es necesario controlar los accesos a las opciones de administración
// $this->adminButtons['adminOptions'] = true;
global $bindingExceptions;
if($bindingExceptions) {
foreach($bindingExceptions as $bk => $bv) {
if($bv["CHILD___BND"] == $id) {
$this->adminButtons['componenteInvisible'] = true;
}
}
}
// print "CC: Bindings seteadas: " . print_r($this->bindings,1) . "\n
";
// opciones via url
}
function setConfigurations($configurations)
{
if(!$this->configurations)
$this->configurations = array();
if(!$configurations) return;
$this->configurations = array_merge($this->configurations,$configurations);
// $opts=explode("|",$configurations);
// foreach($opts as $o) {
// list($label,$value)=split("=",$o,2);
// $this->configurations[$label]=$value;
// }
}
function setContents($contents)
{
$this->contents= $contents;
// $opts=explode("|",$contents);
// foreach($opts as $o) {
// list($label,$value)=split("=",$o,2);
// $this->configurations[$label]=$value;
// }
}
function setBindings($bindings)
{
$this->bindings= array_merge($this->bindings,$bindings);
# $this->configurations=array();
// $opts=explode("|",$configurations);
// foreach($opts as $o) {
// list($label,$value)=split("=",$o,2);
// $this->configurations[$label]=$value;
// }
}
function setId($id)
{
$this->id = $id;
}
/**
* This method converts the object into its HTML source code.
* Expect this to be overriden in each derived method.
*
* @param mixed $newval optional default value to be replaced (default $this->curval).
* @return string HTML code.
*
* NOTE: $newval shouldn't replace $this->curval.
*/
function checkCache()
{
return false;
if (!$this->cacheable)
return false;
if (!isset($this->id))
$this->id = $this->name;
$this->cacheFile = $this->cachePath . "/" . $this->id . ".cached";
if (file_exists($this->cacheFile)) {
if (filemtime($this->cacheFile)<(filemtime($this->templatePath . "/" . $this->template))) //si el cache es mas antiguo que el template
return false;
$this->data = unserialize(file_get_contents($this->cacheFile));
return true;
}
else
return false;
}
function saveCache()
{
return;
if (!isset($this->cacheFile)){
if (!isset($this->id))
$this->id = $this->name;
$this->cacheFile = $this->cachePath . "/" . $this->id . ".cached";
}
$fh = fopen($this->cacheFile,"w");
fwrite($fh, serialize($this->data));
fclose($fh);
}
/* Para proceso adicional de $this->tpl */
function build()
{
}
/* Para agregar botonera de administración */
function adminButtons()
{
global $app;
global $editMode;
if(!$editMode) return "";
$tplData = new ecTpl();
$tplData->compo_name = $this->name;
$tplData->compo_name_std = preg_replace('/[^a-z0-9]+/', '_', strtolower($this->name));
$tplData->compo_uri = $this->url;
$tplData->parent_name = $this->parent->name;
if($this->parent)
$tag = $app->readRecord('BINDING',"PARENT__BND = '" . $app->quotesql($this->parent->id) . "' AND CHILD___BND = '" . $app->quotesql($this->id) . "'");
$tplData->tagName = $tag['DATA____BND'];
# if (!$tag['DATA____BND'])
# print "error en componente: " . $tplData->compo_name . " no tiene nombre de binding";
$this->loadPermissions();
$tplData->buttons = $this->adminButtons;
$tplData->NOMBRE = $this->name;
$tplData->CLASS = $this->class;
$opt = array(
'templateDir' => $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"],
'compileDir' => $this->cachePath
);
$tpl = new HTML_Template_Flexy($opt);
$tpl->compile('marcoAdminButtons.html');
return $tpl->bufferedOutputObject($tplData);
}
// motodo que se llama para dibujar el componente
function getHTML($uri=NULL) {
global $app;
global $adminMode;
global $editMode;
global $globalParams;
$app->log("PROF: " . $this->name . ": " . microtime(true), $app->SEVERITY_DEBUG);
if($editMode) {
$tplData = new ecTpl();
/* SI SE ROMPE LA GRÁFICA EN EL ADMINISTRADOR (usualmente en IE), HAY QUE AGREGAR {ADMINBUTTONS:h} EN LA PLANTILLA QUE ESTÁ ROMPIENDO LA GRÁFICA (usualmente el container) */
if($this->templatePath && $this->configurations["template"] && strstr(@file_get_contents($this->templatePath . "/" . $this->configurations["template"]), "{ADMINBUTTONS:h}")) {
$content = $this->__getHTML($uri);
} else {
/* Compatibilidad */
$tplData->compo = $this->__getHTML($uri);
$tplData->compo_name = $this->name;
$tplData->compo_name_std = preg_replace('/[^a-z0-9]+/', '_', strtolower($this->name));
$tplData->compo_uri = $this->url;
$tplData->parent_name = $this->parent->name;
if($this->parent)
$tag = $app->readRecord('BINDING',"PARENT__BND = '" . $app->quotesql($this->parent->id) . "' AND CHILD___BND = '" . $app->quotesql($this->id) . "'");
$tplData->tagName = $tag['DATA____BND'];
$this->loadPermissions();
$tplData->buttons = $this->adminButtons;
$tplData->NOMBRE = $this->name;
$tplData->CLASS = $this->class;
// FIXME
$tplData->urlAdmin = $adminMode ? "/admin/" : "/editor/";
$opt = array(
'templateDir' => $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"],
'compileDir' => $this->cachePath
);
$tpl = new HTML_Template_Flexy($opt);
$tpl->compile('marcoAdmin.html');
$content = $tpl->bufferedOutputObject($tplData);
}
$content = $this->handleWraps($content, $tplData, true);
$content = str_replace("/index.php","/admin/index_admin.php",$content) ;
if($this->disabledBinding) {
$content = "
No se guardó el archivo PHP porque tiene errores
"; } unlink($tmp); } } if(!$errorPHP) { $f = @fopen($path,'w'); if($f) { fwrite($f, rawurldecode($_REQUEST['contenido'])); fclose($f); } } $faltanTags = array(); foreach ( $this->bindings as $id => $binding){ if ($binding["type"] == "REPLACE" && !preg_match('/{' . $binding["data"] . '(:h)?}/', rawurldecode($_REQUEST['contenido']))) { $faltanTags[] = '{' . $binding["data"]. ':h}'; } } if($faltanTags) { $errorPHP .= "Faltan los siguientes tags: " . join(", ", $faltanTags) . "
"; } } if(isset($_REQUEST["setScriptlet"])) { $_REQUEST["scriptlet"] = $_REQUEST["setScriptlet"]; } if(isset($_REQUEST["clearScriptlet"])) { unset($_REQUEST["scriptlet"]); } $tpl = new HTML_Template_Flexy($opt); $tpl->compile('editTemplate.html'); $data = new ecTpl(); $data->scriptlet = $_REQUEST["scriptlet"]; $data->tags = $this->getTemplateTagList(); $tmp = $this->getScriptletList(); $data->scriptlets = array(); foreach($tmp as $sc) { $data->scriptlets[$sc] = ($_REQUEST["scriptlet"] == $sc) ? "style=\"font-weight: bold\"" : ""; } $data->scriptlet_no_class = $_REQUEST["scriptlet"] ? "" : "style=\"font-weight: bold\""; $data->adminBase = preg_replace("!^/([^/]+)/.*$!", "/$1/", $_SERVER["REQUEST_URI"]); $data->warnings = ""; $path = $this->templatePath.'/'.$this->configurations['template']; if($_REQUEST["scriptlet"]) { $tmp = $data->tags; $data->tags = array(); foreach($tmp as $k => $v) { $data->tags['$data->' . $k ] = $v; } $path = $app->settings["Contento"]["SCRIPTLET_DIR"] . "/" . $_REQUEST["scriptlet"] . "/" . $this->name . ".php"; } else { $tmp = $data->tags; $data->tags = array(); foreach($tmp as $k => $v) { $data->tags['{' . $k . '}'] = $v; } foreach ( $this->bindings as $id => $binding){ if ($binding["type"] == "REPLACE") { $data->tags['{' . $binding["data"] . ':h}'] = "Binding para " . $binding["childName"]; } } } $data->fileData = ""; if(file_exists($path)) { $data->fileData = file_get_contents($path); if(!is_writable($path)) { $data->warnings .= "No se puede escribir al archivo especificado
"; $processUser = posix_getpwuid(posix_geteuid()); $data->warnings .= "Para reparar: chmod " . $processUser['name'] . " $path
"; } } else { if($_REQUEST["scriptlet"]) { if($data->scriptlets[$_REQUEST["scriptlet"]]) { $data->scriptlets[$_REQUEST["scriptlet"]] = "style=\"font-weight: bold; font-style: italic\""; } else { $data->scriptlets[$_REQUEST["scriptlet"]] = "style=\"font-style: italic\""; } } else { if($data->scriptlets_no_class) { $data->scriptlets_no_class = "style=\"font-weight: bold; font-style: italic\""; } else { $data->scriptlets_no_class = "style=\"font-style: italic\""; } } if(!file_exists(dirname($path))) { @recursive_mkdir(dirname($path), 0777); } if(file_exists(dirname($path))) { if(!is_writable(dirname($path))) { $data->warnings .= "No se puede escribir a la carpeta
"; $processUser = posix_getpwuid(posix_geteuid()); $data->warnings .= "Para reparar: chmod -R " . $processUser['name'] . " " . dirname($path) . "
"; } } } if($errorPHP) { $data->warnings .= "$errorPHP
\n"; $data->fileData = $_REQUEST['contenido']; } $ta = new ecInputWidget_ace("contenido",$app->db,'','',''); $ta->setOptions("rows=40|cols=160|top=90|theme=twilight|mode=htm|mode=html"); if($_REQUEST["scriptlet"]) { $ta->setOptions("rows=40|cols=160|top=90|theme=twilight|mode=php"); } $ta->name = "contenido"; $ta->rows = "200"; $data->templatePath = str_replace($app->settings["ecAPI"]["INSTALL_ROOT"] . "/", "", $path); $data->textArea = $ta->getHTML($data->fileData); $data->instName = $this->name; $data->class = $this->type ? $this->type: get_class($this); $data->jsFuncs = $ta->getJSFunction(); $data->js = "\n"; return $tpl->bufferedOutputObject($data); } // Devuelve la url sin los argumentos de este componente. function urlSoFar($incluirMe = false, $blacklist = array()) { global $globalParams; $url = ''; foreach($globalParams as $key => $val) { if($key == '') continue; if($key == '0') continue; if($key == $this->name && !$incluirMe) continue; /* Si esto rompe algo, me dicen - lgm */ if($key == 'CONFIG') { continue; } foreach($val as $key2 => $val2) { if(!is_scalar($val2)) { continue; } if($key == $this->name && $blacklist && in_array($key2, $blacklist)) { continue; } if($blacklist && in_array("$key.$key2", $blacklist)) { continue; } if($val2 == "" || is_null($val2) || strstr($val2, "/")) { continue; } $url .= '/'.$key.'.'.$key2.'/'.$val2; } } $urlfinal = '/'.$globalParams[0][1].'/'.$globalParams[0][2].$url; if($globalParams[0][1] == $globalParams[0][2]) { $urlfinal = '/'.$globalParams[0][2].$url; } /* PUEDEN VENIR LOS PARAMETROS VACIOS Y DEBEMOS MANEJAR ESO $urlfinal = preg_replace("!/./!", "/", $urlfinal); $urlfinal = preg_replace("!/+!", "/", $urlfinal); $urlfinal = preg_replace("!/$!", "", $urlfinal); */ return $urlfinal; } function parseSysString($s) { global $globalParams; global $app; $uid = $_SESSION['userid']; $utable = $app->settings["Security"]["authTable"]; $uname = $_SESSION['username']; $uindex = $app->settings["Security"]["authUserField"]; $s = str_replace('{sys.userindex}',$uindex,$s); $s = str_replace('{sys.usertable}',$utable,$s); $s = str_replace('{sys.userid}',$uid,$s); $s = str_replace('{ist.id}',$this->id,$s); $s = str_replace('{ist.name}',$this->name,$s); foreach($globalParams as $k1=>$v1) foreach($v1 as $k=>$v) { $s = str_replace('{'.$k1.'.'.$k.'}', $v, $s); } if($_SESSION) { foreach($_SESSION as $k=>$v) { if (is_array($k) || is_object($k)) continue; if (is_array($v) || is_object($v)) { foreach($v as $vk => $vv) { if (! ((is_numeric($vk)|| is_string($vk)) && (is_numeric($vv)|| is_string($vv)))) continue; $s = str_replace('{SESSION.'.$k.'.'.$vk.'}', $vv, $s); } continue; } if (! ((is_numeric($k)|| is_string($k)) && (is_numeric($v)|| is_string($v)))) continue; $s = str_replace('{SESSION.'.$k.'}', $v, $s); } } return $s; } function getHelp($item) { return "Help[$item] Class=" . get_class($this); } /** * This method converts the object into its Javascript validator source code. * Expect this to be overriden in each derived method. * * @return string Javascript validation entry for this field. */ function getJS () { } /** * This method converts the object into a function that validates fields of this type. * Expect this to be overriden in each derived method. * * @return array An array whose key is the type of this widget and whose value is the corresponding HTML code (to avoid repetition of functions) */ function getJSFunction() { } /* For multiRecordView and other database-based components */ function getContentFormView() { global $app; global $globalParams; global $editMode; global $modelArray; require_once("ecOutputWidget.php"); require_once("ecView.php"); require_once("ecDDL.php"); $table = $this->configurations['viewTable']; if(!$table) { print "No se definió la tabla para la vista (viewTable). Avisar a soporte@mitocondria.cl
"; print "name=" . $this->name . "
"; print "class=" . get_class($this) . "
"; print "URL=http://" . $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"] . "
"; return; } $model = new ecDDL(); if($app->settings["Contento"]["COMPONENT_DDL"]) { include($app->settings["Contento"]["COMPONENT_DDL"]); } else { include($app->settings["ecAPI"]["DATAMODEL"]); } $model->createFromArray($modelArray); $tableDDL=$model->getTable($table); $fieldlist = $this->configurations['viewFieldlist']; if(!is_array($this->configurations['viewFieldlist'])) $fieldlist = unserialize($this->configurations['viewFieldlist']); if(!$fieldlist) { $fieldlist=array($table=>$tableDDL->getFieldNames()); } $keyname = $this->configurations['viewKey']; if(!$keyname) { $keyname=$model->getTableKey($table); } $cond = $this->configurations['viewCondition']; global $globalParams; foreach($globalParams as $k1=>$v1) { foreach($v1 as $k=>$v) { $cond = str_replace('{'.$k1.'.'.$k.'}', $app->quotesql($v), $cond); } } if(!$_REQUEST["order"]) $_REQUEST["order"]=$keyname; $view = new ecView($fieldlist,$model,$app,$cond); $view->filtered=1; $view->navigator=1; if($_REQUEST["whattodo"]=='deleteSelected') { if($view->massDelete($_REQUEST["viewSelectedRows"],$table,$keyname)) { closewindow($_SERVER["PHP_SELF"]); } exit; } $view->populateFromTable(); $tpl=new ecTpl(); $tpl->TITLE = "Edición de Contenido"; if($viewDefaults = $this->configurations['viewDefaults']) { if(!is_array($viewDefaults)) { $viewDefaults = unserialize($viewDefaults); } $idpagina = NULL; if(is_array($pagina = $globalParams["uri"])) { $pagina = array_shift($pagina); } if($pagina) { $rid = $app->readRecord("URL", "URI_____URL='" . $app->quotesql($pagina) . "'"); $idpagina = $rid["ID______URL"]; } $viewRepl = array( "idpagina" => $idpagina, "pagina" => $pagina, ); $tpl->DEFAULTS = ''; foreach($viewDefaults as $kd => $vd) { foreach($viewRepl as $kr => $vr) { $vd = str_replace('{' . $kr . '}', $vr, $vd); } $tpl->DEFAULTS .= '&defaults[' . $kd . ']=' . rawurlencode($vd); } } $extravars=array( TABLE=>$table, KEYNAME=>$keyname ); $tpl->adminBase = preg_replace("!^/([^/]+)/.*$!", "/$1/", $_SERVER["REQUEST_URI"]); $template = "view_tabbed.html"; if($app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"]) { $app->settings["ecAPI"]["TEMPLATE_DIR"] = $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"]; $app->settings["ecAPI"]["COMPILE_DIR"] = $app->settings["ecAPI"]["CACHE_DIR"]; } else { $app->settings["ecAPI"]["TEMPLATE_DIR"] = $app->settings["ecAPI"]["ADMIN_TEMPLATE_DIR"]; } $tpl->tblCombo[] = $table; #$tpl->tblCombo = array_merge($tpl->tblCombo , $model->getTableNames()); if($_REQUEST["whattodo"]=="xls"){ ini_set("max_execution_time","3600"); $_REQUEST["display_rows"]=100000; $_REQUEST["offset_rows"]=0; $_REQUEST["currentPage"]=1; $tpl->CONTENT=$view->toXLS(); exit; } else { $tpl->CONTENT=$view->toHTML($template ,$extravars, $tpl); } $tpl->TITLE=$model->model[$table]->description; $tpl->TABLE = $table; if(!$tpl->TITLE) $tpl->TITLE=$table; $options = array( 'templateDir' => $app->settings["ecAPI"]["TEMPLATE_DIR"], 'compileDir' => $app->settings["ecAPI"]["COMPILE_DIR"] ); $tpl->ECAPI_ENCODING = $app->settings["DB"]["encoding"]; $output = new HTML_Template_Flexy($options); $output->compile("popup.html"); return $output->bufferedOutputObject($tpl); } /* This hopes to solve the AUTH problem. * It tries to find an AUTH component and call it first. * It also looks at the wrapper, if any. */ function handleAuth() { if($this->bindings) { foreach ( $this->bindings as $id => $binding){ if ($binding["type"] == "AUTH") { $classname = $binding["class"]; require_once($classname . ".php"); $child = new $classname(); $child->setConfigFromRecord($binding["child"]); $child->setParent($this); $child->execute(); } if ($binding["type"] == "WRAP") { $classname = $binding["class"]; require_once($classname . ".php"); $child = new $classname(); $child->setConfigFromRecord($binding["child"]); $child->handleAuth(); } } } } /* Content Edition Policies * Currently only implemented for Intranet Parque del Recuerdo on an experimental way. * * The plan is to have a classification table and apply permissions to each section, but it's not implemented yet. * Note: DON'T OVERWRITE $adminMode, IT'S A GLOBAL PARAMETER!!! * Feel free to disable $this->adminButtons[...] if you find it necessary. */ function loadPermissions() { global $app; global $adminMode; global $currentSession; $userData = $app->readRecord($app->settings["Security"]["authTable"], $app->settings["Security"]["authUserField"] . "='" . $app->quotesql($app->settings["Security"]["authPassField"]) . "'"); if(file_exists($app->settings["Contento"]["CUSTOM_ACCESS_CONTROL"])) { include($app->settings["Contento"]["CUSTOM_ACCESS_CONTROL"]); return; } /* Allow everything for now */ return; } function quickRun($name) { global $app; global $adminMode; $myRecord = $app->readRecord("INSTANCE","NAME____IST='" . $app->quotesql($name) . "'"); if(!$myRecord) { $app->error("quicRun[$name] falló"); } $iclass = $myRecord["CLASS___IST"]; include_once("$iclass.php"); $sist = new $iclass(); $sist->setConfigFromRecord($myRecord); return $sist->getHTML(); } function error($message, $title="error") { global $app; global $adminMode; global $globalParams; $myRecord = $app->readRecord("INSTANCE","NAME____IST='error'"); if(!$myRecord) { $app->error($message, $title); } $app->log("ERROR $title: $message", $app->SEVERITY_DEBUG); $iclass = $myRecord["CLASS___IST"]; include_once("$iclass.php"); $sist = new $iclass(); $myRecord["message"] = $message; $globalParams["CONFIG"]["TITLE"] = $myRecord["title"] = $title; $sist->setConfigFromRecord($myRecord); $sist->tpl->message = $message; if(preg_match("/p.*gina no encontrada|page not found/i", $message)||preg_match("/p.*gina no encontrada|page not found/i", $title)) { $sist->tpl->error404 = 1; } $sist->tpl->title = $title; print $sist->getHTML(); exit; } function execute() { } function listBaseTemplates() { $templates = array(); $folder = "/var/www/contento-2.2.piloto.cl/baseTemplates/" . strtolower(get_class($this)); if(!file_exists($folder)) { return array(); } $dir = opendir($folder); while($file = readdir($dir)) { if($file[0] == ".") continue; if(is_file("$folder/$file")) { $templates[] = $file; } } sort($templates); return $templates; } }