More Qs on User Syncronization with emApp

skyrover

Joined: 2004-06-29
Posts: 13
Posted: Sat, 2006-10-07 22:27

I have made it about half way down the road with embedding G2 in my app. Where i am now getting hung up is on user sync with the users I have currenly in my system, as well as those in G2. I have it working for guest users, who are just browsing a gallery.

Basically, I'm working on getting the owner of G2 gallery logged into G2 so they can do admin (after they've successfully logged into my app). After that I'll tackle new G2 user creation.

I am confused about this user syncronization. I have about 15 users of my app, and 4 of those users have galleries. I have their G2 username in my DB.

If, when a user logs into my system, they have a G2 username I'm trying to log them into G2 so they can manage their photos. I don't really need on-the-fly user creation, but it appears i might have to recreate my gallery users for some reason?

if i try

$g2User = 6;
$ret = GalleryEmbed::init(array( 'g2Uri' => $g2_Config['g2Uri'], 
'activeUserId'=>$gUser, 
'loginRedirect' => $g2_Config['loginredirect'], 
'embedUri' => $g2_Config['embedUri'], 
'fullInit' =>'false'));

knowing that "6" is a gallery userID, it blows up (ERROR_MISSING_OBJECT), which is probably correct because it is supposed to be my app's userID which is not mapped to anything in G2.

Q: Does the following

GalleryEmbed::createUser($emAppUserId, array('username' => $emAppUser['username'],'language' => $emAppUser['language'], ...));

do some magic to attach my userID to a G2 userID? What of those gallery users that already exist? How are they 'mapped'? And what are the rest of the parameters to GalleryEmbed::createUser (the ... above) - are all these calls documented someplace? A search for GalleryEmbed::createUser turns up 2 docs - that above is the most detailed reference. Do i need to spec a password, too?

From the docs:

Quote:
If G2 and/or emApp are not freshly installed and already in use, maybe already with some registered users, you need to map all these users, hopefully in an automated way, else you have to do a lot of manual work. You should map users that exist in emApp and G2 and you should create a new user in emApp for all users in G2 that don't exist in emApp yet and the other way around.

Right - so I loop my users calling GalleryEmbed::createUser, passing my userID, my username, and some other parameters (tbd), and a 'map' is created someplace (where, in the G2 db?)? After this is done, I go back as superadmin and change ownership of all the 'old' (non-synced) albums to their correct new (synced) account name?

Example:

A user on my system has a username of

(because my system uses email address for usernames) and a userID of '27'.

Their G2 username (because I upgraded the g1 gallery to g2) is 'name1234' - because g1 didn't allow email addrs to be used as usernames. Lets say their g2 user id is '12'.

I have in my database 27,name1234@mailhost.com,name1234 (and other stuff) but not G2's id (12). How is the createUser call properly constructed?

is it possible to instead use GalleryEmbed::updateUser() to get the proper 'mapping' (and where do I find out what the updateUser parameters are)?

Any insight would be appreciated.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Sun, 2006-10-08 15:04
Quote:
And what are the rest of the parameters to GalleryEmbed::createUser (the ... above) - are all these calls documented someplace?

Found two answers...

GalleryEmbed::createUser()
     * @param string external user id
     * @param array user data (username required; others optional)
     *              ['username' => string, 'email' => string, 'fullname' => string,
     *               'language' => string, 'password' => string,
     *               'hashedpassword' => string, 'hashmethod' => string,
     *               'creationtimestamp' => integer]

it would appear the updateUser has the same arguments (logical) but the call is based on the external user id, so it would be assumed that a createUser call through embed would have to come before being able to update a user. Thus it would follow that i cannot use updateUser to modify existing G2 users that were created outside the embed - i.e. when the gallery was updated from G1.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Sun, 2006-10-08 18:42
Quote:
but it appears i might have to recreate my gallery users for some reason?

This is apparently true.

Quote:
Do i need to spec a password, too?

Based on the GalleryEmbed::createUser() args, the answer could be no. However, I spec'd a generic password for all of them so that all users have a password. See the program below.

Quote:
Q: Does the following

GalleryEmbed::createUser($emAppUserId, array('username' => $emAppUser['username'],'language' => $emAppUser['language'], ...));

do some magic to attach my userID to a G2 userID?

Apparently yes.

Quote:
What of those gallery users that already exist? How are they 'mapped'?

I'm not sure about this at this point, I think they will have to go away...

I created the following progam to do the initial user sync between my program and G2:

<?

require_once('fullpath/gallery/embed.php');

$dblink = @mysql_connect ("localhost")
			or die ("Could not connect");

$db = "mydb";

$data = array();
	
$g2_Config['path'] = dirname(__FILE__) . '/';
$g2_Config['g2Uri'] = '/gallery/';
$g2_Config['loginredirect'] = '/login.php';
$g2_Config['embedUri'] = '/admin/gallery2.php';

$g2user = "";
$g2DefPW = "abg2pw";

$sql = "select id,username,first_name,last_name,email,enableGallery from blog_sub";
		
$ret = GalleryEmbed::init(array('baseUri' => $baseUri, 'g2Uri' => $g2user, 'activeUserId' => $emAppUserId));
if ($ret) {
     /* Error! */
     echo("gallery init error:" . $ret->getAsHtml());
} else {
	
	// call the db for users
	$result = mysql_db_query($db,$sql);
	
	// loop the users
	while ($row = mysql_fetch_array($result)) {
		if ($row["enableGallery"]) {
			// this user should get a gallery, check them and create them if needed
			
			$emAppUserId = $row["id"];
			$emAppFullname = $row["first_name"] . " " . $row["last_name"];
		
			$ret2 = GalleryEmbed::isExternalIdMapped($emAppUserId, 'GalleryUser');
     		if ($ret2 && $ret2->getErrorCode() & ERROR_MISSING_OBJECT) {
				/* The user does not exist in G2 yet. Create in now on-the-fly */
         		$ret = GalleryEmbed::createUser($emAppUserId, array('username' => $row['username'],
                                                             'email'=>$row['email'],
                                                             'fullname'=>$emAppFullName,
                                                             'password'=>$g2DefPW));
                                                             
				if ($ret) {
					/* An error during user creation. Not good, print an error or do whatever is appropriate 
					* in your emApp when an error occurs */
					print "An error occurred during the on-the-fly user creation <br>";
					print $ret->getAsHtml();
					exit;
				} else {
					echo("created g2 user " . $row["username"] . "<br>");
				}
					
			 } else {
				/* check to see how bad the error was */
				if ($ret2) {
					print "An error occurred while checking if a user already exists<br>";
					print $ret2->getAsHtml();
				} else {
					echo("user " . $row["username"] . " has g2 mapping<br>");
				}
				
			 }
			 
		} // end if enableGallery
		 
 	} // ends the user loop

}

?>

obviously, paths and the DB info will have to be changed for a particular system. But this has worked, and it has a trap in there so that it can be rerun as needed to keep user in sync in the future.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Mon, 2006-10-09 03:06

To keep on followingup on my own thread (in the hopes that someone else might benefit), I am now about 75% of the way there to completing my integration.

Where I am at right now is that after running the above program I have mapped users between my system and G2. Passing G2 the proper userID from my system gets them logged in and able to modify their personal album.

What I have left to complete is:

1. Right now G2 is configured to create a new album when I create a user. This is nice, sort of. There appears to be a fair bit of things that happen when an album is created, so in that sense it's good. it's bad in that I cannot control the title/URL of the album, the theme, and various other config options that I'd really like to set for the user on the fly. I'm exploring using the coreapi calls for this, but i'm not sure if I can use those calls in an embed situation - modules only?

It also appears there is no "modifyAlbum" or "updateAlbum" function as part of the api, which is what I really need. For example, if a user changes their template in my system I'd very much like to automatically change the template of their album(s). So given that createUser will also create an album for that user, what I really need is to modify the album as soon as it's created.

Ideas on that?

2. I'd like to dump the user right into their album from my application, so I need to capture / store the id of the album that was created when the user was created. Trying to figure out what is the best way to do that through embed, if I can. Again, there are some api calls that could help, if I can utilize them without a module.

3. Templates that are embedding gallery really need to be XHTML Strict or the CSS blows to hell - my pages need to be updated for that.

I think at this point I'm confortable I can make the embed work well enough for my users, but the question is how much 'bonus' work do i have to make the user do, like re-choosing their theme, naming the gallery, etc.

 
valiant

Joined: 2003-01-04
Posts: 32509
Posted: Mon, 2006-10-09 10:19

1. you might want to change the useralbum module for that.
createUser() is not directly responsible for creating an album for the user. it's the useralbum module that does that on GalleryEntity::save events of entities of type GalleryUser.

2. The joomla and other integrations do the same and they are GPL. maybe you can copy some code.

3. Don't you like XHTML strict? :)

Please let us know what information is missing at http://codex.gallery2.org/index.php/Gallery2:Embedding . You or I could then update the docs there.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Mon, 2006-10-09 20:34
valiant wrote:
1. you might want to change the useralbum module for that.
createUser() is not directly responsible for creating an album for the user. it's the useralbum module that does that on GalleryEntity::save events of entities of type GalleryUser.

Ok... picking through the code, I see that galleryEmbed::createUser calls GalleryCoreApi::newFactoryInstance('GalleryEntity', 'GalleryUser') - now I assume that because the userAlbum module is listening for a 'new user' event (since i have that module enabled), the userAlbum module creates the new album by calling GalleryCoreApi::createAlbum (line 60 of /modules/useralbum/classes/UserAlbumHelperClass.class). Just prior to this call, the album name and title are assigned by the code based on the new user's full name or username.

So when you suggest modifying the userAlbum module, I could add a bunch of parameters to the function createUserAlbum($user), allowing overrides to the name,title, summary, etc (the parameters for createAlbum listed in the api docs) :

createAlbum( int $parentAlbumId, string $name, string $title, string $summary, string $description, string $keywords )

My question is this: if i know a few of these values (name, title, description) *before* I call galleryEmbed::createUser, how do I set them or pass them all they way through newFactoryInstance to createUserAlbum? I suppose i could set up the parameters as a global vars that createUserAlbum would check for before calling createAlbum? Not terribly keen on using globals, but if they get the job done...

Where does the theme property for an album get set? I can't find this anywhere... And updating an album - what function handles this?

Quote:
2. The joomla and other integrations do the same and they are GPL. maybe you can copy some code.

I'll see what i can find. If i get the create ablums stuff working, i think i could use an api call fetchItemIdByPath to get the id.

Quote:
3. Don't you like XHTML strict? :)

Well, i both like it and dislike it. I suspect a lot of people have 'looser' html pages, and so when embedding it requires a bunch of rework on the embedding site to get it up to standard. It just took a few hours of dinking around with the embed, the html, the css to finally discover exactly what was going on (why the embedded version looked like crap and the non-embed looked ok), and then some additional time to change the embed html to conform to XHTML strict. Not blaming you guys, but having a note on the Embedding How To page or someplace that gallery is expecting XHTML strict and the css does unpredictible things when it isn't would have saved some time.

Quote:
Please let us know what information is missing at http://codex.gallery2.org/index.php/Gallery2:Embedding . You or I could then update the docs there.

When i get this completed, I might send some suggestions in...

thanks.

 
valiant

Joined: 2003-01-04
Posts: 32509
Posted: Mon, 2006-10-09 21:01
Quote:
So when you suggest modifying the userAlbum module, I could add a bunch of parameters to the function createUserAlbum($user), allowing overrides to the name,title, summary, etc (the parameters for createAlbum listed in the api docs) :

no, i'd never do that.

don't change the core API when you can easily achieve the same goal in your modular code.
just change the attributes of that album after it has been created.

Quote:
Where does the theme property for an album get set?

an album inherits the theme of its parent album. same for other theme attributes like thumbnail size etc.
in the current svn version (g2.2-svn), there's an admin setting to switch from defaulting the theme of a new album to the global default settings vs. to the parent.

you can change the theme of an album once it has been created with $album->setTheme($themeId);

@XHTML strict:
well, no need to do be strict. your application sets the HTML document header. you can make it loose too.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Tue, 2006-10-10 00:09
skyrover wrote:
2. I'd like to dump the user right into their album from my application, so I need to capture / store the id of the album that was created when the user was created. Trying to figure out what is the best way to do that through embed, if I can. Again, there are some api calls that could help, if I can utilize them without a module.

OK, another positive step, though a small one. This code:

// user was created, get the new album id
list ($ret, $galleryuser) = GalleryCoreApi::loadEntityByExternalId($emAppUserId,'GalleryUser');
if ($ret) {
	print $ret->getAsHtml();
	exit;
}

if(is_object($galleryuser)) {
			 
	list ($ret, $albumId) = GalleryCoreApi::getPluginParameter('module', 'useralbum', 'albumId', $galleryuser->getId());
	if ($ret) {
		print $ret->getAsHtml();
		exit;
	}
				
	print "AlbumID:  $albumId \n<br>";
				
}

will expose the album id that was just created when calling the GalleryEmbed::createUser()

In the program i posted a few posts back, this would be added were it the

echo("created g2 user " . $row["username"] . "<br>");

statement is.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Tue, 2006-10-10 01:04
valiant wrote:

you can change the theme of an album once it has been created with $album->setTheme($themeId);

Oh so close. after the above block that gets the album id, i added the following:

list ($ret, $album) = GalleryCoreApi::loadEntitiesById($albumId);
if ($ret) {
	print $ret->getAsHtml();
	exit;
}

$themeId = 'classic';
		
$s = $album->setTheme($themeId);
				
var_dump($album);

not quite working. the theme has not changed in the interface. when i look at the var_dump on the $album object, i see the theme listed in two places:

object(GalleryAlbumItem)#57 (23) {
  ["theme"]=>
  string(7) "classic"
  ["orderBy"]=>
  string(0) ""
  ["orderDirection"]=>
  string(3) "asc"
  ["canContainChildren"]=>
  int(1)
  ["description"]=>
  string(0) ""
  ["keywords"]=>
  string(0) ""
  ["ownerId"]=>
  int(463)
  ["summary"]=>
  string(0) ""
  ["title"]=>
  string(10) "timtest104"
  ["viewedSinceTimestamp"]=>
  int(1160441282)
  ["originationTimestamp"]=>
  int(1160441282)
  ["pathComponent"]=>
  string(10) "timtest104"
  ["parentId"]=>
  int(7)
  ["id"]=>
  int(464)
  ["creationTimestamp"]=>
  int(1160441282)
  ["isLinkable"]=>
  int(0)
  ["linkId"]=>
  NULL
  ["linkedEntity"]=>
  NULL
  ["modificationTimestamp"]=>
  int(1160441282)
  ["serialNumber"]=>
  int(2)
  ["entityType"]=>
  string(16) "GalleryAlbumItem"
  ["onLoadHandlers"]=>
  NULL
  ["_persistentStatus"]=>
  array(2) {
    ["flags"]=>
    int(0)
    ["originalValue"]=>
    array(21) {
      ["theme"]=>
      string(0) ""
      ["orderBy"]=>
      string(0) ""
      ["orderDirection"]=>
      string(3) "asc"
      ["canContainChildren"]=>
      int(1)
      ["description"]=>
      string(0) ""
      ["keywords"]=>
      string(0) ""
      ["ownerId"]=>
      int(463)
      ["summary"]=>
      string(0) ""
      ["title"]=>
      string(10) "timtest104"
      ["viewedSinceTimestamp"]=>
      int(1160441282)
      ["originationTimestamp"]=>
      int(1160441282)
      ["pathComponent"]=>
      string(10) "timtest104"
      ["parentId"]=>
      int(7)
      ["id"]=>
      int(464)
      ["creationTimestamp"]=>
      int(1160441282)
      ["isLinkable"]=>
      int(0)
      ["linkId"]=>
      NULL
      ["modificationTimestamp"]=>
      int(1160441282)
      ["serialNumber"]=>
      int(2)
      ["entityType"]=>
      string(16) "GalleryAlbumItem"
      ["onLoadHandlers"]=>
      NULL
    }
  }
}

the first bit was changed to 'classic' as expected, but this ["originalValue"]=>array appears to be the culprit...? Or am i hitting the wrong?

 
valiant

Joined: 2003-01-04
Posts: 32509
Posted: Tue, 2006-10-10 01:13

you'll need to save your changes.

if you want to change an entity (e.g. an album) with id $itemId, you need to:
1, acquire a write lock on $itemId
2. load the entity with $itemId
3. change attributes, e.g. $album->setTheme(..);
4. save the changes: $album->save();
5. release the write lock.

 
skyrover

Joined: 2004-06-29
Posts: 13
Posted: Tue, 2006-10-10 01:42
valiant wrote:
you'll need to save your changes.

if you want to change an entity (e.g. an album) with id $itemId, you need to:
1, acquire a write lock on $itemId
2. load the entity with $itemId
3. change attributes, e.g. $album->setTheme(..);
4. save the changes: $album->save();
5. release the write lock.

Excellent! Thank you for the guidence - here is the updated code block:

// get a write lock
list ($ret, $lockId) = GalleryCoreApi::acquireWriteLock($albumId);
if ($ret) {
	print $ret->getAsHtml();
	exit;
}

// load the album
list ($ret, $album) = GalleryCoreApi::loadEntitiesById($albumId);
if ($ret) {
	print $ret->getAsHtml();
	exit;
}

// change props
$s = $album->setTheme($themeId);

// save the album
$s = $album->save();

// release the lock
$ret = GalleryCoreApi::releaseLocks($lockId);
if ($ret) {
	print $ret->getAsHtml();
	exit;
}

I'll put this all back together as a complete script and post the whole thing as a unit again for other's reference.