$myUploadobj = new FileUploader();
     //creating instance of file.
     $image_type = 'image';
     $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile', true, true, $image_type);
     if ($file == false) {
         $msg = $myUploadobj->error;
         $error = TRUE;
     } else {
         $newuser->picture = $file;
     }
 }
 if ($error == FALSE) {
     try {
         $newuser->save();
         if (!empty($file)) {
             Storage::link($file, array("role" => "avatar", "user" => $newuser->user_id));
         }
         // creating message basic folders
         Message::create_basic_folders($newuser->user_id);
         //token creation
         $expires = 3600 * 24 * 5;
         //5days
         $token = $newuser->get_auth_token($expires);
         //        $user_url = PA::$url .'/mail_action.php?token='.$token.'&action=user';
         //        $edit_url = PA::$url .'/mail_action.php?token='.$token.'&action=profile';
         $user_url = "<a href=\"" . PA::$url . "/mail_action.php?token={$token}&action=user\">" . PA::$url . "/mail_action.php?token={$token}&action=user</a>";
         $edit_url = "<a href=\"" . PA::$url . "/mail_action.php?token={$token}&action=profile\">" . PA::$url . "/mail_action.php?token={$token}&action=profile</a>";
         PAMail::send("create_new_user_by_admin", $newuser, PA::$network_info, array('greeting.message' => $_POST['greeting_msg'], 'user.password' => $password, 'user.link' => $user_url, 'edit.link' => $edit_url));
         // adding default relation
         if ($newuser->user_id != SUPER_USER_ID) {
             User_Registration::add_default_relation($newuser->user_id, PA::$network_info);
 public static function resize_img($root_path, $root_url, $output_path, $max_x, $max_y, $picture, $alternate = NULL, $overwrite = FALSE, $resize_type = RESIZE_CROP)
 {
     $final_path = NULL;
     if ($alternate) {
         if (preg_match("|^http://|", $alternate)) {
             throw new CNException(BAD_PARAMETER, "Alternate image passed to resizing functions must not be a URL");
         }
         if (!preg_match("#^(files|Themes|images)/#", $alternate)) {
             throw new CNException(BAD_PARAMETER, "Alternate image passed to resizing functions must be relative to the web directory; {$alternate} is not valid");
         }
     }
     if ($picture instanceof StoredFile) {
         $stored_file = $picture;
         $pic_path = $picture->filename;
     } else {
         if (defined("NEW_STORAGE")) {
             // check for broken or deprecated calling code
             if (preg_match("|^files/files|", $picture)) {
                 throw new CNException(INVALID_ID, "Broken image ID - starting with files/files!");
             }
             if (preg_match("|^files/pa://|", $picture)) {
                 throw new CNException(INVALID_ID, "Broken image ID - check for code adding 'files/' to the start of a pa:// image URL");
             }
         }
         $stored_file = NULL;
         $image_path = NULL;
         if (getimagesize(PA::$project_dir . "/{$root_path}/{$picture}")) {
             $image_path = PA::$project_dir . "/{$root_path}";
         } else {
             if (getimagesize(PA::$core_dir . "/{$root_path}/{$picture}")) {
                 $image_path = PA::$core_dir . "/{$root_path}";
             } else {
                 if (getimagesize(PA::$project_dir . "/{$root_path}/{$alternate}")) {
                     $image_path = PA::$project_dir . "/{$root_path}";
                 } else {
                     if (getimagesize(PA::$core_dir . "/{$root_path}/{$alternate}")) {
                         $image_path = PA::$core_dir . "/{$root_path}";
                     }
                 }
             }
         }
         if ($picture && is_file("{$image_path}/{$picture}") && getimagesize("{$image_path}/{$picture}") !== false) {
             $pic_path = $picture;
         } else {
             if (!$alternate || !is_file("{$image_path}/{$alternate}")) {
                 // we could throw a FILE_NOT_FOUND exception here, but that
                 // breaks things, so instead we output an image tag with the
                 // requested size that refers to the original path.  this
                 // way the admin will see 404 errors in the log, and maybe
                 // fix what's wrong.
                 $final_path = $picture;
                 $width = $max_x;
                 $height = $max_y;
             } else {
                 $pic_path = $alternate;
             }
         }
     }
     if (!$final_path) {
         // if it's a png or gif, convert to png - so we don't lose transparency.  otherwise jpg.
         $path_parts = pathinfo($pic_path);
         $ext = strtolower($path_parts['extension']);
         switch ($ext) {
             case 'png':
             case 'gif':
                 $ext = 'png';
                 $mime_type = "image/png";
                 break;
             default:
                 $ext = 'jpg';
                 $mime_type = "image/jpeg";
                 break;
         }
         $prefix = ImageResize::$resize_type_prefixes[$resize_type];
         if (!$prefix) {
             throw new CNException(BAD_PARAMETER, "Invalid resize type: {$resize_type}");
         }
         // 'dim' string for file link
         $file_link_dim = $prefix . "-" . $max_x . "x" . $max_y;
         if ($stored_file) {
             // have we resized this already?
             $link = Storage::find_thumb($stored_file->file_id, $file_link_dim);
             if ($link) {
                 $thumb_id = $link['file_id'];
             } else {
                 // nope - we have to resize it now
                 $picture_full_path = $stored_file->getPath();
                 // temp output filename
                 $resized_fn_tmp = tempnam(ini_get("upload_tmp_dir"), "rsz");
                 $resized_fn = $resized_fn_tmp . "." . $ext;
                 rename($resized_fn_tmp, $resized_fn);
                 // leaf name, to show to users later on
                 $leaf = $stored_file->filename;
                 Logger::log("Resizing image '{$picture_full_path}' from Storage into {$resized_fn}", LOGGER_ACTION);
                 ImageResize::do_resize_to_max_side($picture_full_path, $resized_fn, $max_x, $max_y, $resize_type);
                 list($w, $h) = getimagesize($resized_fn);
                 // make the new file
                 $thumb_id = Storage::save($resized_fn, $file_link_dim . "-" . $leaf, "throwaway", $mime_type, array("width" => $w, "height" => $h));
                 unlink($resized_fn);
                 // link it to the original so we can find it again
                 Storage::link($thumb_id, array("role" => "thumb", "dim" => $file_link_dim, "file" => $stored_file->file_id));
             }
             // and return the details
             $thumb = Storage::get($thumb_id);
             return array('url' => $thumb->getURL(), 'width' => $thumb->width, 'height' => $thumb->height, 'size_attr' => 'width="' . $thumb->width . '" height="' . $thumb->height . '"');
         } else {
             // relative path to resized file
             $resized_pic_path = $prefix . "_" . $max_x . "x" . $max_y . "/" . preg_replace("/\\.[A-Za-z]+\$/", "", $pic_path) . ".{$ext}";
             // abs path to resized file
             $resized_fn = PA::$project_dir . "/{$root_path}/{$output_path}/{$resized_pic_path}";
             // only overwrite an existing file if it's out of date or we have been told to (via $overwrite)
             if (!file_exists($resized_fn) || filemtime($resized_fn) < filemtime("{$image_path}/{$pic_path}") || $overwrite) {
                 // make all path parts up to the image
                 if (!is_dir(dirname($resized_fn))) {
                     $mkdir_path = PA::$project_dir . "/{$root_path}/{$output_path}";
                     ImageResize::try_mkdir($mkdir_path);
                     foreach (explode("/", dirname($resized_pic_path)) as $path_part) {
                         $mkdir_path .= "/{$path_part}";
                         ImageResize::try_mkdir($mkdir_path);
                     }
                 }
                 ImageResize::do_resize_to_max_side("{$image_path}/{$pic_path}", $resized_fn, $max_x, $max_y, $resize_type);
                 clearstatcache();
             }
         }
         list($width, $height) = getimagesize($resized_fn);
         $final_path = "{$output_path}/" . dirname($resized_pic_path) . "/" . rawurlencode(basename($resized_pic_path));
     }
     return array('final_path' => $final_path, 'width' => $width, 'height' => $height, 'size_attr' => 'width="' . $width . '" height="' . $height . '"');
 }
 function register($params, $network_info = NULL)
 {
     $core_id = null;
     $picture = null;
     $picture_dimensions = null;
     $avatar = null;
     $avatar_dimensions = null;
     $avatar_small = null;
     $avatar_small_dimensions = null;
     $this->newuser = new User();
     // set API call variable
     $this->newuser->api_call = $this->api_call;
     // filter input parameters (this is the same as filter_all_post())
     $params = Validation::get_input_filter(FALSE)->process($params);
     $this->error = false;
     $mother_network_info = Network::get_mothership_info();
     $mother_extra = unserialize($mother_network_info->extra);
     if (@$mother_extra['captcha_required'] == NET_YES) {
         // added by Z.Hron - if captcha is required
         //Providing the capcha check
         if (md5(strtoupper($_POST['txtNumber'])) != $_SESSION['image_random_value']) {
             $_SESSION['image_is_logged_in'] = true;
             $_SESSION['image_random_value'] = '';
             $error_login = true;
             $this->error = true;
             $this->msg .= "\nPlease enter correct code";
         }
     }
     if (!$this->error) {
         $login_name = trim($params['login_name']);
         $first_name = trim($params['first_name']);
         $last_name = trim(@$params['last_name']);
         // not mandatory
         $email = trim($params['email']);
         $password = trim($params['password']);
         $confirm_password = trim($params['confirm_password']);
         if ($this->api_call == true) {
             $core_id = $params['core_id'];
             // TODO: validate URL
             $picture = trim($params['profile_picture_url']);
             $picture_dimensions = $params['profile_picture_dimensions'];
             $avatar = trim($params['profile_avatar_url']);
             $avatar_dimensions = $params['profile_avatar_dimensions'];
             $avatar_small = trim($params['profile_avatar_small_url']);
             $avatar_small_dimensions = $params['profile_avatar_small_dimensions'];
         }
         $date_created = !empty($params['date_created']) ? $params['date_created'] : null;
         $_years = PA::getYearsList();
         $dob_day = !empty($params['dob_day']) ? trim($params['dob_day']) : null;
         // General data (why? should be personal)
         $dob_month = !empty($params['dob_month']) ? trim($params['dob_month']) : null;
         // General data (why? should be personal)
         $dob_year = !empty($params['dob_year']) ? $_years[(int) trim($params['dob_year'])] : null;
         // General data (why? should be personal)
         $homeAddress1 = !empty($params['homeAddress1']) ? trim($params['homeAddress1']) : null;
         // General data
         $homeAddress2 = !empty($params['homeAddress2']) ? trim($params['homeAddress2']) : null;
         // General data
         $city = !empty($params['city']) ? trim($params['city']) : null;
         // General data
         $state = null;
         if ($params['state'] == -1) {
             // State/Province: Other selected
             $state = !empty($params['stateOther']) ? trim($params['stateOther']) : null;
             // General data
         } else {
             if ($params['state'] > 0) {
                 // one of US States selected
                 $state = !empty($params['state']) ? $this->states[(int) $params['state']] : null;
                 // General data
             }
         }
         $country = $params['country'] > 0 ? $this->countries[(int) $params['country']] : null;
         // General data
         $postal_code = !empty($params['postal_code']) ? trim($params['postal_code']) : null;
         // General data
         $phone = !empty($params['phone']) ? trim($params['phone']) : null;
         // General data
         $validate_array = array('login_name' => 'Login name', 'first_name' => 'First name', 'password' => 'Password', 'confirm_password' => 'Confirm password', 'email' => 'Email');
         $this->msg = '';
         $this->error = FALSE;
         foreach ($validate_array as $key => $value) {
             if (empty($params[$key])) {
                 $this->msg .= "\n" . $value . " is mandatory";
                 $this->error = TRUE;
                 header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
             }
         }
         if (strlen($this->msg) > 0) {
             $this->msg = "\n" . "Fields marked with * must not be left empty" . $this->msg;
         }
     }
     //$error_login = FALSE;
     if (!$this->error) {
         if (empty($login_name)) {
             $error_login = TRUE;
             $this->error = TRUE;
         }
         if (is_numeric($login_name)) {
             // Here we check the login name  is numeric or not
             if (strlen($this->msg) > 0) {
                 $this->msg .= "\n";
             }
             $this->msg .= "Login name must not be numeric";
             $error_login = TRUE;
             $this->error = TRUE;
         }
         if (is_numeric($first_name)) {
             // Here we check the first  name  is numeric or not
             if (strlen($this->msg) > 0) {
                 $this->msg .= "\n";
             }
             $this->msg .= "First name must not be numeric";
             $error_login = TRUE;
             $this->error = TRUE;
         }
         if (is_numeric($last_name)) {
             // Here we check the last name  is numeric or not
             if (strlen($this->msg) > 0) {
                 $this->msg .= "\n";
             }
             $this->msg .= "Last name must not be numeric";
             $error_login = TRUE;
             $this->error = TRUE;
         }
         if ($this->error == TRUE) {
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
         }
     }
     // if error occur than no need to check these errors
     if (!$this->error) {
         if (!Validation::validate_email($email)) {
             $email_invalid = TRUE;
             $this->array_of_errors['error_email'] = $email_invalid;
             $this->error = TRUE;
             $this->msg .= __('E-mail address is not valid.');
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
         }
         // Calculating Allowed Domains
         if (file_exists(PA::$project_dir . "/config/domain_names.txt")) {
             $domain_names_file = PA::$project_dir . "/config/domain_names.txt";
         } elseif (file_exists(PA::$core_dir . "/config/domain_names.txt")) {
             $domain_names_file = PA::$core_dir . "/config/domain_names.txt";
         } else {
             throw new Exception("Allowed Domains configuration file \"/config/domain_names.txt\" not found");
         }
         $allowed_domains = preg_split("/\\s+/", file_get_contents($domain_names_file));
         // Calcutating user domain
         $user_email = explode('@', $email);
         $user_domain = strtolower($user_email[1]);
         $found = 0;
         foreach ($allowed_domains as $i => $d) {
             if (!preg_match('/\\W/', $d)) {
                 continue;
             }
             // make proper regex
             $rx = preg_replace('/\\*/', '[^\\.]*', $d);
             if (preg_match("/{$rx}/", $user_domain)) {
                 $found++;
             }
         }
         if (!$found) {
             // show error
             $email_invalid = TRUE;
             $this->array_of_errors['error_email'] = $email_invalid;
             $this->error = TRUE;
             $this->msg .= __('The domain of your E-mail address is not in the list of allowed domains.');
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
         }
         if ($password != $confirm_password) {
             $this->msg .= "\nPassword and Confirm Password do not match.";
             $error_password_conf = TRUE;
             $this->error = TRUE;
         }
         if ($this->api_call == true) {
             // dont check maximum password length if this is an API call
             // this is so that the API call can accept an encrypted password
         } else {
             // this is not an API request, so check password length normally
             if (strlen($password) > PA::$password_max_length) {
                 $this->msg .= sprintf(__("\nThe password must be less than %d characters."), PA::$password_max_length);
                 $error_password_l = TRUE;
                 $this->error = TRUE;
                 header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
             }
         }
         if (strlen($password) < PA::$password_min_length) {
             $this->msg .= sprintf(__("\nThe password must be longer than %d characters."), PA::$password_min_length);
             $error_password_g = TRUE;
             $this->error = TRUE;
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_PRECONDITION_FAILED));
         }
     }
     if (!$this->error) {
         if (User::user_exist($login_name)) {
             $this->msg = "Login name {$login_name} is already taken";
             $error_login = TRUE;
             $this->error = TRUE;
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_CONFLICT));
         } elseif (User::user_existed($login_name)) {
             $this->msg = "Login name {$login_name} has been used in the past; it belongs to a deleted user.";
             $error_login = $this->error = TRUE;
             header(HttpStatusCodes::httpHeaderFor(HttpStatusCodes::HTTP_CONFLICT));
         }
         $this->array_of_errors = array("error_login" => @$error_login, "error_first_name" => @$error_first_name, "error_email" => @$error_email, "error_password_conf" => @$error_password_conf, "error_password_l" => @$error_password_l, "error_password_g" => @$error_password_g);
     }
     if ($this->error != TRUE) {
         $this->newuser->login_name = $login_name;
         //TODO: change to md5
         $this->newuser->password = $password;
         $this->newuser->first_name = $first_name;
         $this->newuser->last_name = $last_name;
         $this->newuser->email = $email;
         if ($date_created) {
             // for users inserted via import accounts script!
             $this->newuser->created = $date_created;
         }
         if ($this->api_call == true) {
             $this->newuser->core_id = $core_id;
             if ($picture != null && $picture != '') {
                 $this->newuser->picture = $picture;
                 $this->newuser->picture_dimensions = $picture_dimensions;
             } else {
                 $this->newuser->picture_dimensions = User::image_dimensions_to_array(0, 0);
             }
             if ($avatar != null && $avatar != '') {
                 $this->newuser->avatar = $avatar;
                 $this->newuser->avatar_dimensions = $avatar_dimensions;
             } else {
                 $this->newuser->avatar_dimensions = User::image_dimensions_to_array(0, 0);
             }
             if ($avatar_small != null && $avatar_small != '') {
                 $this->newuser->avatar_small = $avatar_small;
                 $this->newuser->avatar_small_dimensions = $avatar_small_dimensions;
             } else {
                 $this->newuser->avatar_small_dimensions = User::image_dimensions_to_array(0, 0);
             }
         } else {
             $this->newuser->picture = Storage::validateFileId(@$params['user_filename']);
         }
     }
     if ($this->error != TRUE) {
         try {
             $save_error = FALSE;
             $extra = unserialize($network_info->extra);
             if ($mother_extra['email_validation'] == NET_NO || $this->api_call == true) {
                 // if email validation not required
                 $this->newuser->is_active = ACTIVE;
             } else {
                 $this->newuser->is_active = UNVERIFIED;
             }
             $this->newuser->save();
             if ($this->newuser->picture) {
                 Storage::link($this->newuser->picture, array("role" => "avatar", "user" => $this->newuser->user_id));
             }
             /* The following code should now be obsolete as this is done in User->save() */
             // saving data in user profile data also -- for searching making more easier
             $data_array = array(array('uid' => $this->newuser->user_id, 'name' => 'first_name', 'value' => $this->newuser->first_name, 'type' => BASIC, 'perm' => 1), array('uid' => $this->newuser->user_id, 'name' => 'last_name', 'value' => $this->newuser->last_name, 'type' => BASIC, 'perm' => 1));
             $this->newuser->save_user_profile($data_array, BASIC);
             // saving default notification for user from network notification setting
             $user_notification = array();
             $profile = array();
             $user_notification = $extra['notify_members'];
             $user_notification['msg_waiting_blink'] = $extra['msg_waiting_blink'];
             $profile['settings']['name'] = 'settings';
             $profile['settings']['value'] = serialize($user_notification);
             $this->newuser->save_profile_section($profile, 'notifications');
             // default notification for user ends
             $desktop_images = User_Registration::get_default_desktopimage($this->newuser->user_id, $network_info);
             // code for adding default desktop image for user
             if ($desktop_images == "") {
                 $desktop_images = array('bay.jpg', 'everglade.jpg', 'bay_boat.jpg', 'delhi.jpg');
                 $rand_key = array_rand($desktop_images);
                 $desk_img = $desktop_images[$rand_key];
             } else {
                 $desk_img = $desktop_images;
             }
             $data_array = array(0 => array('uid' => $this->newuser->user_id, 'name' => 'user_caption_image', 'value' => $desk_img, 'type' => GENERAL, 'perm' => NONE), 1 => array('uid' => $this->newuser->user_id, 'name' => 'dob_day', 'value' => $dob_day, 'type' => GENERAL, 'perm' => NONE), 2 => array('uid' => $this->newuser->user_id, 'name' => 'dob_month', 'value' => $dob_month, 'type' => GENERAL, 'perm' => NONE), 3 => array('uid' => $this->newuser->user_id, 'name' => 'dob_year', 'value' => $dob_year, 'type' => GENERAL, 'perm' => NONE), 4 => array('uid' => $this->newuser->user_id, 'name' => 'dob', 'value' => $dob_year . '-' . $dob_month . '-' . $dob_day, 'type' => GENERAL, 'perm' => NONE), 5 => array('uid' => $this->newuser->user_id, 'name' => 'homeAddress1', 'value' => $homeAddress1, 'type' => GENERAL, 'perm' => NONE), 6 => array('uid' => $this->newuser->user_id, 'name' => 'homeAddress2', 'value' => $homeAddress2, 'type' => GENERAL, 'perm' => NONE), 7 => array('uid' => $this->newuser->user_id, 'name' => 'city', 'value' => $city, 'type' => GENERAL, 'perm' => NONE), 8 => array('uid' => $this->newuser->user_id, 'name' => 'state', 'value' => $state, 'type' => GENERAL, 'perm' => NONE), 9 => array('uid' => $this->newuser->user_id, 'name' => 'country', 'value' => $country, 'type' => GENERAL, 'perm' => NONE), 10 => array('uid' => $this->newuser->user_id, 'name' => 'postal_code', 'value' => $postal_code, 'type' => GENERAL, 'perm' => NONE), 11 => array('uid' => $this->newuser->user_id, 'name' => 'phone', 'value' => $phone, 'type' => GENERAL, 'perm' => NONE));
             //}
             $this->newuser->save_user_profile($data_array, GENERAL);
             if ($mother_extra['email_validation'] == NET_NO || $this->api_call == true) {
                 //if email validation is not required
                 // creating message basic folders
                 Message::create_basic_folders($this->newuser->user_id);
                 // adding default relation
                 if ($this->newuser->user_id != SUPER_USER_ID) {
                     User_Registration::add_default_relation($this->newuser->user_id, $network_info);
                 }
                 // adding default media as well as album
                 User_Registration::add_default_media($this->newuser->user_id, '', $network_info);
                 User_Registration::add_default_media($this->newuser->user_id, '_audio', $network_info);
                 User_Registration::add_default_media($this->newuser->user_id, '_video', $network_info);
                 User_Registration::add_default_blog($this->newuser->user_id);
                 //adding default link categories & links
                 User_Registration::add_default_links($this->newuser->user_id);
                 // adding header image
                 User_Registration::add_default_header($this->newuser->user_id);
                 // Making user member of a network if he is registering to PA from a network
                 if (!empty($network_info) && $network_info->type != PRIVATE_NETWORK_TYPE) {
                     $user_type = null;
                     $register_by_admin = false;
                     if ($this->api_call == true) {
                         // since this is an API call, default this member as a
                         // NETWORK_MEMBER since they already registered
                         $user_type = NETWORK_MEMBER;
                         // since this is an API call, act like it is registration by admin
                         $register_by_admin = true;
                     }
                     Network::join($network_info->network_id, $this->newuser->user_id, $user_type, $register_by_admin);
                     if ($this->api_call == false) {
                         // only send notification of network if this is NOT an API call
                         PANotify::send("network_join", $network_info, $this->newuser, array());
                     }
                 }
             }
         } catch (CNException $e) {
             $this->msg = $e->message;
             if ($e->code == USER_EMAIL_NOT_UNIQUE) {
                 $this->msg = "Email Address has already been taken, please enter other email address.";
             }
             $save_error = TRUE;
             if ($e->message == "The email address is invalid.") {
                 $email_invalid = TRUE;
                 $this->array_of_errors['error_email'] = $email_invalid;
             }
         }
     }
     if ($this->error == TRUE || $save_error == TRUE) {
         $this->msg = "Sorry! your registration failed. " . $this->msg;
         return FALSE;
     }
     // success!
     // give Login User permissions to new user is moved to  Network::join() now!
     /*
      $this->newuser->set_user_role(array(LOGINUSER_ROLE));
     */
     return TRUE;
 }
 private function handleEdit($request_data)
 {
     $this->err = '';
     $data = $this->filter($request_data);
     // handle photo upload
     if (!empty($_FILES)) {
         foreach ($_FILES as $field_name => $file_info) {
             if (!empty($file_info['name'])) {
                 $uploadfile = PA::$upload_path . basename($_FILES[$field_name]['name']);
                 $myUploadobj = new FileUploader();
                 $file = $myUploadobj->upload_file(PA::$upload_path, $field_name, true, true, 'image');
                 if ($file == false) {
                     $msg = $myUploadobj->error;
                     $this->err .= sprintf(__('Please upload a valid Game Image in %s'), ucfirst($field_name)) . "<br/>";
                     continue;
                 } else {
                     Storage::link($file, array("role" => "game_image", "user" => PA::$login_user->user_id));
                     $data[$field_name] = $file;
                 }
             } else {
                 if (!empty($this->entity->attributes[$field_name])) {
                     $data[$field_name] = $this->entity->attributes[$field_name];
                 }
             }
         }
     }
     if (empty($data['name'])) {
         $this->err .= __("Please supply a name.") . "<br/>";
     }
     if (empty($this->err)) {
         // sync it
         TypedGroupEntity::sync($data);
     }
 }
             $networks_data[$counter]['caption'] = $_POST['caption'][$counter];
         } else {
             $networks_data[$counter]['caption'] = null;
         }
         $image_file = 'network_image_' . $counter;
         if (!empty($_FILES[$image_file]['name'])) {
             //validating and then uploading the network image.
             $uploader = new FileUploader();
             //creating instance of file.
             $file = $uploader->upload_file(PA::$upload_path, $image_file, true, true, 'image');
             if ($file == false) {
                 $message[] = __(' For showcased network ') . ($counter + 1) . ', ' . $uploader->error;
                 $networks_data[$counter]['network_image'] = null;
             } else {
                 $networks_data[$counter]['network_image'] = $file;
                 Storage::link($file, array("role" => "showcased_net"));
             }
         } else {
             if (!empty($_POST['current_network_image'][$counter])) {
                 //getting the previously added image from the hidden form field.
                 $networks_data[$counter]['network_image'] = $_POST['current_network_image'][$counter];
             } else {
                 //setting the image to null.
                 $networks_data[$counter]['network_image'] = null;
             }
         }
     }
     //end for
 } else {
     if ($section == 'configure') {
         if (!empty($_POST['show_splash_page']) && $_POST['show_splash_page'] == ACTIVE) {
     );
     $network->set_params($data);
    */
    $msg = "";
    try {
        $nid = $network->save();
        if (sizeof($nid)) {
            $msg = __("Default settings for the network has been saved");
            if (!empty($_REQUEST['config_action']) && $_REQUEST['config_action'] == 'store_as_defaults') {
                $export_config = new NetworkConfig();
                $export_config->buildNetworkSettings($network);
                $export_config->storeSettingsLocal();
                $msg = 'Network default configuration file "' . $export_config->settings_file . '" successfully updated.';
            }
            if (!empty($file)) {
                Storage::link($file, array("role" => "header"));
                // network header
            }
        }
    } catch (CNException $e) {
        $error = TRUE;
        $error_msg = "{$e->message}";
    }
}
//..end of $_POST
function setup_module($column, $module, $obj)
{
    global $form_data, $ack_message, $configure_permission;
    if (!$configure_permission) {
        return 'skip';
    }
 function initializeModule($request_method, $request_data)
 {
     global $error_msg;
     $error = false;
     $msg = array();
     $form_data = NULL;
     $edit = false;
     $message = NULL;
     // check permissions!
     $user_may = false;
     $user_may = PermissionsHandler::can_user(PA::$login_uid, array('permissions' => 'manage_ads'));
     // check for manageads of group permissions
     if (!empty($_REQUEST['gid']) && !$user_may) {
         // we do this checl only if the user is not already permitted to manage ads
         $gp_access = PermissionsHandler::can_group_user(PA::$login_uid, $_REQUEST['gid'], array('permissions' => 'manage_ads'));
         $user_may = $gp_access;
     }
     if (!$user_may) {
         $error_msg = __("You do not have permission to manage Ads.");
         return "skip";
     }
     // paging
     if (!empty($request_data['page'])) {
         $this->Paging["page"] = (int) $request_data['page'];
     }
     if (!empty($request_data['action']) && $request_data['action'] == 'edit' && !empty($request_data['ad_id'])) {
         $edit = TRUE;
         $res = Advertisement::get($params = NULL, $condition = array('ad_id' => (int) $request_data['ad_id']));
         if (!empty($res)) {
             $form_data['ad_id'] = $res[0]->ad_id;
             $form_data['ad_image'] = $res[0]->ad_image;
             $form_data['ad_script'] = $res[0]->ad_script;
             $form_data['ad_url'] = $res[0]->url;
             $form_data['ad_title'] = $res[0]->title;
             $form_data['ad_description'] = $res[0]->description;
             $form_data['ad_page_id'] = $res[0]->page_id;
             $form_data['orientation'] = $res[0]->orientation;
             $form_data['created'] = $res[0]->created;
         }
     } else {
         if (!empty($request_data['action']) && $request_data['action'] == 'delete' && !empty($request_data['ad_id'])) {
             if (!empty($request_data['ad_id'])) {
                 try {
                     Advertisement::delete((int) $request_data['ad_id']);
                     $error_msg = 19013;
                 } catch (CNException $e) {
                     $msg[] = $e->message;
                 }
             }
         } else {
             if (!empty($request_data['action']) && !empty($request_data['ad_id'])) {
                 $update = false;
                 switch ($request_data['action']) {
                     case 'disable':
                         $field_value = DELETED;
                         $msg_id = 19010;
                         $update = true;
                         break;
                     case 'enable':
                         $field_value = ACTIVE;
                         $msg_id = 19011;
                         $update = true;
                         break;
                 }
                 if ($update) {
                     $update_fields = array('is_active' => $field_value);
                     $condition = array('ad_id' => $request_data['ad_id']);
                     try {
                         Advertisement::update($update_fields, $condition);
                         $error_msg = $msg_id;
                     } catch (CNException $e) {
                         $msg[] = $e->message;
                     }
                 }
             }
         }
     }
     $advertisement = new Advertisement();
     if (!$error && $request_method == 'POST' && $request_data['btn_apply_name']) {
         // if page is submitted
         if (!empty($request_data['ad_id'])) {
             $advertisement->ad_id = $request_data['ad_id'];
             $advertisement->created = $request_data['created'];
             $msg_id = 19007;
         } else {
             $msg_id = 19008;
             $advertisement->created = time();
         }
         if (!empty($_FILES['ad_image']['name'])) {
             $filename = $_FILES['ad_image']['name'];
             $uploadfile = PA::$upload_path . basename($filename);
             $myUploadobj = new FileUploader();
             $file = $myUploadobj->upload_file(PA::$upload_path, 'ad_image', TRUE, TRUE, 'image');
             $advertisement->ad_image = $form_data['ad_image'] = $file;
             if ($file == FALSE) {
                 $error = TRUE;
                 $msg[] = $myUploadobj->error;
             }
         } else {
             if (!empty($request_data['ad_id'])) {
                 $advertisement->ad_image = $request_data['edit_image'];
             }
         }
         if (empty($request_data['ad_url']) && empty($request_data['ad_script'])) {
             $error = TRUE;
             $msg[] = MessagesHandler::get_message(19012);
         }
         if (!empty($request_data['ad_url'])) {
             // if url is given then validate
             $request_data['ad_url'] = Validation::validate_url($request_data['ad_url']);
             if (!Validation::isValidURL($request_data['ad_url'])) {
                 $error = TRUE;
                 $msg[] = MessagesHandler::get_message(19009);
             }
         }
         $advertisement->user_id = PA::$login_uid;
         $advertisement->url = $form_data['ad_url'] = $request_data['ad_url'];
         $advertisement->ad_script = $form_data['ad_script'] = $request_data['ad_script'];
         $advertisement->title = $form_data['ad_title'] = $request_data['ad_title'];
         $advertisement->description = $form_data['ad_description'] = $request_data['ad_description'];
         $advertisement->page_id = $form_data['ad_page_id'] = $request_data['ad_page_id'];
         $advertisement->orientation = $form_data['orientation'] = $request_data['x_loc'] . ',' . $request_data['y_loc'];
         $advertisement->changed = time();
         $advertisement->is_active = ACTIVE;
         if (!empty($_REQUEST['gid'])) {
             $advertisement->group_id = (int) $_REQUEST['gid'];
         }
         if (!$error) {
             try {
                 $ad_id = $advertisement->save();
                 if (!empty($file)) {
                     Storage::link($file, array("role" => "ad", "ad" => $ad_id));
                 }
                 $error_msg = $msg_id;
             } catch (CNException $e) {
                 $error_msg = $e->message;
             }
         } else {
             $error_msg = implode("<br/>", $msg);
         }
     }
     $this->form_data = $form_data;
     $this->edit = $edit;
     $this->message = $message;
 }
$error = FALSE;
if (@$_GET['msg_id']) {
    $error_msg = MessagesHandler::get_message($_GET['msg_id']);
}
$file = null;
if (@$_POST['submit'] == 'Submit') {
    if (!empty($_FILES['userfile_0']['name'])) {
        $myUploadobj = new FileUploader();
        //creating instance of file.
        $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile_0', TRUE);
        if (!$file) {
            $msg = $myUploadobj->error;
            $error = TRUE;
        } else {
            $msg = __('Successfully updated');
            Storage::link($file, array("role" => "tour_img"));
        }
    }
    $data = array();
    if ($_POST["userfile_url_0"]) {
        $data[0]['url'] = $_POST["userfile_url_0"];
    }
    if ($_POST['caption'][0]) {
        $data[0]['title'] = $_POST['caption'][0];
    }
    $data[0]['file_name'] = Storage::validateFileId($file ? $file : $_POST['userimage_0']);
    $data = serialize($data);
    $id = 2;
    // stands for the Update for Take Tour
    if (!$error) {
        ModuleData::update($data, $id);
                $msg = $myUploadobj->error;
                $error = TRUE;
            } else {
                $error_file = FALSE;
                $msg = 'successfully updated';
            }
        }
        if ($_POST["userfile_url_{$i}"]) {
            $data[$i]['url'] = $_POST["userfile_url_{$i}"];
        }
        if ($_POST['caption'][$i]) {
            $data[$i]['title'] = $_POST['caption'][$i];
        }
        if (!empty($_FILES['userfile_' . $i]['name'])) {
            $data[$i]['file_name'] = $file;
            Storage::link($file, array("role" => "emblem"));
        } else {
            $data[$i]['file_name'] = $_POST['userimage_' . $i];
        }
    }
    $data = serialize($data);
    $id = 1;
    // stands for the Update for emblum data
    if (!$error) {
        ModuleData::update($data, $id);
        // call the ModuleData to update the data
    }
}
//render the page
$page = new PageRenderer("setup_module", PAGE_MANAGE_EMBLEM, "Manage Emblem", 'container_two_column.tpl', 'header.tpl', PRI, HOMEPAGE, PA::$network_info);
if (!empty($msg)) {
 /** !!
  * This handles the data that is POSTed back to the page upon
  * submission of the form. There is a lot happening in here,
  * but it basically looks at the submitted data, figures out
  * what it is supposed to do with it (based on if the group is
  * being created or modified), then creates a new group or
  * updates the current data using the {@link handle_entity() } method.
  *
  * @param array $request_data  All of the data POSTed back to the form.
  */
 public function handlePOST($request_data)
 {
     require_once "web/includes/classes/CNFileUploader.php";
     require_once "api/CNActivities/CNActivities.php";
     require_once "api/cnapi_constants.php";
     if ($request_data['addgroup']) {
         filter_all_post($request_data);
         $groupname = trim($request_data['groupname']);
         $body = trim($request_data['groupdesc']);
         $tag_entry = trim($request_data['group_tags']);
         $group_category = $request_data['group_category'];
         $header_image = NULL;
         $header_image_action = @$request_data['header_image_action'];
         $display_header_image = @$request_data['display_header_image'];
         $collection_id = NULL;
         $this->extra = NULL;
         if ($request_data['ccid']) {
             $collection_id = (int) $request_data['ccid'];
             $group = new Group();
             $group->load($collection_id);
             // preserve group info we are not editing in this module
             // load group extra
             $extra = $group->extra;
             if (!empty($extra)) {
                 $this->extra = unserialize($extra);
             }
             $header_image = $group->header_image;
             $header_image_action = $group->header_image_action;
             $display_header_image = $group->display_header_image;
         }
         $access = 0;
         // default access is 0 means public
         $reg_type = $request_data['reg_type'];
         if ($reg_type == REG_INVITE) {
             // if reg. type = "Invite" access is PRIVATE
             $access = ACCESS_PRIVATE;
         }
         $is_moderated = 0;
         // is moderated is 0 means contents appear immediately
         $group_tags = $request_data['group_tags'];
         if (empty($request_data['groupname'])) {
             $error_msg = 90222;
         } else {
             if (empty($group_category) && empty($error_msg)) {
                 $error_msg = 90224;
             } else {
                 if (empty($error_msg)) {
                     try {
                         if (empty($_FILES['groupphoto']['name'])) {
                             $upfile = $request_data['file'];
                         } else {
                             $myUploadobj = new FileUploader();
                             //creating instance of file.
                             $image_type = 'image';
                             $file = $myUploadobj->upload_file(PA::$upload_path, 'groupphoto', true, true, $image_type);
                             if ($file == false) {
                                 throw new CNException(GROUP_PARAMETER_ERROR, __("File upload error: ") . $myUploadobj->error);
                             }
                             $upfile = $file;
                             $avatar_uploaded = TRUE;
                         }
                         $exception_message = NULL;
                         $result = Group::save_new_group($collection_id, $_SESSION['user']['id'], $groupname, $body, $upfile, $group_tags, $group_category, $access, $reg_type, $is_moderated, $header_image, $header_image_action, $display_header_image, $this->extra);
                         $ccid = $result;
                         $exception_message = 'Group creation failed: ' . $result;
                         if (!is_numeric($result)) {
                             throw new CNException(GROUP_CREATION_FAILED, $exception_message);
                         } else {
                             if (@$avatar_uploaded) {
                                 Storage::link($upfile, array("role" => "avatar", "group" => (int) $result));
                             }
                             if (@$header_uploaded) {
                                 Storage::link($header_image, array("role" => "header", "group" => (int) $result));
                             }
                             $this->gid = $this->id = $result;
                             if (empty($request_data['gid'])) {
                                 $mail_type = $activity = 'group_created';
                                 $act_text = ' created a new group';
                             } else {
                                 $mail_type = $activity = 'group_settings_updated';
                                 $act_text = ' changed group settings ';
                             }
                             $group = new Group();
                             $group->load((int) $this->gid);
                             PANotify::send($mail_type, PA::$network_info, PA::$login_user, $group);
                             // notify network onwer
                             $_group_url = PA::$url . PA_ROUTE_GROUP . '/gid=' . $result;
                             $group_owner = new User();
                             $group_owner->load((int) $_SESSION['user']['id']);
                             $activity_extra['info'] = $group_owner->first_name . $act_text;
                             $activity_extra['group_name'] = $groupname;
                             $activity_extra['group_id'] = $result;
                             $activity_extra['group_url'] = $_group_url;
                             $extra = serialize($activity_extra);
                             $object = $result;
                             if ($reg_type != REG_INVITE) {
                                 Activities::save($group_owner->user_id, $activity, $object, $extra);
                             }
                             // if we reached here than the group is created
                             if (empty($request_data['gid'])) {
                                 // when a new group is created
                                 // so, we need to assign group admin role to group owner now:
                                 $role_extra = array('user' => false, 'network' => false, 'groups' => array($this->gid));
                                 $user_roles[] = array('role_id' => GROUP_ADMIN_ROLE, 'extra' => serialize($role_extra));
                                 $group_owner->set_user_role($user_roles);
                             }
                             if (!empty(PA::$config->useTypedGroups) && !empty($request_data['type'])) {
                                 $this->gid = $this->id;
                                 switch ($request_data['op']) {
                                     case 'create_entity':
                                     case 'edit_entity':
                                         $this->handleEntity($request_data);
                                         break;
                                 }
                             }
                         }
                     } catch (CNException $e) {
                         if ($e->code == GROUP_PARAMETER_ERROR) {
                             $error_msg = $e->message;
                             if (empty($groupname)) {
                                 $error_msg = 90222;
                             } else {
                                 if (empty($group_category)) {
                                     $error_msg = 90224;
                                 }
                             }
                         } else {
                             $error_msg = $e->message;
                         }
                     }
                 }
             }
         }
     }
     //if form is posted
     $msg_array = array();
     $msg_array['failure_msg'] = @$error_msg;
     $msg_array['success_msg'] = !empty($this->id) ? 90231 : 90221;
     $redirect_url = PA::$url . PA_ROUTE_GROUP;
     $query_str = "?gid=" . @$result;
     set_web_variables($msg_array, $redirect_url, $query_str);
 }
     //try following line
     $network = new Network();
     $network->set_params($data);
     try {
         $nid = $network->save();
         PA::$network_info = get_network_info();
         //refreshing the network_info after saving it.
         $error_msg = 'Network Information Successfully Updated';
         if (!empty($_REQUEST['config_action']) && $_REQUEST['config_action'] == 'store_as_defaults') {
             $export_config = new NetworkConfig();
             $export_config->buildNetworkSettings($network);
             $export_config->storeSettingsLocal();
             $error_msg = 'Network default configuration file "' . $export_config->settings_file . '" successfully updated.';
         }
         if (!empty($new_inner_logo_image)) {
             Storage::link($new_inner_logo_image, array("role" => "avatar"));
         }
         //set $form_data['reciprocated_relationship']if reciprocated relationship is saved
         $form_data['reciprocated_relationship'] = $network_basic_controls['reciprocated_relationship'];
         $form_data['email_validation'] = $network_basic_controls['email_validation'];
         $form_data['captcha_required'] = $network_basic_controls['captcha_required'];
         $form_data['show_people_with_photo'] = $network_basic_controls['show_people_with_photo'];
         $form_data['top_navigation_bar'] = $network_basic_controls['top_navigation_bar'];
         $form_data['language_bar_enabled'] = $network_basic_controls['language_bar_enabled'];
         $form_data['default_language'] = $network_basic_controls['default_language'];
         $form_data['network_content_moderation'] = $network_basic_controls['network_content_moderation'];
     } catch (CNException $e) {
         $error = TRUE;
         $error_msg = "{$e->message}";
     }
 }
 /** !!
  * Get the uploaded image and give an error if it is empty.  Then check to
  * see if it is a user, group or network image. Apply it as the desktop 
  * image of the appropriate type. Finally refresh the page.
  * @param array $request_data contains a from with the desktop image data
  */
 private function handlePOST_applyDesktopImage($request_data)
 {
     global $error, $error_msg;
     $form_data = $request_data['form_data'];
     if (!empty($_FILES['header_image']['name'])) {
         $uploadfile = PA::$upload_path . basename($_FILES['header_image']['name']);
         $myUploadobj = new FileUploader();
         //creating instance of file.
         $image_type = 'image';
         $file = $myUploadobj->upload_file(PA::$upload_path, 'header_image', true, true, $image_type);
         if ($file == false) {
             $error_msg = $myUploadobj->error;
             $error = TRUE;
         } else {
             $header_image = $file;
             Storage::link($header_image, array("role" => "header", "user" => PA::$login_user->user_id));
         }
     } else {
         $header_image = $form_data['header_image_name'];
     }
     switch ($this->settings_type) {
         case 'user':
             $user = $this->shared_data['user_info'];
             $user->set_profile_field(GENERAL, "desktop_image_display", $form_data['desktop_image_display']);
             $user->set_profile_field(GENERAL, "desktop_image_action", $form_data['header_image_option']);
             $user->set_profile_field(GENERAL, "user_caption_image", $header_image);
             break;
         case 'group':
             $group =& $this->shared_data['group_info'];
             $header_img = array('display_header_image' => $form_data['desktop_image_display'], 'header_image_action' => $form_data['header_image_option'], 'header_image' => $header_image);
             $group->save_group_theme($header_img);
             $group->header_image = $header_image;
             $group->header_image_action = $form_data['header_image_option'];
             $group->display_header_image = $form_data['desktop_image_display'];
             break;
         case 'network':
             $network =& $this->shared_data['network_info'];
             $extra =& $this->shared_data['extra'];
             $extra['basic']['header_image']['name'] = $header_image;
             $extra['basic']['header_image']['option'] = $form_data['header_image_option'];
             $extra['basic']['header_image']['display'] = $form_data['desktop_image_display'];
             $data = array('extra' => serialize($extra), 'network_id' => $network->network_id, 'changed' => time());
             $network->set_params($data);
             try {
                 $nid = $network->save();
                 $network = get_network_info();
                 // refreshing the network info
             } catch (PAException $e) {
                 $error_msg = "{$e->message}";
             }
             break;
     }
     unset($_FILES);
     unset($request_data['form_data']);
     $this->controller->redirect($this->url);
 }
function image_uploaded()
{
    if (empty($_FILES['userfile']['name'])) {
        return false;
    } else {
        $uploadfile = PA::$upload_path . basename($_FILES['userfile']['name']);
        $myUploadobj = new FileUploader();
        // creating instance of file.
        $image_type = 'image';
        $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile', true, true, $image_type);
        if ($file == false) {
            throw new CNException(INVALID_ID, "Error uploading image " . $myUploadobj->error);
        } else {
            Storage::link($file, array("role" => "event_banner", "user" => PA::$login_user->user_id));
            return $file;
        }
    }
}
 function testStorage()
 {
     // test Storage - public API
     // store test.txt
     echo "saving test.txt with a crazy name\n";
     $file_id = Storage::save('test.txt', 'O*Bc3wukygfsT@#($0876)$!@#*+_][.txt');
     echo "resulting file_id = {$file_id}\n";
     $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id));
     $this->assertEquals($file->link_count, 0);
     $this->assertEquals($file->last_linked, NULL);
     $file_path = Storage::getPath($file_id);
     $file_url = Storage::getURL($file_id);
     echo "getPath({$file_id}) -> {$file_path}\n";
     echo "getURL({$file_id}) -> {$file_url}\n";
     $this->assertTrue(strpos($file_path, PA::$path . "/web/files/") === 0);
     $this->assertTrue(strpos($file_url, PA::$url) === 0);
     // link it in somewhere
     $link_id = Storage::link($file_id, array('role' => 'avatar', 'user' => 1));
     echo "linked it in as avatar for user 1; link_id = {$link_id}\n";
     $link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($link_id));
     $this->assertEquals($link->file_id, $file_id);
     $file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($file_id));
     $this->assertEquals($file->link_count, 1);
     $this->assertNotEquals($file->last_linked, NULL);
     // another file
     $child_file_id = Storage::save('test2.txt', 'this is the child file.jpg', 'throwaway', 'image/jpeg');
     echo "child file: {$child_file_id}\n";
     $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id));
     $child_file_path = Storage::getPath($child_file_id);
     $child_file_url = Storage::getURL($child_file_id);
     echo "getPath({$child_file_id}) -> {$child_file_path}\n";
     echo "getURL({$child_file_id}) -> {$child_file_url}\n";
     $this->assertTrue(strpos($child_file_path, PA::$path . "/web/files/") === 0);
     $this->assertTrue(strpos($child_file_url, PA::$url) === 0);
     // link child file in as a thumbnail of first file
     $child_link_id = Storage::link($child_file_id, array('role' => 'thumb', 'file' => $file_id, 'dim' => '123x123'));
     echo "child link id: {$child_link_id}\n";
     $child_link = Dal::query_one_object("SELECT * FROM file_links WHERE link_id=?", array($child_link_id));
     $this->assertEquals($child_link->file_id, $child_file_id);
     $this->assertEquals($child_link->parent_file_id, $file_id);
     $child_file = Dal::query_one_object("SELECT * FROM files WHERE file_id=?", array($child_file_id));
     $this->assertEquals($child_file->link_count, 1);
     $this->assertNotEquals($child_file->last_linked, NULL);
     // this should fail (missing role)
     try {
         Storage::link($file_id, array("user" => 1));
         $this->fail("Expected exception");
     } catch (PAException $e) {
         $this->assertEquals($e->getCode(), BAD_PARAMETER);
     }
     // this should fail (missing network)
     try {
         Storage::link($file_id, array("role" => "header", "group" => 42));
         $this->fail("Expected exception");
     } catch (PAException $e) {
         $this->assertEquals($e->getCode(), BAD_PARAMETER);
     }
     // this should fail (network not valid)
     try {
         Storage::link($file_id, array("role" => "thumb", "network" => 1, "file" => $file_id, "dim" => "123x123"));
         $this->fail("Expected exception");
     } catch (PAException $e) {
         $this->assertEquals($e->getCode(), BAD_PARAMETER);
     }
     // this should fail (parent_file_id == file_id)
     try {
         $link_id = Storage::link($file_id, array("role" => "thumb", "file" => $file_id, "dim" => "123x123"));
         $this->fail("Expected exception");
     } catch (PAException $e) {
         $this->assertEquals($e->getCode(), BAD_PARAMETER);
     }
     // Now unlink the two files we just created ...
     // unlink the first - but don't delete it
     Storage::unlink($file_id, $link_id, FALSE);
     // make sure it's gone
     $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($link_id)), NULL);
     // the file should still be there, with zero links, though
     $file = Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id));
     $this->assertNotEquals($file, NULL);
     $this->assertEquals($file->link_count, 0);
     // try a bad unlink operation
     try {
         Storage::unlink($file_id, $child_link_id);
         $this->fail("Expected exception");
     } catch (PAException $e) {
         $this->assertEquals($e->getCode(), FILE_NOT_FOUND);
     }
     // unlink and delete the second
     Storage::unlink($child_file_id, $child_link_id);
     // make sure it's gone
     $this->assertEquals(Dal::query_one("SELECT * FROM file_links WHERE link_id=?", array($child_link_id)), NULL);
     // and make sure the file is gone too
     $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($child_file)), NULL);
     // reap unlinked files (immediately - no grace period)
     Storage::cleanupFiles(-1, -1);
     // make sure the first file is now gone
     $this->assertEquals(Dal::query_one("SELECT * FROM files WHERE file_id=?", array($file_id)), NULL);
 }
 private function handlePOST_addChild($request_data)
 {
     global $error_msg;
     $error = FALSE;
     $login_name = trim($_POST['login_name']);
     $first_name = stripslashes(trim($_POST['first_name']));
     $last_name = stripslashes(trim($_POST['last_name']));
     $email = trim($_POST['email']);
     $password = trim($_POST['password']);
     $use_parent_email = $_POST['use_parent_email'];
     //echo "<pre>".print_r($_POST, 1)."</pre>"; die();
     if (!isset($_POST['state'])) {
         if (isset($_POST['stateOther'])) {
             $_POST['state'] = $_POST['stateOther'];
         }
     }
     if (isset($_POST['stateOther'])) {
         unset($_POST['stateOther']);
     }
     $msg = NULL;
     if (!Validation::validate_email($email) && !empty($_POST['email'])) {
         $email_invalid = TRUE;
         $error = TRUE;
         $msg .= '<br> Email address is not valid';
     }
     if (User::user_exist($login_name)) {
         $msg = "Username {$login_name} is already taken";
         $error = TRUE;
     }
     if ($error == FALSE) {
         $newuser = new User();
         $newuser->login_name = $login_name;
         $newuser->password = $password;
         $newuser->first_name = $first_name;
         $newuser->last_name = $last_name;
         $newuser->email = $email;
         $newuser->is_active = ACTIVE;
         if (!empty($_FILES['userfile']['name'])) {
             $myUploadobj = new FileUploader();
             //creating instance of file.
             $image_type = 'image';
             $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile', true, true, $image_type);
             if ($file == false) {
                 $msg = $myUploadobj->error;
                 $error = TRUE;
             } else {
                 $newuser->picture = $file;
             }
         }
         if ($error == FALSE) {
             try {
                 if ($use_parent_email) {
                     $newuser->save($check_unique_email = false);
                 } else {
                     $newuser->save($check_unique_email = true);
                 }
                 if (!empty($file)) {
                     Storage::link($file, array("role" => "avatar", "user" => $newuser->user_id));
                 }
                 // creating message basic folders
                 Message::create_basic_folders($newuser->user_id);
                 // adding default relation
                 if ($newuser->user_id != SUPER_USER_ID) {
                     User_Registration::add_default_relation($newuser->user_id, PA::$network_info);
                 }
                 // adding default media as well as album
                 User_Registration::add_default_media($newuser->user_id, '', PA::$network_info);
                 User_Registration::add_default_media($newuser->user_id, '_audio', PA::$network_info);
                 User_Registration::add_default_media($newuser->user_id, '_video', PA::$network_info);
                 User_Registration::add_default_blog($newuser->user_id);
                 //adding default link categories & links
                 User_Registration::add_default_links($newuser->user_id);
                 // code for adding default desktop image for user
                 $desk_img = uihelper_add_default_desktopimage($newuser->user_id);
                 if (empty($desk_img)) {
                     $desktop_images = array('bay.jpg', 'everglade.jpg', 'bay_boat.jpg', 'delhi.jpg');
                     $rand_key = array_rand($desktop_images);
                     $desk_img = $desktop_images[$rand_key];
                 }
                 $states = array_values(PA::getStatesList());
                 $countries = array_values(PA::getCountryList());
                 $profile_keys = array('dob_day', 'dob_month', 'dob_year', 'homeAddress1', 'homeAddress2', 'city', 'state', 'country', 'postal_code', 'phone', 'use_parent_email');
                 $profile_data = array();
                 filter_all_post($_POST);
                 //filters all data of html
                 foreach ($profile_keys as $k => $pkey) {
                     if (!empty($_POST[$pkey])) {
                         if ($pkey == 'state' && $_POST[$pkey] >= 0) {
                             $prof_rec = array('uid' => $newuser->user_id, 'name' => $pkey, 'value' => $states[$_POST[$pkey]], 'type' => GENERAL, 'perm' => 1);
                         } else {
                             if ($pkey == 'country' && $_POST[$pkey] >= 0) {
                                 $prof_rec = array('uid' => $newuser->user_id, 'name' => $pkey, 'value' => $countries[$_POST[$pkey]], 'type' => GENERAL, 'perm' => 1);
                             } else {
                                 $prof_rec = array('uid' => $newuser->user_id, 'name' => $pkey, 'value' => $_POST[$pkey], 'type' => GENERAL, 'perm' => 1);
                             }
                         }
                         $profile_data[] = $prof_rec;
                     }
                 }
                 $profile_data[] = array('uid' => $newuser->user_id, 'name' => 'user_caption_image', 'value' => $desk_img, 'type' => GENERAL, 'perm' => 1);
                 //     echo "<pre>".print_r($profile_data,1)."</pre>";
                 $newuser->save_user_profile($profile_data, GENERAL);
                 //if new user is created in a network then he must set as a joined user
                 if (!empty(PA::$network_info)) {
                     $by_admin = true;
                     Network::join(PA::$network_info->network_id, $newuser->user_id, NETWORK_MEMBER, $by_admin);
                     // $by_admin = true overrides the
                     // user_waiting status if it would get set
                     // this is an admin action, so we want it to happen in any case
                 }
                 $user_joined = $this->family->join((int) $newuser->user_id, $newuser->email, null);
                 if ($user_joined) {
                     // deal with TypedGroup Relations
                     require_once "api/Entity/TypedGroupEntityRelation.php";
                     $type = 'child';
                     TypedGroupEntityRelation::set_relation($newuser->user_id, $this->family->collection_id, $type);
                     if ($type == 'child') {
                         // if user type == child remove LoginUser and GroupMember roles
                         $newuser->delete_user_role();
                         // then assign 'Child' role only
                         $_extra = serialize(array('user' => false, 'network' => false, 'groups' => array($this->family->collection_id)));
                         $user_roles[] = array('role_id' => CHILD_MEMBER_ROLE, 'extra' => $_extra);
                         $newuser->set_user_role($user_roles);
                     }
                 }
                 $msg = __("Child's account was successfully created");
             } catch (PAException $e) {
                 $msg = $e->message;
             }
         }
         // end if
     }
     //end if
     $error_msg = $msg;
 }
 /** !!
  ************************************************************************
  * The following methods take the request data, validate it, parse it,
  * and store it if there were no previous errors.
  ************************************************************************
  */
 public function basicProfileSave($request_data)
 {
     global $error_msg;
     $this->isError = TRUE;
     if (empty($request_data['first_name'])) {
         $this->message = __('Fields marked with * can not be empty, First name can not be empty.');
     } else {
         if (empty($request_data['email_address'])) {
             $this->message = __('Fields marked with * can not be empty, Email field is mandatory.');
         } else {
             if (!empty($request_data['pass']) || !empty($request_data['conpass'])) {
                 $set_new_password = true;
                 $new_password_ok = false;
                 if ($request_data['pass'] != $request_data['conpass']) {
                     $this->message = __('Password and confirm password should match.');
                 } else {
                     if (strlen($request_data['pass']) < PA::$password_min_length) {
                         $this->message = sprintf(__('Password should be of %s characters or more.'), PA::$password_min_length);
                     } else {
                         if (strlen($request_data['pass']) > PA::$password_max_length) {
                             $this->message = sprintf(__('Password should be less than %s charcaters.'), PA::$password_max_length);
                         } else {
                             // all is good
                             $new_password_ok = true;
                         }
                     }
                 }
             }
         }
     }
     if ($request_data['deletepicture'] == "true") {
         $this->handleDeleteUserPic($request_data);
     }
     if (empty($this->message) && !empty($_FILES['userfile']['name'])) {
         $uploadfile = PA::$upload_path . basename($_FILES['userfile']['name']);
         $myUploadobj = new FileUploader();
         $file = $myUploadobj->upload_file(PA::$upload_path, 'userfile', true, true, 'image');
         if ($file == false) {
             $this->message = $myUploadobj->error;
             $error = TRUE;
         } else {
             $this->user_info->picture = $file;
             Storage::link($file, array("role" => "avatar", "user" => $user->user_id));
         }
     }
     if (empty($this->message)) {
         //If there is no error message then try saving the user information.
         $this->user_info->first_name = $request_data['first_name'];
         $this->user_info->last_name = $request_data['last_name'];
         $this->user_info->email = $request_data['email_address'];
         if (!empty($request_data['pass'])) {
             $this->user_info->password = md5($request_data['pass']);
         }
         try {
             $this->user_info->save();
             $dynProf = new DynamicProfile(PA::$login_user);
             $dynProf->processPOST('basic');
             $dynProf->save('basic');
             $this->message = __('Profile updated successfully.');
             //        $this->redirect2 = PA_ROUTE_EDIT_PROFILE;
             //        $this->queryString = '?type='.$this->profile_type;
             $this->isError = FALSE;
         } catch (PAException $e) {
             $this->message = $e->message;
         }
     }
     $error_msg = $this->message;
 }