/**
 * Connect to the database server and select the database.
 * @param array $config the db configuration parameters
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($config, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_details;
    $_zp_DB_details = unserialize(DB_NOT_CONNECTED);
    if (function_exists('mysqli_connect')) {
        $_zp_DB_connection = @mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass']);
    } else {
        $_zp_DB_connection = NULL;
    }
    if (!$_zp_DB_connection) {
        if ($errorstop) {
            zp_error(gettext('MySQLi Error: Zenphoto could not instantiate a connection.'));
        }
        return false;
    }
    $_zp_DB_details['mysql_host'] = $config['mysql_host'];
    if (!$_zp_DB_connection->select_db($config['mysql_database'])) {
        if ($errorstop) {
            zp_error(sprintf(gettext('MySQLi Error: MySQLi returned the error %1$s when Zenphoto tried to select the database %2$s.'), $_zp_DB_connection->error, $config['mysql_database']));
        }
        return false;
    }
    $_zp_DB_details = $config;
    if (array_key_exists('UTF-8', $config) && $config['UTF-8']) {
        $_zp_DB_connection->set_charset("utf8");
    }
    // set the sql_mode to relaxed (if possible)
    @$_zp_DB_connection->query('SET SESSION sql_mode="";');
    return $_zp_DB_connection;
}
/**
 * Connect to the database server and select the database.
 * @param array $config the db configuration parameters
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($config, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_details;
    $_zp_DB_details = unserialize(DB_NOT_CONNECTED);
    if (function_exists('mysql_connect')) {
        $_zp_DB_connection = @mysql_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass']);
    } else {
        $_zp_DB_connection = NULL;
    }
    if (!$_zp_DB_connection) {
        if ($errorstop) {
            zp_error(sprintf(gettext('MySQL Error: ZenPhoto20 received the error %s when connecting to the database server.'), mysql_error()));
        }
        return false;
    }
    $_zp_DB_details['mysql_host'] = $config['mysql_host'];
    if (!@mysql_select_db($config['mysql_database'])) {
        if ($errorstop) {
            zp_error(sprintf(gettext('MySQL Error: MySQL returned the error %1$s when ZenPhoto20 tried to select the database %2$s.'), mysql_error(), $config['mysql_database']));
        }
        return false;
    }
    $_zp_DB_details = $config;
    if (array_key_exists('UTF-8', $config) && $config['UTF-8']) {
        mysql_set_charset('utf8', $_zp_DB_connection);
    }
    // set the sql_mode to relaxed (if possible)
    @mysql_query('SET SESSION sql_mode="";');
    return $_zp_DB_connection;
}
Beispiel #3
0
/**
 * Connect to the database server and select the database.
 * @param array $config the db configuration parameters
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($config, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_details;
    $_zp_DB_details = unserialize(DB_NOT_CONNECTED);
    $_zp_DB_connection = NULL;
    if ($errorstop) {
        zp_error(gettext('MySQLi Error: Zenphoto could not instantiate a connection.'));
    }
    return false;
    return $_zp_DB_connection;
}
/**
 * The main query function. Runs the SQL on the connection and handles errors.
 * @param string $sql sql code
 * @param bool $noerrmsg set to false to supress the error message
 * @return results of the sql statements
 * @since 0.6
 */
function query($sql, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_conf_vars;
    if (is_null($_zp_DB_connection)) {
        db_connect();
    }
    // Changed this to mysql_query - *never* call query functions recursively...
    $result = mysql_query($sql, $_zp_DB_connection);
    if (!$result) {
        if ($errorstop) {
            $sql = html_encode($sql);
            zp_error(sprintf(gettext('MySQL Query ( <em>%1$s</em> ) failed. MySQL returned the error <em>%2$s</em>'), $sql, mysql_error()));
        }
        return false;
    }
    return $result;
}
Beispiel #5
0
 function __construct()
 {
     global $_configMutex, $_zp_conf_vars;
     $_configMutex->lock();
     $zp_cfg = file_get_contents(SERVERPATH . '/' . DATA_FOLDER . '/' . CONFIGFILE);
     $i = strpos($zp_cfg, "\$conf['special_pages']");
     $j = strpos($zp_cfg, '//', $i);
     if ($i === false || $j === false) {
         $conf = array('special_pages' => array());
         $this->conf_vars = $conf['special_pages'];
         $i = strpos($zp_cfg, '/** Do not edit below this line. **/');
         if ($i === false) {
             zp_error(gettext('The Zenphoto configuration file is corrupt. You will need to restore it from a backup.'));
         }
         $this->zp_cfg_a = substr($zp_cfg, 0, $i);
         $this->zp_cfg_b = "//\n" . substr($zp_cfg, $i);
     } else {
         $this->zp_cfg_a = substr($zp_cfg, 0, $i);
         $this->zp_cfg_b = substr($zp_cfg, $j);
         eval(substr($zp_cfg, $i, $j - $i));
         $this->conf_vars = $conf['special_pages'];
         foreach ($_zp_conf_vars['special_pages'] as $page => $element) {
             if (isset($element['option'])) {
                 $this->plugin_vars[$page] = $element;
             }
         }
     }
     if (OFFSET_PATH == 2) {
         $old = array_keys($conf['special_pages']);
         $zp_cfg = file_get_contents(SERVERPATH . '/' . ZENFOLDER . '/zenphoto_cfg.txt');
         $i = strpos($zp_cfg, "\$conf['special_pages']");
         $j = strpos($zp_cfg, '//', $i);
         eval(substr($zp_cfg, $i, $j - $i));
         $new = array_keys($conf['special_pages']);
         if ($old != $new) {
             //Things have changed, need to reset to defaults;
             setOption('rewriteTokens_restore', 1);
             $this->handleOptionSave(NULL, NULL);
             setupLog(gettext('rewriteTokens restored to default'), true);
         }
     } else {
         enableExtension('rewriteTokens', 97 | ADMIN_PLUGIN);
         //	plugin must be enabled for saving options
     }
 }
/**
 * The main query function. Runs the SQL on the connection and handles errors.
 * @param string $sql sql code
 * @param bool $noerrmsg set to false to supress the error message
 * @return results of the sql statements
 * @since 0.6
 */
function query($sql, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_last_result, $_zp_conf_vars;
    if ($_zp_DB_connection == null) {
        db_connect();
    }
    $_zp_DB_last_result = false;
    try {
        $_zp_DB_last_result = $_zp_DB_connection->query($sql);
        return $_zp_DB_last_result;
    } catch (PDOException $e) {
        $_zp_DB_last_result = $e;
        if (true || $noerrmsg) {
            zp_error(sprintf(gettext('%1$s Error: Zenphoto received the error <em>%2$s</em> from the database server.'), DATABASE_SOFTWARE, $e->getMessage()));
        }
        return false;
    }
}
/**
 * Connect to the database server and select the database.
 * @param array $config the db configuration parameters
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($config, $errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_details, $_zp_DB_last_result;
    $_zp_DB_details = unserialize(DB_NOT_CONNECTED);
    $_zp_DB_connection = $_zp_DB_last_result = NULL;
    if (array_key_exists('UTF-8', $config) && $config['UTF-8']) {
        $utf8 = ';charset=utf8';
    } else {
        $utf8 = false;
    }
    try {
        $db = $config['mysql_database'];
        $hostname = $config['mysql_host'];
        $username = $config['mysql_user'];
        $password = $config['mysql_pass'];
        if (class_exists('PDO')) {
            $_zp_DB_connection = new PDO("mysql:host={$hostname};dbname={$db}{$utf8}", $username, $password);
        }
    } catch (PDOException $e) {
        $_zp_DB_last_result = $e;
        if ($errorstop) {
            zp_error(sprintf(gettext('MySql Error: Zenphoto received the error %s when connecting to the database server.'), $e->getMessage()));
        }
        $_zp_DB_connection = NULL;
        return false;
    }
    $_zp_DB_details = $config;
    if ($utf8 && version_compare(PHP_VERSION, '5.3.6', '<')) {
        try {
            $_zp_DB_connection->query("SET NAMES 'utf8'");
        } catch (PDOException $e) {
            //	:(
        }
    }
    // set the sql_mode to relaxed (if possible)
    try {
        $_zp_DB_connection->query('SET SESSION sql_mode="";');
    } catch (PDOException $e) {
        //	What can we do :(
    }
    return $_zp_DB_connection;
}
Beispiel #8
0
/**
 * Updates an item in the configuration file
 * @param unknown_type $item
 * @param unknown_type $value
 * @param unknown_type $quote
 */
function updateConfigItem($item, $value, $zp_cfg, $quote = true)
{
    if ($quote) {
        $value = '"' . $value . '"';
    }
    $i = strpos($zp_cfg, $item);
    if ($i === false) {
        $parts = preg_split('~\\/\\*.*Do not edit below this line.*\\*\\/~', $zp_cfg);
        if (isset($parts[1])) {
            $zp_cfg = $parts[0] . "\$conf['" . $item . "'] = " . $value . ";\n/** Do not edit below this line. **/" . $parts[1];
        } else {
            zp_error(gettext('The Zenphoto configuration file is corrupt. You will need to restore it from a backup.'));
        }
    } else {
        $i = strpos($zp_cfg, '=', $i);
        $j = strpos($zp_cfg, "\n", $i);
        $zp_cfg = substr($zp_cfg, 0, $i) . '= ' . $value . ';' . substr($zp_cfg, $j);
    }
    return $zp_cfg;
}
Beispiel #9
0
 /**
  * Constructor for class-video
  *
  * @param object &$album the owning album
  * @param sting $filename the filename of the image
  * @return Image
  */
 function __construct($album, $filename, $quiet = false)
 {
     global $_zp_supported_images;
     $msg = false;
     if (!is_object($album) || !$album->exists) {
         $msg = gettext('Invalid video instantiation: Album does not exist');
     } else {
         if (!$this->classSetup($album, $filename) || !file_exists($this->localpath) || is_dir($this->localpath)) {
             $msg = gettext('Invalid video instantiation: file does not exist.');
         }
     }
     if ($msg) {
         $this->exists = false;
         if (!$quiet) {
             zp_error($msg, E_USER_WARNING);
         }
         return;
     }
     $alts = explode(',', extensionEnabled('class-video_videoalt'));
     foreach ($alts as $alt) {
         $this->videoalt[] = trim(strtolower($alt));
     }
     $this->sidecars = $_zp_supported_images;
     $this->video = true;
     $this->objectsThumb = checkObjectsThumb($this->localpath);
     // This is where the magic happens...
     $album_name = $album->name;
     $this->updateDimensions();
     $new = $this->instantiate('images', array('filename' => $filename, 'albumid' => $this->album->getID()), 'filename', true, empty($album_name));
     if ($new || $this->filemtime != $this->get('mtime')) {
         if ($new) {
             $this->setTitle($this->displayname);
         }
         $this->updateMetaData();
         $this->set('mtime', $this->filemtime);
         $this->save();
         if ($new) {
             zp_apply_filter('new_image', $this);
         }
     }
 }
/**
 * Connect to the database server and select the database.
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_last_result, $_zp_conf_vars;
    $_zp_DB_last_result = NULL;
    $db = $_zp_conf_vars['mysql_database'];
    if (!is_array($_zp_conf_vars)) {
        if ($errorstop) {
            zp_error(gettext('The <code>$_zp_conf_vars</code> variable is not an array. Zenphoto has not been instantiated correctly.'));
        }
        return false;
    }
    try {
        $hostname = $_zp_conf_vars['mysql_host'];
        $username = $_zp_conf_vars['mysql_user'];
        $password = $_zp_conf_vars['mysql_pass'];
        $_zp_DB_connection = new PDO("mysql:host={$hostname};dbname={$db}", $username, $password);
    } catch (PDOException $e) {
        $_zp_DB_last_result = $e;
        if ($errorstop) {
            zp_error(sprintf(gettext('MySql Error: Zenphoto received the error <em>%s</em> when connecting to the database server.'), $e->getMessage()));
        }
        return false;
    }
    if (array_key_exists('UTF-8', $_zp_conf_vars) && $_zp_conf_vars['UTF-8']) {
        try {
            $_zp_DB_connection->query("SET NAMES 'utf8'");
        } catch (PDOException $e) {
            //	:(
        }
    }
    // set the sql_mode to relaxed (if possible)
    try {
        $_zp_DB_connection->query('SET SESSION sql_mode="";');
    } catch (PDOException $e) {
        //	What can we do :(
    }
    return $_zp_DB_connection;
}
/**
 * Connect to the database server and select the database.
 * @param bool $errorstop set to false to omit error messages
 * @return true if successful connection
 */
function db_connect($errorstop = true)
{
    global $_zp_DB_connection, $_zp_DB_last_result, $_zp_conf_vars;
    $_zp_DB_last_result = NULL;
    $db = $_zp_conf_vars['mysql_database'];
    if (!is_array($_zp_conf_vars)) {
        if ($errorstop) {
            zp_error(gettext('The <code>$_zp_conf_vars</code> variable is not an array. Zenphoto has not been instantiated correctly.'));
        }
        return false;
    }
    if (empty($folder) || $folder == 'localhost') {
        $folder = dirname(dirname(__FILE__)) . '/zp-data/';
    } else {
        $folder = str_replace($_zp_conf_vars['mysql_host'], '\\', '/');
        if (substr($folder, -1, 1) != '/') {
            $folder .= '/';
        }
    }
    try {
        $_zp_DB_connection = new PDO('sqlite:' . $folder . $_zp_conf_vars['mysql_database']);
    } catch (PDOException $e) {
        $_zp_DB_last_result = $e;
        if ($errorstop) {
            zp_error(sprintf(gettext('SQLite Error: Zenphoto received the error <em>%s</em> when connecting to the database server.'), $e->getMessage()));
        }
        return false;
    }
    try {
        $_zp_DB_connection->query('PRAGMA encoding = "UTF-8"');
    } catch (PDOException $e) {
        if (true || $noerrmsg) {
            zp_error(sprintf(gettext('%1$s Error: Zenphoto received the error <em>%2$s</em> from the database server.'), DATABASE_SOFTWARE, $e->getMessage()));
        }
        return false;
    }
    return $_zp_DB_connection;
}
/**
 * The main query function. Runs the SQL on the connection and handles errors.
 * @param string $sql sql code
 * @param bool $noerrmsg set to true to supress the error message
 * @return results of the sql statements
 * @since 0.6
 */
function query($sql, $noerrmsg = false)
{
    global $mysql_connection, $_zp_query_count, $_zp_conf_vars;
    if ($mysql_connection == null) {
        db_connect();
    }
    $result = mysql_query($sql, $mysql_connection);
    if (!$result) {
        if ($noerrmsg) {
            return false;
        } else {
            $sql = sanitize($sql, 3);
            $error = sprintf(gettext('MySQL Query ( <em>%1$s</em> ) failed. Error: %2$s'), $sql, mysql_error());
            // Changed this to mysql_query - *never* call query functions recursively...
            if (!mysql_query("SELECT 1 FROM " . prefix('albums') . " LIMIT 0", $mysql_connection)) {
                $error .= "<br />" . gettext("It looks like your zenphoto tables haven't been created.") . ' ' . sprintf(gettext('You may need to run <a href="%s/%s/setup.php">the setup script.</a>'), WEBPATH, ZENFOLDER);
            }
            zp_error($error);
            return false;
        }
    }
    $_zp_query_count++;
    return $result;
}
<?php 
echo "\n</head>";
?>


<body>

	<?php 
$checkarray_images = array(gettext('*Bulk actions*') => 'noaction', gettext('Delete') => 'deleteall', gettext('Set to published') => 'showall', gettext('Set to unpublished') => 'hideall', gettext('Add tags') => 'addtags', gettext('Clear tags') => 'cleartags', gettext('Disable comments') => 'commentsoff', gettext('Enable comments') => 'commentson', gettext('Change owner') => 'changeowner');
if (extensionEnabled('hitcounter')) {
    $checkarray_images['Reset hitcounter'] = 'resethitcounter';
}
$checkarray_images = zp_apply_filter('bulk_image_actions', $checkarray_images);
// Create our album
if (!isset($_GET['album'])) {
    zp_error(gettext("No album provided to sort."));
} else {
    // Layout the page
    printLogoAndLinks();
    ?>

		<div id="main">
			<?php 
    printTabs();
    ?>
			<div id="content">
				<?php 
    zp_apply_filter('admin_note', 'albums', 'sort');
    if ($album->getParent()) {
        $link = getAlbumBreadcrumbAdmin($album);
    } else {
Beispiel #14
0
        $query['albumzip'] = 'true';
        if ($fromcache) {
            $query['fromcache'] = 'true';
        }
        $link = FULLWEBPATH . '/' . preg_replace('~^' . WEBPATH . '/~', '', $request['path']) . '?' . http_build_query($query);
        echo '<a href="' . html_encode($link) . '" rel="nofollow" class="downloadlist_link">' . html_encode($file) . '</a>' . $filesize;
    }
}
/**
 * Process any download requests
 */
if (isset($_GET['download'])) {
    $item = sanitize($_GET['download']);
    if (empty($item) || !extensionEnabled('downloadList')) {
        if (TEST_RELEASE) {
            zp_error(gettext('Forbidden'));
        } else {
            header("HTTP/1.0 403 " . gettext("Forbidden"));
            header("Status: 403 " . gettext("Forbidden"));
            exitZP();
            //	terminate the script with no output
        }
    }
    $hash = getOption('downloadList_password');
    if (GALLERY_SECURITY != 'public' || $hash) {
        //	credentials required to download
        if (!zp_loggedin(getOption('downloadList_rights') ? FILES_RIGHTS : ALL_RIGHTS)) {
            $user = getOption('downloadList_user');
            zp_handle_password('download_auth', $hash, $user);
            if (!empty($hash) && zp_getCookie('download_auth') != $hash) {
                $show = $user ? true : NULL;
     mkdir($uploaddir, CHMOD_VALUE);
 }
 @chmod($uploaddir, CHMOD_VALUE);
 $album = new Album($gallery, $folder);
 if ($album->exists) {
     if (!isset($_POST['publishalbum'])) {
         $album->setShow(false);
     }
     $title = sanitize($_POST['albumtitle'], 2);
     if (!empty($title) && $newAlbum) {
         $album->setTitle($title);
     }
     $album->save();
 } else {
     $AlbumDirName = str_replace(SERVERPATH, '', $gallery->albumdir);
     zp_error(gettext("The album couldn't be created in the 'albums' folder. This is usually a permissions problem. Try setting the permissions on the albums and cache folders to be world-writable using a shell:") . " <code>chmod 777 " . $AlbumDirName . CACHEFOLDER . "</code>, " . gettext("or use your FTP program to give everyone write permissions to those folders."));
 }
 $error = false;
 foreach ($_FILES['files']['error'] as $key => $error) {
     if ($_FILES['files']['name'][$key] == "") {
         continue;
     }
     if ($error == UPLOAD_ERR_OK) {
         $tmp_name = $_FILES['files']['tmp_name'][$key];
         $name = $_FILES['files']['name'][$key];
         $soename = UTF8toFilesystem(seoFriendlyURL($name));
         if (is_valid_image($name) || is_valid_other_type($name)) {
             $uploadfile = $uploaddir . '/' . $soename;
             move_uploaded_file($tmp_name, $uploadfile);
             @chmod($uploadfile, 0666 & CHMOD_VALUE);
             $image = newImage($album, $soename);
        $path_info = pathinfo($file);
        $themefiles_to_ext[$path_info['extension']][] = $file;
        // array(['php']=>array('file.php', 'image.php'),['css']=>array('style.css'))
    } else {
        unset($themefiles[$file]);
        // $themefile will eventually have all editable files and nothing else
    }
}
// Check that the theme is valid to edit
if (!themeIsEditable($theme)) {
    zp_error(gettext('Cannot edit this theme!'));
}
// If we're attempting to edit a file that's not a text file or that does not belong to the theme directory, this is an illegal attempt
if ($file_to_edit) {
    if (!in_array($file_to_edit, $themefiles) or !isTextFile($file_to_edit) or filesize($file_to_edit) == 0) {
        zp_error(gettext('Cannot edit this file!'));
    }
}
// realpath() to take care of ../../file.php schemes, str_replace() to sanitize Win32 filenames
// Handle POST that updates a file
if (isset($_POST['action']) && $_POST['action'] == 'edit_file' && $file_to_edit) {
    XSRFdefender('edit_theme');
    $file_content = sanitize($_POST['newcontent'], 0);
    $theme = urlencode($theme);
    if (is_writeable($file_to_edit)) {
        //is_writable() not always reliable, check return value. see comments @ http://uk.php.net/is_writable
        $f = @fopen($file_to_edit, 'w+');
        if ($f !== FALSE) {
            @fwrite($f, $file_content);
            fclose($f);
            clearstatcache();
Beispiel #17
0
 function __construct($p_zipname)
 {
     // ----- Tests the zlib
     if (!function_exists('gzopen')) {
         zp_error('Abort ' . basename(__FILE__) . ' : Missing zlib extensions');
     }
     // ----- Set the attributes
     $this->zipname = $p_zipname;
     $this->zip_fd = 0;
     $this->magic_quotes_status = -1;
     // ----- Return
     return;
 }
Beispiel #18
0
 /**
  * Load all of the filenames that are found in this Albums directory on disk.
  * Returns an array with all the names.
  *
  * @param  $dirs Whether or not to return directories ONLY with the file array.
  * @return array
  */
 protected function loadFileNames($dirs = false)
 {
     clearstatcache();
     $albumdir = $this->localpath;
     $dir = @opendir($albumdir);
     if (!$dir) {
         if (is_dir($albumdir)) {
             $msg = sprintf(gettext("Error: The album %s is not readable."), html_encode($this->name));
         } else {
             $msg = sprintf(gettext("Error: The album named %s cannot be found."), html_encode($this->name));
         }
         zp_error($msg, E_USER_WARNING);
         return array();
     }
     $files = array();
     $others = array();
     while (false !== ($file = readdir($dir))) {
         $file8 = filesystemToInternal($file);
         if (@$file8[0] != '.') {
             if ($dirs && (is_dir($albumdir . $file) || hasDynamicAlbumSuffix($file))) {
                 $files[] = $file8;
             } else {
                 if (!$dirs && is_file($albumdir . $file)) {
                     if ($handler = Gallery::imageObjectClass($file)) {
                         $files[] = $file8;
                         if ($handler !== 'Image') {
                             $others[] = $file8;
                         }
                     }
                 }
             }
         }
     }
     closedir($dir);
     if (count($others) > 0) {
         $others_thumbs = array();
         foreach ($others as $other) {
             $others_root = substr($other, 0, strrpos($other, "."));
             foreach ($files as $image) {
                 if ($image != $other) {
                     $image_root = substr($image, 0, strrpos($image, "."));
                     if ($image_root == $others_root && Gallery::imageObjectClass($image) == 'Image') {
                         $others_thumbs[] = $image;
                     }
                 }
             }
         }
         $files = array_diff($files, $others_thumbs);
     }
     if ($dirs) {
         return zp_apply_filter('album_filter', $files);
     } else {
         return zp_apply_filter('image_filter', $files);
     }
 }
Beispiel #19
0
 /**
  * Save the updates made to this object since the last update. Returns
  * true if successful, false if not.
  */
 function save()
 {
     if ($this->transient) {
         return false;
     }
     // If this object isn't supposed to be persisted, don't save it.
     if (!$this->unique_set) {
         // If we don't have a unique set, then this is incorrect. Don't attempt to save.
         zp_error('empty $this->unique set is empty');
         return false;
     }
     if (!$this->id) {
         $this->setDefaults();
         // Create a new object and set the id from the one returned.
         $insert_data = array_merge($this->unique_set, $this->updates, $this->tempdata);
         if (empty($insert_data)) {
             return true;
         }
         $i = 0;
         $cols = $vals = '';
         foreach ($insert_data as $col => $value) {
             if ($i > 0) {
                 $cols .= ", ";
             }
             $cols .= "`{$col}`";
             if ($i > 0) {
                 $vals .= ", ";
             }
             if (is_null($value)) {
                 $vals .= "NULL";
             } else {
                 $vals .= db_quote($value);
             }
             $i++;
         }
         $sql = 'INSERT INTO ' . prefix($this->table) . ' (' . $cols . ') VALUES (' . $vals . ')';
         $success = query($sql);
         if (!$success || db_affected_rows() != 1) {
             return false;
         }
         foreach ($insert_data as $key => $value) {
             // copy over any changes
             $this->data[$key] = $value;
         }
         $this->data['id'] = $this->id = (int) db_insert_id();
         // so 'get' will retrieve it!
         $this->loaded = true;
         $this->updates = array();
         $this->tempdata = array();
     } else {
         // Save the existing object (updates only) based on the existing id.
         if (empty($this->updates)) {
             return true;
         } else {
             $sql = 'UPDATE ' . prefix($this->table) . ' SET';
             $i = 0;
             foreach ($this->updates as $col => $value) {
                 if ($i > 0) {
                     $sql .= ",";
                 }
                 if (is_null($value)) {
                     $sql .= " `{$col}` = NULL";
                 } else {
                     $sql .= " `{$col}` = " . db_quote($value);
                 }
                 $this->data[$col] = $value;
                 $i++;
             }
             $sql .= ' WHERE id=' . $this->id . ';';
             $success = query($sql);
             if (!$success || db_affected_rows() != 1) {
                 return false;
             }
             foreach ($this->updates as $key => $value) {
                 $this->data[$key] = $value;
             }
             $this->updates = array();
         }
     }
     zp_apply_filter('save_object', true, $this);
     $this->addToCache($this->data);
     return true;
 }
Beispiel #20
0
/**
 * "Rewrite" handling for zenphoto
 *
 * The basic rules are found in the zenphoto-rewrite.txt file. Additional rules can be provided by plugins. But
 * for the plugin to load in time for the rules to be seen it must be either a CLASS_PLUGIN or a FEATURE_PLUGIN.
 * Plugins add rules by inserting them into the $_zp_conf_vars['special_pages'] array. Each "rule" is an array
 * of three elements: <var>define</var>, <var>rewrite</var>, and (optionally) <var>rule</rule>.
 *
 * Elemments which have a <var>define</var> and no <var>rule</rule> are processed by rewrite rules in the
 * zenphoto-rewrite.txt file and the <var>define</var> is used internally to zenphoto to reference
 * the rewrite text when building links.
 *
 * Elements with a <var>rule</rule> defined are processed after Search, Pages, and News rewrite rules and before
 * Image and album rewrite rules. The tag %REWRITE% in the rule is replaced with the <var>rewrite</var> text
 * before processing the rule. Thus <var>rewrite</var> is the token that should appear in the acutal URL.
 *
 * It makes no sense to have an element without either a <var>define</var> or a <var>rule</rule> as nothing will happen.
 *
 * At present all rules are presumed to to stop processing the rule set. Historically that is what all our rules have done, but I suppose
 * we could change that. The "R" flag may be used to cause a <var>header</var> status to be sent. However, we do not redirect
 * back to index.php, so the "R" flag is only useful if the target is a different script.
 *
 * @author Stephen Billard (sbillard)
 *
 * @package admin
 */
function rewriteHandler()
{
    global $_zp_conf_vars, $_zp_rewritten;
    $_zp_rewritten = false;
    $definitions = array();
    //	query parameters should already be loaded into the $_GET and $_REQUEST arrays, so we discard them here
    $request = explode('?', getRequestURI());
    //rewrite base
    $requesturi = ltrim(substr($request[0], strlen(WEBPATH)), '/');
    list($definitions, $rules) = getRules();
    //process the rules
    foreach ($rules as $rule) {
        if ($rule = trim($rule)) {
            if ($rule[0] != '#') {
                if (preg_match('~^rewriterule~i', $rule)) {
                    // it is a rewrite rule, see if it is applicable
                    $rule = strtr($rule, $definitions);
                    preg_match('~^rewriterule\\s+(.*?)\\s+(.*?)\\s*\\[(.*)\\]$~i', $rule, $matches);
                    if (array_key_exists(1, $matches)) {
                        if (preg_match('~' . $matches[1] . '~', $requesturi, $subs)) {
                            $params = array();
                            //	setup the rule replacement values
                            foreach ($subs as $key => $sub) {
                                $params['$' . $key] = urlencode($sub);
                                // parse_str is going to decode the string!
                            }
                            //	parse rewrite rule flags
                            $flags = array();
                            $banner = explode(',', strtoupper($matches[3]));
                            foreach ($banner as $flag) {
                                $flag = strtoupper(trim($flag));
                                $f = explode('=', $flag);
                                $flags[trim($f[0])] = isset($f[1]) ? trim($f[1]) : NULL;
                            }
                            if (!array_key_exists('QSA', $flags)) {
                                //	QSA means merge the query parameters. Otherwise we clear them
                                $_REQUEST = array_diff($_REQUEST, $_GET);
                                $_GET = array();
                            }
                            preg_match('~(.*?)\\?(.*)~', $matches[2], $action);
                            if (empty($action)) {
                                $action[1] = $matches[2];
                            }
                            if (array_key_exists(2, $action)) {
                                //	process the rules replacements
                                $query = strtr($action[2], $params);
                                parse_str($query, $gets);
                                $_GET = array_merge($_GET, $gets);
                                $_REQUEST = array_merge($_REQUEST, $gets);
                            }
                            //	we will execute the index.php script in due course. But if the rule
                            //	action takes us elsewhere we will have to re-direct to that script.
                            if (isset($action[1]) && $action[1] != 'index.php') {
                                $qs = http_build_query($_GET);
                                if ($qs) {
                                    $qs = '?' . $qs;
                                }
                                if (array_key_exists('R', $flags)) {
                                    header('Status: ' . $flags['R']);
                                }
                                header('Location: ' . WEBPATH . '/' . $action[1] . $qs);
                                exit;
                            }
                            $_zp_rewritten = true;
                            break;
                        }
                    } else {
                        zp_error(sprintf(gettext('Error processing rewrite rule: “%s”'), trim(preg_replace('~^rewriterule~i', '', $rule))), E_USER_WARNING);
                    }
                } else {
                    if (preg_match('~define\\s+(.*?)\\s*\\=\\>\\s*(.*)$~i', $rule, $matches)) {
                        //	store definitions
                        eval('$definitions[$matches[1]] = ' . $matches[2] . ';');
                    }
                }
            }
        }
    }
}
Beispiel #21
0
 /**
  * Load all of the filenames that are found in this Albums directory on disk.
  * Returns an array with all the names.
  *
  * @param  $dirs Whether or not to return directories ONLY with the file array.
  * @return array
  */
 function loadFileNames($dirs = false)
 {
     if ($this->isDynamic()) {
         // there are no 'real' files
         return array();
     }
     $albumdir = $this->localpath;
     if (!is_dir($albumdir) || !is_readable($albumdir)) {
         if (!is_dir($albumdir)) {
             $msg = sprintf(gettext("Error: The album named %s cannot be found."), $this->name);
         } else {
             $msg = sprintf(gettext("Error: The album %s is not readable."), $this->name);
         }
         zp_error($msg, false);
         return array();
     }
     $dir = opendir($albumdir);
     $files = array();
     $others = array();
     while (false !== ($file = readdir($dir))) {
         $file8 = filesystemToInternal($file);
         if ($dirs && (is_dir($albumdir . $file) && substr($file, 0, 1) != '.' || hasDynamicAlbumSuffix($file))) {
             $files[] = $file8;
         } else {
             if (!$dirs && is_file($albumdir . $file)) {
                 if (is_valid_other_type($file)) {
                     $files[] = $file8;
                     $others[] = $file8;
                 } else {
                     if (is_valid_image($file)) {
                         $files[] = $file8;
                     }
                 }
             }
         }
     }
     closedir($dir);
     if (count($others) > 0) {
         $others_thumbs = array();
         foreach ($others as $other) {
             $others_root = substr($other, 0, strrpos($other, "."));
             foreach ($files as $image) {
                 $image_root = substr($image, 0, strrpos($image, "."));
                 if ($image_root == $others_root && $image != $other && is_valid_image($image)) {
                     $others_thumbs[] = $image;
                 }
             }
         }
         $files = array_diff($files, $others_thumbs);
     }
     if ($dirs) {
         return zp_apply_filter('album_filter', $files);
     } else {
         return zp_apply_filter('image_filter', $files);
     }
 }
Beispiel #22
0
 /**
  * Load all of the albums names that are found in the Albums directory on disk.
  * Returns an array containing this list.
  *
  * @return array
  */
 private function loadAlbumNames()
 {
     $albumdir = $this->getAlbumDir();
     $dir = opendir($albumdir);
     if (!$dir) {
         if (!is_dir($albumdir)) {
             $msg .= sprintf(gettext('Error: The “albums” directory (%s) cannot be found.'), $this->albumdir);
         } else {
             $msg .= sprintf(gettext('Error: The “albums” directory (%s) is not readable.'), $this->albumdir);
         }
         zp_error($msg);
     }
     $albums = array();
     while ($dirname = readdir($dir)) {
         if ($dirname[0] != '.' && (is_dir($albumdir . $dirname) || hasDynamicAlbumSuffix($dirname))) {
             $albums[] = filesystemToInternal($dirname);
         }
     }
     closedir($dir);
     return zp_apply_filter('album_filter', $albums);
 }
/**
 * Common error reporting for query errors
 * @param type $sql
 */
function dbErrorReport($sql)
{
    zp_error(sprintf(gettext('%1$s Error: ( %2$s ) failed. %1$s returned the error %3$s'), DATABASE_SOFTWARE, $sql, db_error()), E_USER_ERROR);
}
function editInPlace_handle_request($context = '', $field = '', $value = '', $orig_value = '')
{
    // Cannot edit when context not set in current page (should happen only when editing in place from index.php page)
    if (!in_context(ZP_IMAGE) && !in_context(ZP_ALBUM) && !in_context(ZP_ZENPAGE_PAGE) && !in_context(ZP_ZENPAGE_NEWS_ARTICLE)) {
        die($orig_value . '<script type="text/javascript">alert("' . gettext('Oops.. Cannot edit from this page') . '");</script>');
    }
    // Make a copy of context object
    switch ($context) {
        case 'image':
            global $_zp_current_image;
            $object = $_zp_current_image;
            break;
        case 'album':
            global $_zp_current_album;
            $object = $_zp_current_album;
            break;
        case 'zenpage_page':
            global $_zp_current_zenpage_page;
            $object = $_zp_current_zenpage_page;
            break;
        case 'zenpage_news':
            global $_zp_current_zenpage_news;
            $object = $_zp_current_zenpage_news;
            break;
        default:
            die(gettext('Error: malformed Ajax POST'));
    }
    // Dates need to be handled before stored
    if ($field == 'date') {
        $value = date('Y-m-d H:i:s', strtotime($value));
    }
    // Sanitize new value
    switch ($field) {
        case 'desc':
            $level = 1;
            break;
        case 'title':
            $level = 2;
            break;
        default:
            $level = 3;
    }
    $value = str_replace("\n", '<br />', sanitize($value, $level));
    // note: not using nl2br() here because it adds an extra "\n"
    // Write new value
    if ($field == '_update_tags') {
        $value = trim($value, ', ');
        $object->setTags($value);
    } else {
        $object->set($field, $value);
    }
    $result = $object->save();
    if ($result !== false) {
        echo $value;
    } else {
        echo '<script type="text/javascript">alert("' . gettext('Could not save!') . '");</script>' . $orig_value;
    }
    zp_error(gettext('Front_end_edit could not save changes!'));
}
/**
 * returns the current values for the image size or its height & width
 * This information comes form (in order of priority)
 *   1. The posting of a radio button selection
 *   2. A cookie stored from #1
 *   3. The default (either as passed, or from the plugin option.)
 *
 * The function is used internally, so the above priority determines the
 * image sizing.
 *
 * @param string $default the default (initial) value for the image sizing
 * @param int $size The size of the image (Width and Height are NULL)
 * @param int $width The width of the image (size is null)
 * @param int $height The height of the image (size is null)
 */
function getViewerImageSize($default, &$size, &$width, &$height)
{
    global $postdefault;
    if (isset($_POST['viewer_size_image_selection']) || empty($default)) {
        $msg = gettext('There is a format error in user size selection');
        $validate = $postdefault;
    } else {
        $msg = gettext('There is a format error in your $default parameter');
        $validate = $default;
    }
    $size = $width = $height = NULL;
    preg_match_all('/(\\$[shw])[\\s]*=[\\s]*([0-9]+)/', $validate, $matches);
    if ($matches) {
        foreach ($matches[0] as $key => $str) {
            switch ($matches[1][$key]) {
                case '$s':
                    $size = $matches[2][$key];
                    break;
                case '$w':
                    $width = $matches[2][$key];
                    break;
                case '$h':
                    $height = $matches[2][$key];
                    break;
            }
        }
        if (!empty($size)) {
            $width = $height = NULL;
        } else {
            $size = NULL;
        }
    }
    if (empty($size) && empty($width) && empty($height)) {
        zp_error($msg, E_USER_NOTICE);
    }
}
Beispiel #26
0
        getSubalbumImages($folder);
    }
}
$search = new SearchEngine(true);
if (isset($_POST['savealbum'])) {
    XSRFdefender('savealbum');
    $albumname = sanitize($_POST['album']);
    if ($album = sanitize($_POST['albumselect'])) {
        $albumobj = newAlbum($album);
        $allow = $albumobj->isMyItem(ALBUM_RIGHTS);
    } else {
        $allow = zp_loggedin(MANAGE_ALL_ALBUM_RIGHTS);
    }
    if (!$allow) {
        if (!zp_apply_filter('admin_managed_albums_access', false, $return)) {
            zp_error(gettext("You do not have edit rights on this album."));
        }
    }
    if ($_POST['create_tagged'] == 'static') {
        $unpublished = isset($_POST['return_unpublished']);
        $_POST['return_unpublished'] = true;
        //	state is frozen at this point, so unpublishing should not impact
        $words = sanitize($_POST['album_tag']);
        $searchfields[] = 'tags_exact';
        // now tag each element
        if (isset($_POST['return_albums'])) {
            $subalbums = $search->getAlbums(0);
            foreach ($subalbums as $analbum) {
                $albumobj = newAlbum($analbum);
                if ($unpublished || $albumobj->getShow()) {
                    $tags = array_unique(array_merge($albumobj->getTags(), array($words)));
Beispiel #27
0
 /**
  * Gets the feed items
  *
  * @return array
  */
 public function getitems()
 {
     global $_zp_CMS;
     switch ($this->feedtype) {
         case 'gallery':
             if ($this->mode == "albums") {
                 $items = getAlbumStatistic($this->itemnumber, $this->sortorder, $this->albumfolder, 0, $this->sortdirection);
             } else {
                 $items = getImageStatistic($this->itemnumber, $this->sortorder, $this->albumfolder, $this->collection, 0, $this->sortdirection);
             }
             break;
         case 'news':
             switch ($this->newsoption) {
                 case "category":
                     if ($this->sortorder) {
                         $items = getZenpageStatistic($this->itemnumber, 'categories', $this->sortorder, $this->sortdirection);
                     } else {
                         $items = getLatestNews($this->itemnumber, $this->catlink, false, $this->sortdirection);
                     }
                     break;
                 default:
                 case "news":
                     if ($this->sortorder) {
                         $items = getZenpageStatistic($this->itemnumber, 'news', $this->sortorder, $this->sortdirection);
                     } else {
                         // Needed baceause type variable "news" is used by the feed item method and not set by the class method getArticles!
                         $items = getLatestNews($this->itemnumber, '', false, $this->sortdirection);
                     }
                     break;
             }
             break;
         case "pages":
             if ($this->sortorder) {
                 $items = getZenpageStatistic($this->itemnumber, 'pages', $this->sortorder, $this->sortdirection);
             } else {
                 $items = $_zp_CMS->getPages(NULL, false, $this->itemnumber);
             }
             break;
         case 'comments':
             switch ($type = $this->commentfeedtype) {
                 case 'gallery':
                     $items = getLatestComments($this->itemnumber, 'all');
                     break;
                 case 'album':
                     $items = getLatestComments($this->itemnumber, 'album', $this->id);
                     break;
                 case 'image':
                     $items = getLatestComments($this->itemnumber, 'image', $this->id);
                     break;
                 case 'zenpage':
                     $type = 'all';
                 case 'news':
                 case 'page':
                     if (function_exists('getLatestZenpageComments')) {
                         $items = getLatestZenpageComments($this->itemnumber, $type, $this->id);
                     }
                     break;
                 case 'allcomments':
                     $items = getLatestComments($this->itemnumber, 'all');
                     $items_zenpage = array();
                     if (function_exists('getLatestZenpageComments')) {
                         $items_zenpage = getLatestZenpageComments($this->itemnumber, 'all', $this->id);
                         $items = array_merge($items, $items_zenpage);
                         $items = sortMultiArray($items, 'date', true);
                         $items = array_slice($items, 0, $this->itemnumber);
                     }
                     break;
             }
             break;
     }
     if (isset($items)) {
         return $items;
     }
     if (TEST_RELEASE) {
         zp_error(gettext('Bad ' . $this->feed . ' feed:' . $this->feedtype), E_USER_WARNING);
     }
     return NULL;
 }
Beispiel #28
0
/**
 * Creates a menu set from the items passed. But only if the menu set does not already exist
 * @param array $menuitems items for the menuset
 * 		array elements:
 * 			'type'=>menuset type
 * 			'title'=>title for the menu item
 * 			'link'=>URL or other data for the item link
 * 			'show'=>set to 1:"visible" or 0:"hidden",
 * 			'nesting'=>nesting level of this item in the menu heirarchy
 *
 * @param string $menuset current menuset
 */
function createMenuIfNotExists($menuitems, $menuset = 'default')
{
    $count = db_count('menu', 'WHERE menuset=' . db_quote($menuset));
    if ($count == 0) {
        // there was not an existing menu set
        require_once dirname(__FILE__) . '/menu_manager/menu_manager-admin-functions.php';
        $success = 1;
        $orders = array();
        foreach ($menuitems as $key => $result) {
            if (array_key_exists('nesting', $result)) {
                $nesting = $result['nesting'];
            } else {
                $nesting = 0;
            }
            while ($nesting + 1 < count($orders)) {
                array_pop($orders);
            }
            while ($nesting + 1 > count($orders)) {
                array_push($orders, -1);
            }
            $result['id'] = 0;
            if (isset($result['include_li'])) {
                $includeli = $result['include_li'];
            } else {
                $includeli = 1;
            }
            $type = $result['type'];
            switch ($type) {
                case 'all_items':
                    $orders[$nesting]++;
                    query("INSERT INTO " . prefix('menu') . " (`title`,`link`,`type`,`show`,`menuset`,`sort_order`) " . "VALUES ('" . gettext('Home') . "', '" . WEBPATH . '/' . "','galleryindex','1'," . db_quote($menuset) . ',' . db_quote($orders), true);
                    $orders[$nesting] = addAlbumsToDatabase($menuset, $orders);
                    if (extensionEnabled('zenpage')) {
                        $orders[$nesting]++;
                        query("INSERT INTO " . prefix('menu') . " (title`,`link`,`type`,`show`,`menuset`,`sort_order`) " . "VALUES ('" . gettext('News index') . "', '" . getNewsIndexURL() . "','newsindex','1'," . db_quote($menuset) . ',' . db_quote(sprintf('%03u', $base + 1)), true);
                        $orders[$nesting] = addPagesToDatabase($menuset, $orders) + 1;
                        $orders[$nesting] = addCategoriesToDatabase($menuset, $orders);
                    }
                    $type = false;
                    break;
                case 'all_albums':
                    $orders[$nesting]++;
                    $orders[$nesting] = addAlbumsToDatabase($menuset, $orders);
                    $type = false;
                    break;
                case 'all_Pages':
                    $orders[$nesting]++;
                    $orders[$nesting] = addPagesToDatabase($menuset, $orders);
                    $type = false;
                    break;
                case 'all_categorys':
                    $orders[$nesting]++;
                    $orders[$nesting] = addCategoriesToDatabase($menuset, $orders);
                    $type = false;
                    break;
                case 'album':
                    $result['title'] = NULL;
                    if (empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty link.'), $key));
                    }
                    break;
                case 'galleryindex':
                    $result['link'] = NULL;
                    if (empty($result['title'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title.'), $key));
                    }
                    break;
                case 'Page':
                    $result['title'] = NULL;
                    if (empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty link.'), $key));
                    }
                    break;
                case 'newsindex':
                    $result['link'] = NULL;
                    if (empty($result['title'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title.'), $key));
                    }
                    break;
                case 'category':
                    $result['title'] = NULL;
                    if (empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty link.'), $key));
                    }
                    break;
                case 'custompage':
                    if (empty($result['title']) || empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title or link.'), $key));
                    }
                    break;
                case 'customlink':
                    if (empty($result['title'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title.'), $key));
                    } else {
                        if (empty($result['link'])) {
                            $result['link'] = seoFriendly(get_language_string($result['title']));
                        }
                    }
                    break;
                case 'menulabel':
                    if (empty($result['title'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title.'), $key));
                    }
                    $result['link'] = sha1($result['title']);
                    break;
                case 'menufunction':
                    if (empty($result['title']) || empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title or link.'), $key));
                    }
                    break;
                case 'html':
                    if (empty($result['title']) || empty($result['link'])) {
                        $success = -1;
                        debugLog(sprintf(gettext('createMenuIfNotExists item %s has an empty title or link.'), $key));
                    }
                    break;
                default:
                    $success = -1;
                    debugLog(sprintf(gettext('createMenuIfNotExists item %s has an invalid type.'), $key));
                    break;
            }
            if ($success > 0 && $type) {
                $orders[$nesting]++;
                $sort_order = '';
                for ($i = 0; $i < count($orders); $i++) {
                    $sort_order .= sprintf('%03u', $orders[$i]) . '-';
                }
                $sort_order = substr($sort_order, 0, -1);
                $sql = "INSERT INTO " . prefix('menu') . " (`title`,`link`,`type`,`show`,`menuset`,`sort_order`,`include_li`) " . "VALUES (" . db_quote($result['title']) . ", " . db_quote($result['link']) . "," . db_quote($result['type']) . "," . $result['show'] . "," . db_quote($menuset) . "," . db_quote($sort_order) . ",{$includeli})";
                if (!query($sql, false)) {
                    $success = -2;
                    debugLog(sprintf(gettext('createMenuIfNotExists item %1$s query (%2$s) failed: %3$s.'), $key, $sql, db_error()));
                }
            }
        }
    } else {
        $success = 0;
    }
    if ($success < 0) {
        zp_error(gettext('createMenuIfNotExists has posted processing errors to your debug log.'), E_USER_NOTICE);
    }
    return $success;
}
Beispiel #29
0
 /**
  * Sets default values for a new album
  *
  * @return bool
  */
 protected function setDefaults()
 {
     global $_zp_gallery;
     if (TEST_RELEASE) {
         $bt = debug_backtrace();
         $good = false;
         foreach ($bt as $b) {
             if ($b['function'] == "newAlbum") {
                 $good = true;
                 break;
             }
         }
         if (!$good) {
             zp_error(gettext('An album object was instantiated without using the newAlbum() function.'), E_USER_WARNING);
         }
     }
     // Set default data for a new Album (title and parent_id)
     $parentalbum = NULL;
     $this->setShow($_zp_gallery->getAlbumPublish());
     $this->set('mtime', time());
     $title = trim($this->name);
     $this->set('title', sanitize($title, 2));
     return true;
 }
Beispiel #30
0
 /**
  * Migrates credentials
  *
  * @param int $oldversion
  */
 function migrateAuth($to)
 {
     if ($to > self::$supports_version || $to < self::$preferred_version - 1) {
         zp_error(sprintf(gettext('Cannot migrate rights to version %1$s (Zenphoto_Authority supports only %2$s and %3$s.)'), $to, self::$supports_version, self::$preferred_version), E_USER_NOTICE);
         return false;
     }
     $success = true;
     $oldversion = self::getVersion();
     setOption('libauth_version', $to);
     $this->admin_users = array();
     $sql = "SELECT * FROM " . prefix('administrators') . "ORDER BY `rights` DESC, `id`";
     $admins = query($sql, false);
     if ($admins) {
         // something to migrate
         $oldrights = array();
         foreach (self::getRights($oldversion) as $key => $right) {
             $oldrights[$key] = $right['value'];
         }
         $currentrights = self::getRights($to);
         while ($user = db_fetch_assoc($admins)) {
             $update = false;
             $rights = $user['rights'];
             $newrights = $currentrights['NO_RIGHTS']['value'];
             foreach ($currentrights as $key => $right) {
                 if ($right['display']) {
                     if (array_key_exists($key, $oldrights) && $rights & $oldrights[$key]) {
                         $newrights = $newrights | $right['value'];
                     }
                 }
             }
             if ($oldversion < 4) {
                 $newrights = $newrights | $currentrights['USER_RIGHTS']['value'];
             }
             if ($to >= 3 && $oldversion < 3) {
                 if ($rights & $oldrights['VIEW_ALL_RIGHTS']) {
                     $updaterights = $currentrights['ALL_ALBUMS_RIGHTS']['value'] | $currentrights['ALL_PAGES_RIGHTS']['value'] | $currentrights['ALL_NEWS_RIGHTS']['value'] | $currentrights['VIEW_SEARCH_RIGHTS']['value'] | $currentrights['VIEW_GALLERY_RIGHTS']['value'] | $currentrights['VIEW_FULLIMAGE_RIGHTS']['value'];
                     $newrights = $newrights | $updaterights;
                 }
             }
             if ($oldversion >= 3 && $to < 3) {
                 if ($oldrights['ALL_ALBUMS_RIGHTS'] || $oldrights['ALL_PAGES_RIGHTS'] || $oldrights['ALL_NEWS_RIGHTS']) {
                     $newrights = $newrights | $currentrights['VIEW_ALL_RIGHTS']['value'];
                 }
             }
             if ($oldversion == 1) {
                 // need to migrate zenpage rights
                 if ($rights & $oldrights['ZENPAGE_RIGHTS']) {
                     $newrights = $newrights | $currentrights['ZENPAGE_PAGES_RIGHTS'] | $currentrights['ZENPAGE_NEWS_RIGHTS'] | $currentrights['FILES_RIGHTS'];
                 }
             }
             if ($to >= 3) {
                 if ($newrights & $currentrights['ADMIN_RIGHTS']['value']) {
                     $newrights = $currentrights['ALL_RIGHTS']['value'];
                 } else {
                     if ($newrights & $currentrights['MANAGE_ALL_ALBUM_RIGHTS']['value']) {
                         // these are lock-step linked!
                         $newrights = $newrights | $currentrights['ALBUM_RIGHTS']['value'];
                     }
                     if ($newrights & $currentrights['MANAGE_ALL_NEWS_RIGHTS']['value']) {
                         // these are lock-step linked!
                         $newrights = $newrights | $currentrights['ZENPAGE_NEWS_RIGHTS']['value'];
                     }
                     if ($newrights & $currentrights['MANAGE_ALL_PAGES_RIGHTS']['value']) {
                         // these are lock-step linked!
                         $newrights = $newrights | $currentrights['ZENPAGE_PAGES_RIGHTS']['value'];
                     }
                 }
             }
             $sql = 'UPDATE ' . prefix('administrators') . ' SET `rights`=' . $newrights . ' WHERE `id`=' . $user['id'];
             $success = $success && query($sql);
         }
         // end loop
         db_free_result($admins);
     }
     return $success;
 }