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 = "
$content
"; } return $content; } return $this->__getHTML(); } function delBinding($name) { global $app; $app->do_query("DELETE FROM binding WHERE parent__bnd = ".$this->id." AND data____bnd = '".$name."'"); echo ''; exit(0); } function enableBinding($name) { global $app, $globalParams; if(!$this->url) { foreach($globalParams[0] as $ik => $vk) { if($vk == 'uri') { $this->url = $globalParams[0][$ik + 1]; break; } } } $bnd = $app->readRecord("BINDING", "PARENT__BND='" . $app->quotesql($this->id) . "' AND DATA____BND='" . $app->quotesql($name) . "'"); if($bnd) { $url = $app->readRecord("URL", "URI_____URL='" . $app->quotesql($this->url) . "'"); if(!$url) { print_r($globalParams); print "No recibí la URL de este componente"; exit; } $app->do_query("DELETE FROM BINDING_EXCEPTION WHERE BINDING_BEX='" . $app->quotesql($bnd["ID______BND"]) . "' AND URL_____BEX='" . $app->quotesql($url["ID______URL"]) . "'"); echo ''; } else { print "Not found: " . $this->id . " name=$name"; } exit(0); } function disableBinding($name) { global $app, $globalParams; if(!$this->url) { foreach($globalParams[0] as $ik => $vk) { if($vk == 'uri') { $this->url = $globalParams[0][$ik + 1]; break; } } } $bnd = $app->readRecord("BINDING", "PARENT__BND='" . $app->quotesql($this->id) . "' AND DATA____BND='" . $app->quotesql($name) . "'"); if($bnd) { $url = $app->readRecord("URL", "URI_____URL='" . $app->quotesql($this->url) . "'"); if(!$url) { print_r($globalParams); print "No recibí la URL de este componente"; exit; } $disabled = $app->readRecord("BINDING_EXCEPTION", "BINDING_BEX='" . $app->quotesql($bnd["ID______BND"]) . "' AND URL_____BEX='" . $app->quotesql($url["ID______URL"]) . "'"); if(!$disabled) { $hash = array( "URL_____BEX" => $url["ID______URL"], "BINDING_BEX" => $bnd["ID______BND"] ); $app->addRecord("BINDING_EXCEPTION", $hash); } #print "El componente ya estaba desactivado. ID=" . $this->id . "NAME=" . $this->name . " name=$name URL=" . $this->url; echo ''; exit(0); } else { print "Error al encontrar componente. ID=" . $this->id . " name=$name"; } exit(0); } function getContentParameters() { return array(); } function getContentForm() { global $app; require_once("ecInputWidget/tinymce.php"); require_once("ecFormVars.php"); require_once("ecForm.php"); require_once("ecDDL.php"); require_once("ecFormVars.php"); require_once("ecValidator.php"); require_once("ecArrayValidator.php"); $opt = array( 'templateDir' => $app->settings["ecAPI"]["INSTALL_ROOT"] . "/classes/templates", 'compileDir' => $this->cachePath ); $oData = new ecTpl(); $oData->config = $this->getContentParameters(); $oData->ddl = $this->getContentFormDefinition(); $oData->instance_name = $this->name; if($this->getContentFormDefinition()) { $ddl = new ecDDL(); $ddl->createFromArray($this->getContentFormDefinition()); $table = $ddl->getTable('CONFIG'); $fieldlist = array('CONFIG' => $table->getFieldNames()); } if(isset($_POST['aceptar'])) { $formvars = new ecFormVars(); $formvalues = $formvars->toArray(); $av = new ecArrayValidator($fieldlist,$ddl,$app); $av->setOptions(array( "skipTypes"=>"" )); if(count($av->validate($formvalues))) { } else { foreach($fieldlist['CONFIG'] as $v) { if($v == 'file' && $formvalues[$v] == '') $formvalues[$v] = $this->contents['file']; $guard[$v] = $formvalues[$v]; } $str = $app->quotesql(serialize($guard)); $app->do_query("UPDATE INSTANCE SET CONTENT_IST = '".$str."' WHERE ID______IST = ".$this->id); $this->contents = $guard; } } else if(isset($_REQUEST['sub'])) { $str = $app->quotesql(serialize($_REQUEST['keys'])); $this->contents = $_REQUEST['keys']; $app->do_query("UPDATE INSTANCE SET CONTENT_IST = '".$str."' WHERE ID______IST = ".$this->id); echo 'Done!'; echo ''; } #print $this->name . ": " . get_class($this) . "
\n"; if($this->getContentFormDefinition()) { $form = new ecForm($fieldlist,$ddl,$app); $form->setDefaults($this->getContentParameters()); // print "Contenidos:" . print_r($this->contents,1); // print print_r($this->getContentParameters(),1) ; $oData->content = $form->toHTML('form.html'); } else { foreach($oData->config as $key => $value) { $ta = new ecInputWidget_tinymce("keys[$key]",$app->db,'','',''); $ta->name = "keys[$key]"; # $ta->rows="100"; $ta->setOptions("rows=20|mode=basic"); $oData->textArea[$key] = $ta->getHTML($value); $oData->jsFuncs = $ta->getJSFunction(); } } $odata->ECAPI_ENCODING = $app->settings["DB"]["encoding"]; $tpl = new HTML_Template_Flexy($opt); $tpl->compile('content_component.html'); return $tpl->bufferedOutputObject($oData); } function getContentFormDefinition() { return false; } // metodo para configurar las variables que iran serialziadas en la DB function getAdminForm() { require_once("ecValidator.php"); require_once("ecArrayValidator.php"); global $app; $opt = array( 'templateDir' => $app->settings["ecAPI"]["INSTALL_ROOT"] . "/classes/templates", 'compileDir' => $this->cachePath ); $jsIG = new JSInputGrid("Bindings"); $jsIG->setFields(array("BINDING"=> array("ID______BND","PARENT__BND","CHILD___BND","TYPE____BND","DATA____BND"))); $jsIG->setKeyField("ID______BND"); $datas = new ecTpl(); if(isset($_REQUEST['sub'])) { $config = $this->getConfigurationParameters(); $configwidgets = $this->getConfigurationWidgets(); $str = array(); $oldData = $app->readRecord("INSTANCE"," ID______IST = ".$app->quotesql($this->id) ); $str = unserialize( $oldData["CONFIG__IST"] ) ; foreach($config as $k => $v) { if($configwidgets[$k]) { $type = $configwidgets[$k]; $options = ""; if(eregi("^(.*)\\[(.*)\\]$", $type, $regTags)) { $type=$regTags[1]; $options=$regTags[2]; } } else { $type = "serialized"; $options = ""; } require_once("ecValidator/$type.php"); $classname = "ecValidator_" . $type; $validator = new $classname(); $validator->uploadDir = $app->settings["ecAPI"]["UPLOAD_DIR"]; if($options) { $validator->setOptions($options); } if($type=='serialized') { $str[$k] = $validator->parseRequest($_REQUEST['keys'][$k]); } elseif($type=='txt_multilines') { $dummy = array(); foreach($_REQUEST as $rk=>$rv) { if(ereg("^keys_tm_$k", $rk)) { $dummy[$rk] = $rv; } } $validator->validate("keys_tm_$k", $dummy); $str[$k] = $dummy["keys_tm_$k"]; } elseif( $type =='fileupload' OR $type =='imageupload' ) { /* Borrado */ if($_REQUEST["keys"][$k]) { $str[$k] = ""; } if ( isset( $_FILES["keys"]["name"][$k] ) AND strlen( $_FILES["keys"]["name"][$k] ) > 0 ) { $fileinfo[$k] = array( $k.'_MIME' => '' , $k.'_NAME' => $_FILES["keys"]["name"][$k] , "name" => $_FILES["keys"]["name"][$k] , "tmp_name" => $_FILES["keys"]["tmp_name"][$k] ); $validator->validate($k, $fileinfo ); $str[$k] = $_FILES["keys"]["name"][$k]; } } else { $dummy = array("field" => $_REQUEST['keys'][$k]); $validator->validate("field", $dummy); $str[$k] = $dummy["field"]; } } $str = serialize($str); $app->do_query("UPDATE INSTANCE SET CONFIG__IST = '" . $app->quotesql($str) ."' WHERE ID______IST = ".$app->quotesql($this->id)); $this->setConfigFromRecord($this->id); foreach($jsIG->getRowsToUpdate() as $row) { $row['PARENT__BND'] = $this->id; $app->updateRecord("BINDING",$row,"ID______BND = ".$row["ID______BND"]); } foreach($jsIG->getRowsToAdd() as $row) { unset($row["ID______BND"]); $row['PARENT__BND'] = $this->id; $app->addRecord("BINDING",$row); } foreach($jsIG->getRowsToDelete() as $row) { $app->deleteRecord("BINDING","ID______BND=" . $row["ID______BND"]); } $datas->MENSAJES = 'Done.

' . ''; if(!strstr(file_get_contents($opt['templateDir'] . "/config_component.html"), '{MENSAJES:h}')) { echo $datas->MENSAJES; } } $jsIG = new JSInputGrid("Bindings"); $jsIG->setFields(array("BINDING"=> array("ID______BND","CHILD___BND","TYPE____BND","DATA____BND"))); $jsIG->setKeyField("ID______BND"); $q = $app->InitReadLoop("BINDING","PARENT__BND='".$this->id."'"); $instanceconfig = $app->readRecord('INSTANCE','ID______IST = '.$this->id); while( $row = $q->fetchRow(DB_FETCHMODE_ASSOC)) $data[] = $row; $jsIG->data= $data; $datas->jsFuncs = array(); $datas->confignorm = $datas->configfields = array(); $config = $this->getConfigurationParameters(); $configwidgets = $this->getConfigurationWidgets(); $help = $this->getConfigurationHelp(); $widgetfunctionsadded = array(); foreach($config as $k => $v) { if($configwidgets[$k]) { $type = $configwidgets[$k]; $options = ""; if(eregi("^(.*)\\[(.*)\\]$", $type, $regTags)) { $type=$regTags[1]; $options=$regTags[2]; } } else { $type = "serialized"; $options = "valuesize=40"; } require_once("ecInputWidget/$type.php"); $classname = "ecInputWidget_" . $type; if($type == 'txt_multilines') { $widget = new $classname($dummy, $app->db, "keys_tm_$k", NULL); } else { $widget = new $classname($dummy, $app->db, "keys[$k]", NULL); } $widget->setOptions($options); if($type == "serialized") { $w = serialize($v); } else { $w = $v; } $html = $widget->getHTML($w); if(!$widgetfunctionsadded[$type] || $type == 'function') { $a = $widget->getJSFunction(); if($a) { foreach($a as $ka => $va) { $datas->jsFuncs[$ka] = $va; } } $widgetfunctionsadded[$type] = 1; } $datas->confignorm[$k . " " . $help[$k] . ""] = $html; $datas->configfields[$k] = array( "name" => $k, "help" => $help[$k], "value" => $html ); } $datas->jsFuncs = join("\n", $datas->jsFuncs); $datas->submit_url = ''; $datas->grid = $jsIG->getGrid(1); $datas->jsFuncs .= $jsIG->getJsFunctions(); $datas->instName = $this->name; $datas->class = get_class($this); $datas->instID = $this->id; $tpl = new HTML_Template_Flexy($opt); $tpl->compile('config_component.html'); return $tpl->bufferedOutputObject($datas); } // function getHTML() // { /* if ($this->checkCache()) return $this->data; else { */ /* global $banner_factory; if($banner_factory) { $banner_factory->build($this->tpl); } //si no estaba en el cache... $options = array( 'templateDir' => $this->templatePath, 'compileDir' => $this->cachePath ); $output = new HTML_Template_Flexy($options); // print "template: ". $this->template."
"; $output->compile($this->template); $this->data = $output->bufferedOutputObject($this->tpl); chmod($this->cachePath."/".$this->template.".en.php",0777); chmod($this->cachePath."/".$this->template.".gettext.serial",0777); /*$this->saveCache();*/ // return $this->data; /* } */ // } // // Devuelve los parametros pasados via url pertenecientes solo a la instancia // function getParams() { global $globalParams; return $globalParams[$this->name]; } // // Setea el componente para que se despliegue en forma administrable. // function setAdminMode() { $this->adminMode = true; } // Agrega un binding, si no se pasa el id del instance hijo se despliega un formulario function addBinding($tagName) { global $app; if($_REQUEST['child_id'] > 0) { $row['PARENT__BND'] = $this->id; $row['CHILD___BND'] = $_REQUEST['child_id']; $row['DATA____BND'] = $_REQUEST['tagName']; $row['TYPE____BND'] = 'REPLACE'; $app->addRecord('binding',$row); #echo 'Done'; #exit(0); closewindow('/admin'); exit; } $oData = new ecTpl(); $oData->tagName = $tagName; $oData->parentId = $this->id; $oData->ists = $this->name; $q = $app->initReadLoop('INSTANCE','ID______IST <> '.$this->id,'ID______IST ASC','ID______IST,NAME____IST,CLASS___IST'); while($oData->instances[] = $q->fetchRow(DB_FETCHMODE_ASSOC)); $opt = array( 'templateDir' => $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"], 'compileDir' => $this->cachePath ); $newinstances = array(); foreach($oData->instances as $key => $val){ if(!$newinstances[$val["CLASS___IST"]]) $newinstances[$val["CLASS___IST"]] = array(); $newinstances[$val["CLASS___IST"]][] = $val; } $oData->instances = $newinstances; $tpl = new HTML_Template_Flexy($opt); $tpl->compile('addBinding.html'); return $tpl->bufferedOutputObject($oData); } function handleGlobals(&$tpl) { global $globalParams; foreach($globalParams as $k1=>$v1) { foreach($v1 as $k=>$v) { $tpl->{$k1.'_'.$k} = $v; } } if($_SESSION) { foreach($_SESSION as $k=>$v) { $tpl->{'SESSION_'.$k} = $v; } } $tpl->{'rol_' . $_SESSION['userrole'] } = 1; } function handleBindings(&$tpl) { global $globalParams; global $app; global $bindingExceptions; if(!$this->url) { /* Backwards compatibility */ $this->url = $globalParams[0][2]; if($this->url == 'ist'||$this->url == 'lst'||$this->url == 'url') { $this->url = $globalParams[0][3]; } } $url = $app->readRecord("URL", "URI_____URL='" . $app->quotesql($this->url) . "'"); if($url) { foreach($url as $k => $v) { $tpl->{'URL_'.$k} = $v; } } $tpl->PHP_SELF = $_SERVER["PHP_SELF"]; $tpl->REQUEST_URI = $_SERVER["REQUEST_URI"]; $tpl->HTTP_HOST = $_SERVER["HTTP_HOST"]; $tpl->FULL_PAGE_URL = "http://" . $_SERVER["HTTP_HOST"] . ($_SERVER["SERVER_PORT"] == 80 ? "" : (":" . $_SERVER["SERVER_PORT"])); $tpl->FULL_PAGE_URL .= $_SERVER["REQUEST_URI"]; if(!is_array($this->bindings)) { return; } foreach ( $this->bindings as $id => $binding){ if ($binding["type"] == "REPLACE"){ if(!$binding["data"]) { #print "[" . $this->name . "]"; print "REPLACE sin indicar a donde en " . $this->name . ":"; var_export($binding); continue; } $classname = $binding["class"]; require_once($classname . ".php"); $child = new $classname(); $child->url = $this->url; $child->setConfigFromRecord($binding["child"]); $child->setParent($this); $app->log("REPLACE: " . $this->name . ": $classname : " . $child->name . ":" . microtime(true), $app->SEVERITY_DEBUG); if($bindingExceptions[$id]) { $child->disabledBinding = true; global $adminMode, $editMode; if(!$adminMode && !$editMode) { $tpl->{$binding["data"]} = ""; continue; } } $tpl->{$binding["data"]} = $child->getHTML(); #print $binding["data"] . ": " . $child->name . ": $classname : " . strlen($tpl->{$binding["data"]}) . "
\n"; } else if ($binding["type"] == "DATASET") { global $contentoDataSets; $data = $contentoDataSets[$id]; if(!$data) { $classname = $binding["class"]; require_once($classname . ".php"); $child = new $classname(); $child->setConfigFromRecord($binding["child"]); $child->setParent($this); $data = $contentoDataSets[$id] = $child->getData(); } foreach($data as $k=>$v) { $tpl->{$k} = (array)$v; } } else if ($binding["type"] != "WRAP" && $binding["type"] != "AUTH") { $classname = $binding["class"]; require_once($classname . ".php"); $child = new $classname(); $child->url = $this->url; $child->setConfigFromRecord($binding["child"]); $child->setParent($this); $app->log($binding["type"] . ": " . $this->name . ": $classname : " . $child->name . ":" . microtime(true), $app->SEVERITY_DEBUG); $child->execute(); } } } function handleWraps($content, $tpl = NULL, $force = false) { global $app; global $adminMode, $editMode, $bindingExceptions; if($editMode && !$force) { /* No procesamos los wraps todavía */ return $content; } #$app->log("WRAPS FOR: " . $this->name, $app->SEVERITY_DEBUG); $child = $this; // print_r($app); if($this->bindings) { foreach ($this->bindings as $id => $binding) { #$app->log("> " . $binding["child"] . ":" . $binding["class"] . ":" . $binding["type"], $app->SEVERITY_DEBUG); if ($binding["type"] == "WRAP") { $classname = $binding["class"]; require_once($classname . ".php"); $parent = new $classname(); $parent->setConfigFromRecord($binding["child"]); $child->setParent($parent); $app->log("WRAP: " . $this->name . ": $classname : " . $child->name . ":" . microtime(true), $app->SEVERITY_DEBUG); if($bindingExceptions[$id]) { $parent->disabledBinding = true; global $adminMode, $editMode; if(!$adminMode && !$editMode) { continue; } } if($tpl) { foreach($tpl as $k=>$v) { $parent->tpl->{"WRAPPED_$k"} = $v; } } if ($binding["data"]) { $parent->tpl->{$binding["data"]} = $content; } else { die("tag 'data' para una operacion 'wrap' no definido"); } $content = $parent->getHTML(); $child = $parent; } } } return $content; } function addAdminTags(&$data) { global $adminMode, $app; if($adminMode && $this->configurations['template']) { $dataF = file_get_contents($this->templatePath.'/'.$this->configurations['template']); if (preg_match_all("/{([a-zA-Z0-9._-]*):h}/",$dataF,$tags)) { foreach($tags[1] as $v) { if(!$v) { continue; } if(preg_match('/^WRAPPED_/', $v)) { continue; } if(preg_match('/^........(CON|TAX)(_NAME|_MIME)?$/', $v)) { continue; } if ( $v != 'CONFIG_BASE' AND $v != 'CONFIG_TITLE' AND $v != 'CONFIG_DESCRIPTION' AND $v != 'CONFIG_KEYWORDS' AND $v != 'CONFIG_HEADERS' ) { if (!$v) continue; if(!isset($data->{$v})) { $opt = array( 'templateDir' => $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"], 'compileDir' => $this->cachePath ); $tpl2 = new HTML_Template_Flexy($opt); $tpl2->compile("marcoAddComp.html"); $oData = new ecTpl(); $oData->ists = $this->name; $oData->istId = $this->id; $oData->bindName = $v; $data->{$v} = $tpl2->bufferedOutputObject($oData); } } } } } } function createTemplate($baseTemplate, $finalName) { global $app; $data = new ecTpl(); /* Inicio porción a sobreescribir */ /* Fin porción a sobreescribir */ $this->createTemplatePost($data, $baseTemplate, $finalName); } function createTemplatePost($data, $baseTemplate, $finalName) { global $app; if(!in_array($baseTemplate, $this->listBaseTemplates())) { $app->error("La plantilla seleccionada no fue encontrada"); } $opt = array( 'templateDir' => "/var/www/contento-2.2.piloto.cl/baseTemplates/" . strtolower(get_class($this)), 'compileDir' => $this->cachePath ); $tpl = new HTML_Template_Flexy($opt); $tpl->compile($baseTemplate); $fullFinalName = $this->templatePath . "/$finalName"; if(file_exists($fullFinalName)) { $app->error("La plantilla ya existe ($fullFinalName). Por favor seleccione otro nombre de plantilla"); } $fp = fopen($fullFinalName, "w"); if(!$fp) { $app->error("No pude escribir en la plantilla. Por favor asegúrese que la carpeta " . $this->templatePath . " tenga permisos de escritura"); } fputs($fp, str_replace('{!', '{', $tpl->bufferedOutputObject($data))); fclose($fp); global $app; $oldData = $app->readRecord("INSTANCE"," ID______IST = ".$app->quotesql($this->id) ); $str = unserialize( $oldData["CONFIG__IST"] ) ; $str["template"] = $finalName; $str = serialize($str); $app->do_query("UPDATE INSTANCE SET CONFIG__IST = '" . $app->quotesql($str) ."' WHERE ID______IST = ".$app->quotesql($this->id)); $this->setConfigFromRecord($this->id); } function editTemplate() { global $app; //require_once("ecInputWidget/tinymce.php"); //require_once("ecInputWidget/bespin.php"); require_once("ecInputWidget/textarea.php"); require_once("ecInputWidget/ace.php"); $opt = array( 'templateDir' => $app->settings["Contento"]["COMPONENT_ADMIN_TEMPLATE_DIR"], 'compileDir' => $this->cachePath ); if($_POST["predesignTemplate"]) { $this->createTemplate($_POST["newTemplate"], $_POST["templateName"]); } if(!$this->configurations['template']) { $tmp = $this->getConfigurationParameters(); if(in_array('template', array_keys($tmp))) { $tpl = new HTML_Template_Flexy($opt); $tpl->compile('predesignTemplate.html'); $data = new ecTpl(); $data->tags = $this->getTemplateTagList(); $data->templates = $this->listBaseTemplates(); if(!$data->templates) { $app->error("Este componente no tiene una plantilla configurada, y no hay plantillas base disponibles.
Deberá crear plantillas base en la carpeta:
/var/www/contento-2.2.piloto.cl/baseTemplates/" . strtolower(get_class($this)) . "

Deberá además sobreescribir el método createTemplate de la clase " . strtolower(get_class($this)) . " de acuerdo a las necesidades de la clase."); } $data->singleTemplate = count($data->templates) == 1; return $tpl->bufferedOutputObject($data); } else { $app->error("Este componente no soporta la opción de plantillas"); } } $errorPHP = false; if(isset($_REQUEST['guardar'])) { $path = $this->templatePath.'/'.$this->configurations['template']; if($_REQUEST["scriptlet"]) { $path = $app->settings["Contento"]["SCRIPTLET_DIR"] . "/" . $_REQUEST["scriptlet"] . "/" . $this->name . ".php"; $tmp = tempnam(function_exists("sys_get_temp_dir") ? sys_get_temp_dir() : "/tmp", "slet"); $f = @fopen($tmp,'w'); if($f) { fwrite($f, rawurldecode($_REQUEST['contenido'])); fclose($f); $out = array(); $ret = 0; exec("/usr/bin/php -l " . escapeshellarg($tmp) . " 2>&1", $out, $ret); if($ret) { $errorPHP = str_replace($tmp, $this->name . ".php", join("
\n", $out)) . "

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; } }