Exemple #1
1
 function handle(&$params)
 {
     if (!@$_REQUEST['email']) {
         return PEAR::raiseError("No email address  specified");
     }
     import('HTML/QuickForm.php');
     $form = new HTML_QuickForm('opt_out_form', 'post');
     $form->addElement('hidden', 'email', $_REQUEST['email']);
     $form->addElement('hidden', '-action', 'email_opt_out');
     $form->addElement('submit', 'submit', 'Cancel Subscription');
     if ($form->validate()) {
         $res = mysql_query("replace into dataface__email_blacklist (email) values ('" . addslashes($_REQUEST['email']) . "')", df_db());
         if (!$res) {
             trigger_error(mysql_error(df_db()), E_USER_ERROR);
         }
         header('Location: ' . DATAFACE_SITE_HREF . '?--msg=' . urlencode('You have successfully opted out of our mail list.  You will no longer receive emails from us.'));
         exit;
     }
     ob_start();
     $form->display();
     $html = ob_get_contents();
     ob_end_clean();
     $context = array();
     $context['form'] = $html;
     df_register_skin('email', DATAFACE_PATH . '/modules/Email/templates');
     df_display($context, 'email/opt_out_form.html');
 }
Exemple #2
0
function performJobs()
{
    if (!mutex('email.' . base64_encode(DATAFACE_SITE_PATH))) {
        die("Email daemon already running");
    }
    $res = mysql_query("select * from dataface__email_jobs", df_db());
    if (!$res) {
        trigger_error(mysql_error(df_db()), E_USER_ERROR);
    }
    require_once DATAFACE_PATH . '/modules/Email/actions/email.php';
    $action = new actions_email();
    while ($row = mysql_fetch_assoc($res)) {
        echo "\nSending mail for job {$row['job_id']} ...";
        $res2 = mysql_query("delete from `" . $row['join_table'] . "` where recipient_email='' and messageid='" . addslashes($row['email_id']) . "'", df_db());
        $action->sendMail($row['email_id'], $row['email_table'], $row['join_table'], $row['recipients_table'], $row['email_column']);
        // check to see if all the messages for this job have been sent yet
        $res2 = mysql_query("select count(*) from `" . $row['join_table'] . "` where sent<>1 and messageid='" . addslashes($row['email_id']) . "'", df_db());
        if (!$res2) {
            trigger_error(mysql_error(df_db()), E_USER_ERROR);
        }
        list($num) = mysql_fetch_row($res2);
        @mysql_free_result($res2);
        if ($num == 0) {
            echo "\nJob {$row['job_id']} is complete!  Deleting job...";
            $res2 = mysql_query("delete from dataface__email_jobs where job_id='" . addslashes($row['job_id']) . "' limit 1", df_db());
            if (!$res2) {
                trigger_error(mysql_error(df_db()), E_USER_ERROR);
            }
        } else {
            echo "\nAfter sending mail for job {$row['job_id']}, there are still {$num} messages left to send.";
        }
    }
    @mysql_free_result($res);
    echo "\n";
}
/**
 * This function acts as a member method of the PreferencesTool class.  It has
 * been factored out for efficiency because it only needs to be run once.
 * @see Dataface_PreferncesTool::_createPreferencesTable()
 */
function Dataface_PreferencesTool__createPreferencesTable()
{
    $res = xf_db_query("create table if not exists `dataface__preferences` (\n\t\t\t`pref_id` int(11) unsigned not null auto_increment,\n\t\t\t`username` varchar(64) not null,\n\t\t\t`table` varchar(128) not null,\n\t\t\t`record_id` varchar(255) not null,\n\t\t\t`key` varchar(128) not null,\n\t\t\t`value` varchar(255) not null,\n\t\t\tprimary key (pref_id),\n\t\t\tindex `username` (`username`),\n\t\t\tindex `table` (`table`),\n\t\t\tindex `record_id` (`record_id`))", df_db());
    if (!$res) {
        throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
    }
}
Exemple #4
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query = $app->getQuery();
     $query['-skip'] = 0;
     $query['-limit'] = 999999999;
     $at = Dataface_ActionTool::getInstance();
     $emailAction = $at->getAction(array('name' => 'email'));
     if (!isset($emailAction) or !isset($emailAction['email_column'])) {
         return PEAR::raiseError("No email column specified");
     }
     $col = $emailAction['email_column'];
     $qb = new Dataface_QueryBuilder($query['-table'], $query);
     $sql = "select `" . $col . "` " . $qb->_from() . $qb->_secure($qb->_where());
     $res = mysql_query($sql, df_db());
     if (!$res) {
         trigger_error(mysql_error(df_db()), E_USER_ERROR);
     }
     $addresses = array();
     while ($row = mysql_fetch_row($res)) {
         $addresses[] = $row[0];
     }
     @mysql_free_result($res);
     header("Content-type: text/plain");
     echo implode(', ', $addresses);
     exit;
 }
    /**
     * @brief Initializes the datepicker module and registers all of the event listener.
     *
     */
    function __construct()
    {
        $app = Dataface_Application::getInstance();
        // Now work on our dependencies
        $mt = Dataface_ModuleTool::getInstance();
        // We require the XataJax module
        // The XataJax module activates and embeds the Javascript and CSS tools
        $mt->loadModule('modules_XataJax', 'modules/XataJax/XataJax.php');
        // Register the geopicker widget with the form tool so that it responds
        // to widget:type=geopicker
        import('Dataface/FormTool.php');
        $ft = Dataface_FormTool::getInstance();
        $ft->registerWidgetHandler('geopicker', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'widget.php', 'Dataface_FormTool_geopicker');
        if (!@$app->_conf['modules_geopicker'] or !@$app->_conf['modules_geopicker']['key']) {
            $msg = <<<END
                 <p>Google Maps Module is installed but no API key is specified.</p>
                 <p>For information about obtaining your API key see <a href="https://developers.google.com/maps/documentation/javascript/tutorial#api_key">this page</a>.</p>
                 <p>After obtaining your key, add the following section to your application's conf.ini file:</p>
                 <p><code><pre>
[modules_geopicker]
    key=YOUR_API_KEY_HERE
                    </pre></code></p>
END;
            die($msg);
        }
        $app->addHeadContent('<script>XF_GEOPICKER_API_KEY="' . htmlspecialchars($app->_conf['modules_geopicker']['key']) . '";</script>');
        foreach (Dataface_Table::loadTable('', df_db(), true) as $t) {
            $evt = new StdClass();
            $evt->table = $t;
            $this->afterTableInit($evt);
        }
        $app->registerEventListener("afterTableInit", array($this, 'afterTableInit'));
        $app->registerEventListener("Dataface_Record__htmlValue", array($this, 'Dataface_Record__htmlValue'));
    }
Exemple #6
0
 static function q($sql)
 {
     $res = mysql_query($sql, df_db());
     if (!$res) {
         throw new Exception(mysql_error(df_db()));
     }
     return $res;
 }
Exemple #7
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     if (df_get_database_version() == df_get_file_system_version()) {
         $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The application database is up to date at version ' . df_get_database_version()));
     }
     if (df_get_database_version() > df_get_file_system_version()) {
         $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The database version is greater than the file system version.  Please upgrade your application to match the version in the database (version ' . df_get_database_version()));
     }
     $res = xf_db_query("select count(*) from dataface__version", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
     $row = xf_db_fetch_row($res);
     if ($row[0] == 0) {
         $res2 = xf_db_query("insert into dataface__version (`version`) values (0)", df_db());
         if (!$res2) {
             throw new Exception(xf_db_error(df_db()));
         }
     }
     if (file_exists('conf/Installer.php')) {
         import('conf/Installer.php');
         $installer = new conf_Installer();
         $methods = get_class_methods('conf_Installer');
         $methods = preg_grep('/^update_([0-9]+)$/', $methods);
         $updates = array();
         foreach ($methods as $method) {
             preg_match('/^update_([0-9]+)$/', $method, $matches);
             $version = intval($matches[1]);
             if ($version > df_get_database_version() and $version <= df_get_file_system_version()) {
                 $updates[] = $version;
             }
         }
         sort($updates);
         foreach ($updates as $update) {
             $method = 'update_' . $update;
             $res = $installer->{$method}();
             if (PEAR::isError($res)) {
                 return $res;
             }
             $res = xf_db_query("update dataface__version set `version`='" . addslashes($update) . "'", df_db());
             if (!$res) {
                 throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
             }
         }
     }
     $res = xf_db_query("update dataface__version set `version`='" . addslashes(df_get_file_system_version()) . "'", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
     }
     if (function_exists('apc_clear_cache')) {
         apc_clear_cache('user');
     }
     df_clear_views();
     df_clear_cache();
     $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The database has been successfully updated to version ' . df_get_file_system_version()));
 }
/**
 * A method to create the configuration table in the database.  The configuration
 * table is where configuration (e.g. fields.ini etc..) may be stored.  This is
 * a new feature in 0.6.14.
 *
 * @author Steve Hannah <*****@*****.**>
 * @created Feb. 26, 2007
 */
function Dataface_ConfigTool_createConfigTable()
{
    $self =& Dataface_ConfigTool::getInstance();
    if (!Dataface_Table::tableExists($self->configTableName, false)) {
        $sql = "CREATE TABLE `" . $self->configTableName . "` (\n\t\t\t\t\tconfig_id int(11) NOT NULL auto_increment primary key,\n\t\t\t\t\t`file` varchar(255) NOT NULL,\n\t\t\t\t\t`section` varchar(128),\n\t\t\t\t\t`key` varchar(128) NOT NULL,\n\t\t\t\t\t`value` text NOT NULL,\n\t\t\t\t\t`lang` varchar(2),\n\t\t\t\t\t`username` varchar(32),\n\t\t\t\t\t`priority` int(5) default 5\n\t\t\t\t\t)";
        $res = xf_db_query($sql, df_db());
        if (!$res) {
            throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
        }
    }
}
Exemple #9
0
 public static function createPortletWithSQL($sql, $cols = null, $opts = array())
 {
     $db = new Database(df_db());
     if (is_array($sql)) {
         if (count($sql) > 1) {
             $queryParams = $sql[1];
         } else {
             $queryParams = array();
         }
         $sql = $sql[0];
     }
     $rows = $db->query($sql, (object) $queryParams);
     return new Portlet($rows, $cols, $opts);
 }
Exemple #10
0
function get_user($token = null)
{
    $db = new Database(df_db());
    if (!isset($token)) {
        $token = $_POST['token'];
    }
    if (!$token) {
        return null;
    }
    $user = $db->getObject("select username from sessions where token_id=:token_id and expires > :now", array('token_id' => $token, 'now' => time()));
    if ($user) {
        return $user->username;
    }
    return null;
}
/**
 * Sets a configuration parameter in the configuration table.
 * This should not be called directly.  It should be called through the 
 * Dataface_ConfigTool class as its setConfigParam method.
 *
 * @param string $file The name of the ini file in which the config value is being set.
 * @param string $section The name of the section (could be null).
 * @param string $key The name of the parameter's key (not null)
 * @param string $value The value to set (not null)
 * @param string $username The username for which the parameter is being set (null for all users)
 * @param string $lang The 2-digit language code for which the parameter is being set (null for all languages).
 * @param integer $priority The priority of this config variable (priority dictates which 
 *					parameters take priority. Default vallue of 5.
 * @returns true if success or PEAR_Error if failure.
 *
 * This will create the configuration table if it doesn't already exist.
 *
 *	@author Steve Hannah <*****@*****.**>
 * @created Feb. 26, 2007
 */
function Dataface_ConfigTool_setConfigParam($file, $section, $key, $value, $username = null, $lang = null, $priority = 5)
{
    $self =& Dataface_ConfigTool::getInstance();
    // See if this parameter has already been set:
    $where = array();
    $where[] = "`key`='" . addslashes($key) . "'";
    $where[] = "`file`='" . addslashes($file) . "'";
    $where[] = "`section`" . (isset($section) ? "='" . addslashes($section) . "'" : ' IS NULL');
    $where[] = "`username`" . (isset($username) ? "='" . addslashes($username) . "'" : ' IS NULL');
    $where[] = "`lang`" . (isset($lang) ? "='" . addslashes($lang) . "'" : ' IS NULL');
    $where = implode(' and ', $where);
    $sql = "select `config_id` from `" . $self->configTableName . "` where {$where} limit 1";
    $res = mysql_query($sql, df_db());
    if (!$res) {
        $self->createConfigTable();
        $res = mysql_query($sql, df_db());
    }
    if (!$res) {
        return PEAR::raiseError("Failed to get config parameter: " . mysql_error(df_db()));
    }
    $vals = array("section" => isset($section) ? "'" . addslashes($section) . "'" : 'NULL', "key" => "'" . addslashes($key) . "'", "value" => "'" . addslashes($value) . "'", "username" => "'" . addslashes($username) . "'", "lang" => "'" . addslashes($lang) . "'", "priority" => $priority);
    if (mysql_num_rows($res) > 0) {
        $row = mysql_fetch_assoc($res);
        // We need to perform an update
        $updates = array();
        foreach ($vals as $vkey => $vval) {
            $updates[] = '`' . $vkey . '`=' . $vval;
        }
        $sets = implode(' and ', $updates);
        $sql = "update `" . $self->configTableName . "` set " . $sets . " where `config_id`='" . $row['config_id'] . "' limit 1";
    } else {
        $values = array();
        $cols = array();
        foreach ($vals as $vkey => $vval) {
            $cols[] = "`{$vkey}`";
            $values[] = $vval;
        }
        $cols = implode(',', $cols);
        $values = implode(',', $values);
        $sql = "insert into `" . $self->configTableName . "` ({$cols}) VALUES ({$values})";
    }
    @mysql_free_result($res);
    $res = mysql_query($sql, df_db());
    if (!$res) {
        return PEAR::raiseError("Could not write config value: " . mysql_error(df_db()));
    }
    return true;
}
Exemple #12
0
 public static function q($sql)
 {
     if (is_array($sql)) {
         $res = null;
         foreach ($sql as $q) {
             $res = self::q($q);
         }
         return $res;
     } else {
         $res = mysql_query($sql, df_db());
         if (!$res) {
             throw new Exception(mysql_error(df_db()));
         }
         return $res;
     }
 }
Exemple #13
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $mt =& Dataface_ModuleTool::getInstance();
     $mod =& $mt->loadModule('modules_DataGrid');
     if (PEAR::isError($mod)) {
         return $mod;
     }
     $res = mysql_query("select gridID,gridName from dataface__DataGrids where tableName='" . addslashes($query['-table']) . "'", df_db());
     $grids = array();
     while ($row = mysql_fetch_assoc($res)) {
         $grids[$row['gridID']] = array('name' => $row['gridName'], 'url' => $app->url('-gridid=' . $row['gridID'] . '&-action=DataGrid_view'));
     }
     //print_r($grids);
     df_register_skin('DataGrid', DATAFACE_PATH . '/modules/DataGrid/templates');
     df_display(array('grids' => $grids), 'DataGrid/list.html');
 }
Exemple #14
0
 function handle(&$params)
 {
     $res = xf_db_query("show tables like 'dataface__view_%'", df_db());
     $views = array();
     while ($row = xf_db_fetch_row($res)) {
         $views[] = $row[0];
     }
     if ($views) {
         $sql = "drop view `" . implode('`,`', $views) . "`";
         echo $sql;
         echo "<br/>";
         $res = xf_db_query("drop view `" . implode('`,`', $views) . "`", df_db());
         if (!$res) {
             throw new Exception(xf_db_error(df_db()));
         }
     }
     echo "done";
 }
Exemple #15
0
 function saveDataGrid($grid)
 {
     if ($grid->id) {
         $idName = 'gridID,';
         $idVal = "'" . addslashes($grid->id) . "',";
     } else {
         $idName = '';
         $idVal = '';
     }
     $sql = "replace into dataface__DataGrids \n\t\t\t(" . $idName . "gridName,gridData,tableName)\n\t\t\tvalues\n\t\t\t(" . $idVal . "'" . addslashes($grid->name) . "',\n\t\t\t'" . addslashes(serialize($grid)) . "',\n\t\t\t'" . addslashes($grid->tableName) . "')";
     $res = mysql_query($sql, df_db());
     if (!$res) {
         trigger_error(mysql_error(df_db()), E_USER_ERROR);
     }
     if (!$grid->id) {
         $grid->id = mysql_insert_id(df_db());
         return $this->saveDataGrid($grid);
     }
     return true;
 }
Exemple #16
0
 function afterCopy(Dataface_Record $orig, Dataface_Record $copy)
 {
     $rand = md5(rand(0, 1000000));
     $copytable = 'copy_' . $rand;
     $res = xf_db_query("create temporary table `{$copytable}` select * from formula_ingredients where formula_id='" . addslashes($orig->val('formula_id')) . "'", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
     $res = xf_db_query("update `{$copytable}` set formula_id='" . addslashes($copy->val('formula_id')) . "'", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
     $res = xf_db_query("insert into formula_ingredients select * from `{$copytable}`", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
     $res = xf_db_query("drop table `{$copytable}`", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
 }
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $context = array();
     if (!is_array(@$app->_conf['_output_cache']) or !@$app->_conf['_output_cache']['enabled']) {
         $context['enabled'] = false;
         //return PEAR::raiseError('The output cache is currently disabled.  You can enable it by adding an [_output_cache] section to your conf.ini file with a value \'enabled=1\'');
     } else {
         $context['enabled'] = true;
     }
     if (@$_POST['--clear-cache']) {
         // We should clear the cache
         @xf_db_query("delete from `__output_cache`", df_db());
         $app->redirect($app->url('') . '&--msg=' . urlencode('The output cache has been successfully cleared.'));
     }
     $res = xf_db_query("select count(*) from `__output_cache`", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
     }
     list($numrows) = xf_db_fetch_row($res);
     $context['numrows'] = $numrows;
     df_display($context, 'manage_output_cache.html');
 }
 function handle($params)
 {
     $query = Dataface_Application::getInstance()->getQuery();
     if (!isset($query['website_id'])) {
         throw new Exception("No site id provided");
     }
     $site = df_get_record('websites', array('website_id' => '=' . $query['website_id']));
     if (!$site->checkPermission('view')) {
         throw new Exception("No permission to perform action");
     }
     import('Dataface/ResultReader.php');
     $reader = new Dataface_ResultReader("select\n\t\t\tws.source_language,\n\t\t\tws.target_language,\n\t\t\tws.log_translation_misses,\n\t\t\tws.website_id, \n\t\t\tws.website_name,\n\t\t\tws.website_url,\n\t\t\tws.translation_memory_id,\n\t\t\tconcat('http://',ws.host,ws.base_path) as proxy_url,\n\t\t\tws.source_language,\n\t\t\tws.target_language,\n\t\t\t(\n\t\t\t\tselect count(*) from webpages w where w.website_id=ws.website_id\n\t\t\t) as numpages,\n\t\t\t(\n\t\t\t\tselect count(*) from swete_strings tml where tml.website_id=ws.website_id\n\t\t\t) as numphrases,\n\t\t\tifnull((\n\t\t\t\tselect sum(tml.num_words) from xf_tm_strings xts \n\t\t\t\t\tinner join swete_strings tml on tml.string_id=xts.string_id\n\t\t\t\twhere tml.website_id=ws.website_id\n\t\t\t), 0) as numwords,\n\t\t\t(\n\t\t\t\tselect count(*) from swete_strings tml\n\t\t\t\t\tinner join websites ws2 on ws2.website_id=tml.website_id\n\t\t\t\t\tinner join xf_tm_translation_memory_strings xttms on xttms.translation_memory_id=ws2.translation_memory_id and xttms.string_id=tml.string_id\n\t\t\t\twhere xttms.current_translation_id is not null\n\t\t\t\t \tand tml.website_id=ws.website_id\n\t\t\t\t\n\t\t\t) as translated_phrases,\n\t\t\t\n\t\t\tifnull((\n\t\t\t\tselect sum(tml.num_words) from swete_strings tml\n\t\t\t\t\tinner join websites ws2 on ws2.website_id=tml.website_id\n\t\t\t\t\tinner join xf_tm_translation_memory_strings xttms on xttms.translation_memory_id=ws2.translation_memory_id and xttms.string_id=tml.string_id\n\t\t\t\t\tinner join xf_tm_strings xts on xttms.string_id=xts.string_id\n\t\t\t\twhere xttms.current_translation_id is not null\n\t\t\t\t\tand tml.website_id=ws.website_id\n\t\t\t\t\t\n\t\t\t), 0) as translated_words\n\t\t\t\n\t\t\t\t\n\t\t\tfrom websites ws where website_id='" . addslashes($query['website_id']) . "'\n\t\t\t", df_db());
     $results = array();
     //$languages = Dataface_Table::loadTable('websites')->getValuelist('languages');
     foreach ($reader as $row) {
         $results[] = $row;
         $row->untranslated_words = $row->numwords - $row->translated_words;
         $row->untranslated_phrases = $row->numphrases - $row->translated_phrases;
         //$row->source_label = @$languages[$row->source_language] ? $languages[$row->source_language] : $row->source_language;
         //$row->target_label = @$languages[$row->target_language] ? $languages[$row->target_language] : $row->target_language;
     }
     df_display(array('results' => $results), 'swete/actions/dashboard_site_stats.html');
 }
Exemple #19
0
 function df_q($sql)
 {
     if (is_array($sql)) {
         foreach ($sql as $q) {
             $res = df_q($q);
         }
         return $res;
     } else {
         $res = xf_db_query($sql, df_db());
         if (!$res) {
             error_log("Error executing SQL: {$sql}");
             error_log(xf_db_error(df_db()));
             throw new Exception(xf_db_error(df_db()));
         }
         return $res;
     }
 }
Exemple #20
0
 /**
  * Returns the name of the VIEW to be used for reading records from the database.
  * This feature is new in version 1.2 and is intended to improve performance
  * by NOT using subqueries to implement support for __sql__ parameters on tables.
  * We'll see if this makes a big difference to mysql.
  *
  * This method will return the name of the view to be used.  If no custom SQL has
  * been defined this will return null.  If mysql doesn't support views, this will
  * return null.
  *
  * @return string
  */
 function getProxyView()
 {
     if (defined('XATAFACE_DISABLE_PROXY_VIEWS') and XATAFACE_DISABLE_PROXY_VIEWS) {
         return null;
     }
     $sql = $this->sql();
     // If there is no custom SQL then there is no point using a view at all
     if (!$sql) {
         return null;
     }
     $sqlKey = md5($sql);
     $viewName = 'dataface__view_' . $this->tablename . '_' . $sqlKey;
     if (isset($this->_proxyViews[$viewName]) and $this->_proxyViews[$viewName]) {
         return $viewName;
     } else {
         if (isset($this->_proxyViews[$viewName]) and !$this->_proxyViews[$viewName]) {
             return null;
         }
     }
     if (Dataface_Application::getInstance()->getMySQLMajorVersion() < 5) {
         $this->_proxyViews[$viewName] = false;
         return null;
     }
     if (@$this->app->_conf['multilingual_content'] and $this->getTranslations()) {
         $this->_proxyViews[$viewName] = false;
         return null;
     }
     // Check if view already exists
     $res = mysql_query("show table status like '" . addslashes($viewName) . "'", df_db());
     if (!$res) {
         throw new Exception(mysql_error(df_db()));
     }
     if (mysql_num_rows($res) < 1) {
         @mysql_free_result($res);
         // The view doesn't exist yet
         $res = mysql_query("create view `" . str_replace('`', '', $viewName) . "` as " . $sql, df_db());
         if (!$res) {
             error_log(mysql_error(df_db()));
             $this->_proxyViews[$viewName] = false;
             return null;
         }
     } else {
         @mysql_free_result($res);
     }
     $this->_proxyViews[$viewName] = true;
     return $viewName;
 }
Exemple #21
0
 /**
  * @brief Builds an HTML_QuickForm object to edit the given record.
  * @param Dataface_Record &$record The record that is to be edited.
  *
  * @param string $tab The name of the tab to display.  In the case of multi
  *			tab forms, we may specify the tab which we wish to display.
  *			the tab may contain only a subset of the fields in the table,
  *			or it could be a 'partition' tab.  A 'partition' tab.
  */
 function createRecordForm($record, $new = false, $tab = null, $query = null, $fields = null)
 {
     if (!$record) {
         throw new Exception("Cannot create record form for null record");
     }
     $table =& $record->_table;
     if (!$table) {
         throw new Exception("Could not find table " . $record->_table->tablename);
     }
     if ($table->hasJoinTable($tab, $record)) {
         $query['--tab'] = null;
         $jrecord = $record->getJoinRecord($tab, true);
         if (!isset($jrecord)) {
             $new = true;
         } else {
             $new = false;
         }
         $form = $this->createRecordForm($record->getJoinRecord($tab), $new, null, $query, $fields);
         $form->overrideNoQuery = true;
         return $form;
     } else {
         // TO DO:  Finish this method
         $form = new Dataface_QuickForm($table->tablename, df_db(), $query, '', $new, $fields);
         $form->_record =& $record;
         $form->tab = $tab;
         return $form;
     }
 }
Exemple #22
0
 function rollbackTransaction()
 {
     return xf_db_query('rollback', df_db());
 }
Exemple #23
0
    function getResultFilters()
    {
        ob_start();
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        echo '<div class="resultlist-filters">
		<h3>' . df_translate('scripts.Dataface_ResultList.MESSAGE_FILTER_RESULTS', 'Filter Results') . ':</h3>
		<script language="javascript"><!--
		
		function resultlist__updateFilters(col,select){
			var currentURL = "' . $app->url('') . '";
			var currentParts = currentURL.split("?");
			var currentQuery = "?"+currentParts[1];
			var value = select.options[select.selectedIndex].value;
			var regex = new RegExp(\'([?&])\'+col+\'={1,2}[^&]*\');
			if ( currentQuery.match(regex) ){
				if ( value ){
					prefix = "=";
				} else {
					prefix = "";
				}
				currentQuery = currentQuery.replace(regex, \'$1\'+col+\'=\'+prefix+encodeURIComponent(value));
			} else {
				currentQuery += \'&\'+col+\'==\'+encodeURIComponent(value);
			}
			window.location=currentParts[0]+currentQuery;
		}
		//--></script>
		<ul>';
        $qb = new Dataface_QueryBuilder($this->_table->tablename, $query);
        foreach ($this->_filterCols as $col) {
            $field =& $this->_table->getField($col);
            unset($vocab);
            if (isset($field['vocabulary'])) {
                $vocab =& $this->_table->getValuelist($field['vocabulary']);
            } else {
                $vocab = null;
            }
            echo '<li> ' . htmlspecialchars($field['widget']['label']) . ' <select onchange="resultlist__updateFilters(\'' . addslashes($col) . '\', this);"><option value="">' . df_translate('scripts.GLOBAL.LABEL_ALL', 'All') . '</option>';
            $res = df_query("select `{$col}`, count(*) as `num` " . $qb->_from() . " " . $qb->_secure($qb->_where(array($col => null))) . " group by `{$col}`", null, true);
            if (!$res and !is_array($res)) {
                trigger_error(mysql_error(df_db()), E_USER_ERROR);
            }
            if (@$query[$col] and $query[$col][0] == '=') {
                $queryColVal = substr($query[$col], 1);
            } else {
                $queryColVal = @$query[$col];
            }
            //while ( $row = mysql_fetch_assoc($res) ){
            foreach ($res as $row) {
                if (isset($vocab) and isset($vocab[$row[$col]])) {
                    $val = $vocab[$row[$col]];
                } else {
                    $val = $row[$col];
                }
                if ($queryColVal == $row[$col]) {
                    $selected = ' selected';
                } else {
                    $selected = '';
                }
                echo '<option value="' . htmlspecialchars($row[$col]) . '"' . $selected . '>' . htmlspecialchars($val) . ' (' . $row['num'] . ')</option>';
            }
            //@mysql_free_result($res);
            echo '</select></li>';
        }
        echo '</ul></div>';
        $out = ob_get_contents();
        ob_end_clean();
        return $out;
    }
Exemple #24
0
 function delete_request_with_uuid($uuid)
 {
     $table = self::$TABLE_RESET_PASSWORD;
     $res = xf_db_query("delete from `{$table}` where request_uuid='" . addslashes($uuid) . "' limit 1", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     }
 }
Exemple #25
0
 /**
  * 
  * @param array $columns
  * @return type
  * @throws Exception@brief Load the totals for the current found set using MySQL's aggregate 
  * operators.  This method will always query the database directly (no caching).  
  * 
  * <p>This method was developed to make it easier to create "totals" rows in the 
  *    list view.</p>
  * 
  * <h3>Example</h3>
  * 
  * @code
  * $resultSet = Dataface_Application::getInstance()->getResultSet();
  * $results = $resultSet->loadTotals(array(
  *    'age#avg',
  *    'age#std',
  *    'income#sum'
  * ));
  * print_r($results);
  * @endcode
  * 
  * <p>Output:</p>
  * 
  * @code
  * array(
  *    'age_AVG' => 74.4,
  *    'age_STD' => 13.2,
  *    'income_SUM' => 100567
  * );
  * @endcode
  * 
  * @param array $columns A list of strings of the form {fieldname}#{operator} where 
  *  where {fieldname} is the name of a field and {operator} is the name of an operator
  *  to apply to the field.
  * 
  * <h3>Available Operators</h3>
  * <table>
  *    <tr>
  *     <th>Operator</th><th>Description</th>
  *    </tr>
  *    <tr>
  *       <td>sum</td><td>The sum of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>avg</td><td>The average value of field in result set.</td>
  *    <tr>
  *       <td>max</td><td>The max value of field in result set.</td>
  *    </tr>
  *    <tr>
  *       <td>min</td><td>The minimum value of field result set.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_and</td><td>Result of bitwise AND on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_or</td><td>Result of bitwise OR on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_xor</td><td>Result of bitwise XOR on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>group_concat</td><td>The concatenation of all rows in found set for field.  Joined with a comma.</td>
  *    </tr>
  *    <tr>
  *       <td>std</td><td>Population Standard deviation of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>stddev_samp</td><td>Sample Standard deviation of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>stddev_pop</td><td>Same as stddev</td>
  *    </tr>
  *    <tr>
  *       <td>var_pop<td><td>Population standard variance for field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>var_samp</td><td>Sample standard deviation for field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>variance</td><td>Same as var_pop</td>
  *    </tr>
  * </table>
  * 
  *    
  * @return Associative array where the keys have the form {fieldname}_{operator|uppercase} and the values
  *  are the corresponding result of the operator on that field.  E.g. If your input was array('field1#sum', 'field2#avg')
  *  the output woult be array('field1_SUM' => {some number}, 'field2_AVG' => {some_number})
  * 
  * @since 2.0.4
  * @see Dataface_QueryBuilder::select_totals()
  */
 function loadTotals($columns = array())
 {
     $builder = new Dataface_QueryBuilder($this->_tablename, $this->_query);
     $sql = $builder->select_totals(array(), null, $columns);
     $res = df_query($sql);
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     } else {
         $out = xf_db_fetch_assoc($res);
         @xf_db_free_result($res);
         return $out;
     }
 }
Exemple #26
0
 function update_3446()
 {
     $sql[] = "INSERT INTO `user_roles` VALUES \n    \t\t(1,'USER','USER'),(2,'TRANSLATOR','TRANSLATOR'),(3,'ADMIN','ADMIN');";
     foreach ($sql as $q) {
         mysql_query($q, df_db());
     }
 }
Exemple #27
0
 /**
  * Returns an array of history ids of history records that match the 
  * given query.
  */
 function findMatchingSnapshots($record, $query, $idsOnly = true)
 {
     $app =& Dataface_Application::getInstance();
     $htablename = $record->_table->tablename . '__history';
     if (!Dataface_Table::tableExists($htablename)) {
         return array();
     }
     $keys = $record->strvals(array_keys($record->_table->keys()));
     foreach ($keys as $key => $val) {
         $query[$key] = '=' . $val;
     }
     if ($idsOnly) {
         $qbuilder = new Dataface_QueryBuilder($htablename, $query);
         $sql = $qbuilder->select(array('history__id'), $query);
         $res = xf_db_query($sql, df_db());
         $ids = array();
         while ($row = xf_db_fetch_row($res)) {
             $ids[] = $row[0];
         }
         @xf_db_free_result($res);
         return $ids;
     } else {
         return df_get_records_array($htablename, $query);
     }
 }
Exemple #28
0
 function handle(&$params)
 {
     $app = Dataface_Application::getInstance();
     if (!isset($_GET['code'])) {
         // We need this parameter or we can do nothing.
         return PEAR::raiseError(df_translate('actions.activate.MESSAGE_MISSING_CODE_PARAMETER', 'The code parameter is missing from your request.  Validation cannot take place.  Please check your url and try again.'), DATAFACE_E_ERROR);
     }
     // Step 0:  Find out what the redirect URL will be
     // We accept --redirect markers to specify which page to redirect
     // to after we're done.  This will usually be the page that the
     // user was on before they went to the login page.
     if (isset($_SESSION['--redirect'])) {
         $url = $_SESSION['--redirect'];
     } else {
         if (isset($_SESSION['-redirect'])) {
             $url = $_SESSION['-redirect'];
         } else {
             if (isset($_REQUEST['--redirect'])) {
                 $url = $_REQUEST['--redirect'];
             } else {
                 if (isset($_REQUEST['-redirect'])) {
                     $url = $_REQUEST['-redirect'];
                 } else {
                     $url = $app->url('-action=' . $app->_conf['default_action']);
                 }
             }
         }
     }
     if (strpos($url, '?') === false) {
         $url .= '?';
     }
     // Step 1: Delete all registrations older than time limit
     $time_limit = 24 * 60 * 60;
     // 1 day
     if (isset($params['time_limit'])) {
         $time_limit = intval($params['time_limit']);
     }
     $res = xf_db_query("delete from dataface__registrations \n\t\t\t\twhere registration_date < '" . addslashes(date('Y-m-d H:i:s', time() - $time_limit)) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to delete registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     // Step 2: Load the specified registration information
     $res = xf_db_query("select registration_data from dataface__registrations\n\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
     if (!$res) {
         error_log(xf_db_error(df_db()));
         throw new Exception("Failed to load registration information due to an SQL error.  See error log for details.", E_USER_ERROR);
     }
     if (xf_db_num_rows($res) == 0) {
         // We didn't find any records matching the prescribed code, so
         // we redirect the user to their desired page and inform them
         // that the registration didn't work.
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_NOT_FOUND', 'No registration information could be found to match this code.  Please try registering again.');
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
     // Step 3: Check to make sure that there are no other users with the
     // same name.
     list($raw_data) = xf_db_fetch_row($res);
     $values = unserialize($raw_data);
     $appdel = $app->getDelegate();
     if (isset($appdel) and method_exists($appdel, 'validateRegistrationForm')) {
         $res = $appdel->validateRegistrationForm($values);
         if (PEAR::isError($res)) {
             $msg = $res->getMessage();
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     } else {
         $res = xf_db_query("select count(*) from \n\t\t\t\t`" . str_replace('`', '', $app->_conf['_auth']['users_table']) . "` \n\t\t\t\twhere `" . str_replace('`', '', $app->_conf['_auth']['username_column']) . "` = '" . addslashes($values[$app->_conf['_auth']['username_column']]) . "'\n\t\t\t\t", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to find user records due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         list($num) = xf_db_fetch_row($res);
         if ($num > 0) {
             $msg = df_translate('actions.activate.MESSAGE_DUPLICATE_USER', 'Registration failed because a user already exists by that name.  Try registering again with a different name.');
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     }
     // Step 4: Save the registration data and log the user in.
     $record = new Dataface_Record($app->_conf['_auth']['users_table'], array());
     $record->setValues($values);
     $res = $record->save();
     if (PEAR::isError($res)) {
         $app->redirect($url . '&--msg=' . urlencode($res->getMessage()));
     } else {
         $res = xf_db_query("delete from dataface__registrations\n\t\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db());
         if (!$res) {
             error_log(xf_db_error(df_db()));
             throw new Exception("Failed to clean up old registrations due to an SQL error.  See error log for details.", E_USER_ERROR);
         }
         $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_COMPLETE', 'Registration complete.  You are now logged in.');
         $_SESSION['UserName'] = $record->strval($app->_conf['_auth']['username_column']);
         import('Dataface/Utilities.php');
         Dataface_Utilities::fireEvent('after_action_activate', array('record' => $record));
         $app->redirect($url . '&--msg=' . urlencode($msg));
     }
 }
Exemple #29
0
 /**
  * Returns the application version in the database.
  * @return int The version number in the database.
  */
 function df_get_database_version($db = null)
 {
     if (!$db) {
         $db = df_db();
     }
     static $version = -1;
     if ($version == -1) {
         $sql = "select `version` from dataface__version limit 1";
         $res = @mysql_query($sql, $db);
         if (!$res) {
             $res = mysql_query("create table dataface__version ( `version` int(5) not null default 0)", $db);
             if (!$res) {
                 trigger_error(mysql_error($db), E_USER_ERROR);
             }
             //$fs_version = df_get_file_system_version();
             $res = mysql_query("insert into dataface__version values ('0')", $db);
             if (!$res) {
                 trigger_error(mysql_error($db), E_USER_ERROR);
             }
             $res = mysql_query($sql, $db);
             if (!$res) {
                 trigger_error(mysql_error($db), E_USER_ERROR);
             }
         }
         list($version) = mysql_fetch_row($res);
     }
     return $version;
 }
Exemple #30
0
 /**
  * @brief Updates a module so that the database version is the same
  * as the file system version.
  * @param string $modname The name of the module.
  * @param string $path The path to the module.
  */
 public function updateModule($modname, $path)
 {
     $installpath = dirname($path) . DIRECTORY_SEPARATOR . 'installer.php';
     if (file_exists($installpath)) {
         import($installpath);
         $classname = $modname . '_installer';
         $installer = new $classname();
         $methods = get_class_methods($classname);
         $methods = preg_grep('/^update_([0-9]+)$/', $methods);
         $updates = array();
         $fsversion = $this->getFsVersion($modname, $path);
         $dbversion = $this->getDbVersion($modname);
         foreach ($methods as $method) {
             preg_match('/^update_([0-9]+)$/', $method, $matches);
             $version = intval($matches[1]);
             if ($version > $dbversion and $version <= $fsversion) {
                 $updates[] = $version;
             }
         }
         sort($updates);
         if ($dbversion == 0) {
             $res = xf_db_query("insert into dataface__modules (module_name,module_version)\n\t\t\t\t\tvalues ('" . addslashes($modname) . "',-1)", df_db());
             if (!$res) {
                 throw new Exception(xf_db_error(df_db()));
             }
         }
         foreach ($updates as $update) {
             $method = 'update_' . $update;
             $res = $installer->{$method}();
             if (PEAR::isError($res)) {
                 return $res;
             }
             $res = xf_db_query("update dataface__modules set `module_version`='" . addslashes($update) . "'", df_db());
             if (!$res) {
                 throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
             }
         }
         $res = xf_db_query("update dataface__modules set `module_version`='" . addslashes($fsversion) . "'", df_db());
         if (!$res) {
             throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
         }
     }
 }