Пример #1
0
 static function change_provider($new_provider)
 {
     $current_provider = module::get_var("gallery", "identity_provider");
     if (!empty($current_provider)) {
         module::uninstall($current_provider);
     }
     try {
         IdentityProvider::reset();
         $provider = new IdentityProvider($new_provider);
         module::set_var("gallery", "identity_provider", $new_provider);
         if (method_exists("{$new_provider}_installer", "initialize")) {
             call_user_func("{$new_provider}_installer::initialize");
         }
         module::event("identity_provider_changed", $current_provider, $new_provider);
         auth::login($provider->admin_user());
         Session::instance()->regenerate();
     } catch (Exception $e) {
         static $restore_already_running;
         // In case of error, make an attempt to restore the old provider.  Since that's calling into
         // this function again and can fail, we should be sure not to get into an infinite recursion.
         if (!$restore_already_running) {
             $restore_already_running = true;
             // Make sure new provider is not in the database
             module::uninstall($new_provider);
             // Lets reset to the current provider so that the gallery installation is still
             // working.
             module::set_var("gallery", "identity_provider", null);
             IdentityProvider::change_provider($current_provider);
             module::activate($current_provider);
             message::error(t("Error attempting to enable \"%new_provider\" identity provider, " . "reverted to \"%old_provider\" identity provider", array("new_provider" => $new_provider, "old_provider" => $current_provider)));
             $restore_already_running = false;
         }
         throw $e;
     }
 }
Пример #2
0
 /**
  * Make sure that we have a session and group_ids cached in the session.
  */
 static function load_user()
 {
     try {
         // Call IdentityProvider::instance() now to force the load of the user interface classes.
         // We are about to load the active user from the session and which needs the user definition
         // class, which can't be reached by Kohana's heiracrchical lookup.
         IdentityProvider::instance();
         $session = Session::instance();
         if (!($user = $session->get("user"))) {
             self::set_active_user($user = self::guest());
         }
         // The installer cannot set a user into the session, so it just sets an id which we should
         // upconvert into a user.
         // @todo set the user name into the session instead of 2 and then use it to get the user object
         if ($user === 2) {
             auth::login(IdentityProvider::instance()->admin_user());
         }
         if (!$session->get("group_ids")) {
             $ids = array();
             foreach ($user->groups() as $group) {
                 $ids[] = $group->id;
             }
             $session->set("group_ids", $ids);
         }
     } catch (Exception $e) {
         // Log it, so we at least have so notification that we swallowed the exception.
         Kohana_Log::add("error", "load_user Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString());
         try {
             Session::instance()->destroy();
         } catch (Exception $e) {
             // We don't care if there was a problem destroying the session.
         }
         url::redirect(item::root()->abs_url());
     }
 }
Пример #3
0
 public function login()
 {
     if (input::post('username') && input::post('password') && auth::login(input::post('username'), input::post('password'), self::AUTH_REALM)) {
         $this->index();
     } else {
         return $this->access_denied();
     }
 }
Пример #4
0
 public function index()
 {
     $username = Input::instance()->post("user");
     $password = Input::instance()->post("password");
     if (empty($username) || auth::too_many_failures($username)) {
         throw new Rest_Exception("Forbidden", 403);
     }
     $user = identity::lookup_user_by_name($username);
     if (empty($user) || !identity::is_correct_password($user, $password)) {
         module::event("user_login_failed", $username);
         throw new Rest_Exception("Forbidden", 403);
     }
     auth::login($user);
     rest::reply(rest::access_key());
 }
Пример #5
0
 private function _auth($url)
 {
     $form = auth::get_login_form($url);
     $valid = $form->validate();
     if ($valid) {
         $user = identity::lookup_user_by_name($form->login->inputs["name"]->value);
         if (empty($user) || !identity::is_correct_password($user, $form->login->password->value)) {
             log::warning("user", t("Failed login for %name", array("name" => $form->login->inputs["name"]->value)));
             $form->login->inputs["name"]->add_error("invalid_login", 1);
             $valid = false;
         }
     }
     if ($valid) {
         auth::login($user);
     }
     // Either way, regenerate the session id to avoid session trapping
     Session::instance()->regenerate();
     return array($valid, $form);
 }
Пример #6
0
    include_once "modules/party/class_party.php";
    $party = new party();
} else {
    // If without party-module: just give a fake ID, for many modules need it
    class party
    {
        var $party_id;
    }
    $party = new party();
    $party->party_id = (int) $cfg['signon_partyid'];
}
if ($config['environment']['configured'] != 0) {
    if ($_GET['mod'] == 'auth') {
        switch ($_GET['action']) {
            case 'login':
                $auth = $authentication->login($_POST['email'], $_POST['password']);
                break;
            case 'logout':
                $auth = $authentication->logout();
                $_GET['mod'] = 'home';
                break;
            case 'switch_to':
                // Switch to user
                $authentication->switchto($_GET["userid"]);
                break;
            case 'switch_back':
                // Switch back to Adminuser
                $authentication->switchback();
                break;
        }
    }
Пример #7
0
 public function first($hash)
 {
     $pending_user = ORM::factory("pending_user")->where("hash", "=", $hash)->where("state", "=", 2)->find();
     if ($pending_user->loaded()) {
         // @todo add a request date to the pending user table and check that it hasn't expired
         $user = identity::lookup_user_by_name($pending_user->name);
         if (!empty($user)) {
             auth::login($user);
             Session::instance()->set("registration_first_usage", true);
             $pending_user->delete();
         }
         url::redirect(item::root()->abs_url());
     } else {
         message::warning(t("Your account is ready to use so please login."));
     }
     url::redirect(item::root()->abs_url());
 }
Пример #8
0
        $upload = new Upload();
        //коммент
        call_user_func(array($upload, 'out'));
        break;
    case 'auth':
        header('Content-Type: application/json');
        $ident = new auth();
        if (isset($_GET['auth'])) {
            $auth = $_GET['auth'];
            switch ($auth) {
                case 'user':
                    $ident->get_user();
                    break;
                case 'logout':
                    $ident->logount();
                    break;
                default:
                    $ident->login();
                    break;
            }
        } else {
            $ident->login();
        }
        break;
    default:
        // header('Content-Type: application/json');
        $recipes = new Recipes();
        $shag = $_GET['shag'];
        echo $recipes->getRecipes($shag);
        break;
}
Пример #9
0
 /**
  * authenticate the user
  *
  * @param string $url
  * @return boolean
  */
 private function _auth($url)
 {
     $form = auth::get_login_form($url);
     $validform = $form->validate();
     $valid = false;
     if ($validform) {
         // retrieve the values from the form
         $name = $form->login->inputs["name"]->value;
         $pass = $form->login->password->value;
         // do we have a user?
         $user = identity::lookup_user_by_name($name);
         $validuser = empty($user) ? false : true;
         // is the user authentic?
         $checkpass = $this->_checkpass($name, $pass);
         /*
          * we are concerned with these three possibilities:
          * 1. there is no valid user or no valid password
          * 2. there is no valid user but a valid password
          * 3. there is a valid user and a valid password
          */
         // 1. there is no valid user or no valid password: error
         if (!$validuser || !$checkpass) {
             $form->login->inputs["name"]->add_error("invalid_login", 1);
             $name = $form->login->inputs["name"]->value;
             log::warning("user", t("Failed login for %name", array("name" => $name)));
             module::event("user_auth_failed", $name);
         }
         // 2. there is no valid user but a valid password: create account if allowed
         if (!$validuser && $checkpass && $this->create_account) {
             $account = $this->pam_auth->getAccount();
             if ($account) {
                 $password = md5(uniqid(mt_rand(), true));
                 $new_user = identity::create_user($account->name, $account->full_name, $password, $account->email);
                 $new_user->url = '';
                 $new_user->admin = false;
                 $new_user->guest = false;
                 $new_user->save();
                 $user = identity::lookup_user_by_name($account->name);
                 $validuser = empty($user) ? false : true;
             }
         }
         // 3. there is a valid user and a valid password: load user account
         if ($validuser && $checkpass) {
             auth::login($user);
             $valid = true;
         }
     }
     // regenerate the session id to avoid session trapping
     Session::instance()->regenerate();
     return array($valid, $form);
 }
Пример #10
0
<?php

// Initialize
global $template;
$registration_successful = false;
// Create new user
if (isset($_POST['submit']) && $_POST['submit'] == tr('Register Now')) {
    $user = new User();
    $userid = $user->create();
    // Redirect to payment, if needed
    if ($template->has_errors != 1) {
        // Login
        $auth = new auth();
        $auth->login('public', false);
        // Redirect, as needed
        if ($_POST['is_payment'] == 1) {
            $template = new template('pay');
            $template->add_message("Successfully created new user, {$_POST['username']}.  You may now login with your account.");
            $template->parse();
            exit(0);
        } else {
            $template->add_message("Successfully created new user, {$_POST['username']}.  You may now login with your account.");
        }
    }
}
// Set variables
if (isset($_REQUEST['is_payment']) && $_REQUEST['is_payment'] == 1) {
    $is_payment = 1;
    $amount = $_REQUEST['amount'];
    $currency = $_REQUEST['currency'];
    $wallet_id = $_REQUEST['wallet_id'];
Пример #11
0
<?php

require_once '../../config/configuracao.php';
require_once $BASE_DIR . 'lib/adLDAP.php';
require_once $BASE_DIR . 'core/data/connection_factory.php';
require_once $BASE_DIR . 'core/login/session.php';
require_once $BASE_DIR . 'core/login/auth.php';
$sessao = new session($param_conn);
// INICIA UM NOVO PROCESSO DE LOGIN
if (isset($_POST['modulo'])) {
    $conn = new connection_factory($param_conn);
    // verifica usuário na base LDAP
    $adLdap = new adLDAP($param_ldap);
    $autentica = new auth($BASE_URL, $adLdap);
    $autentica->log_file($BASE_DIR . 'logs/login.log');
    if ($autentica->login(trim($_POST['uid']), trim($_POST['pwd']), $_POST['modulo'], $conn) === TRUE) {
        // REDIRECIONA DE ACORDO COM O MODULO SELECIONADO
        switch ($_SESSION['sa_modulo']) {
            case 'sa_login':
                exit(header('Location: ' . $BASE_URL . 'app/'));
                break;
            case 'web_diario_login':
                exit(header('Location: ' . $BASE_URL . 'app/web_diario/'));
                break;
            case 'aluno_login':
                exit(header('Location: ' . $BASE_URL . 'app/aluno'));
                break;
            default:
                exit(header('Location: ' . $BASE_URL . 'index.php?sa_msg=Sessão inválida'));
        }
    } else {
Пример #12
0
<?php

require_once './../persistence.class.php';
require_once './../auth.class.php';
$uid = "eddadmin";
$pass = "******";
$auth = new auth($uid);
$user = $auth->login($uid, $pass);
$status = $user->authenticated() ? "user logged in: {$user->username}" : "auth failed<br />reason: {$user->fail_reason()}";
persistence::persist_user($user);
echo "user: {$uid}, password: {$pass} <br />";
echo $status;
Пример #13
0
    echo '
                  <form action="" method="post">
                  <input type="text" name="nick" placeholder="Логин" required>
                  <input type="password" name="pass" placeholder="Пароль" required>
                  <input type="submit" name="login" value="Авторизироваться!">
                  </form>
                  <a href="?action=register">Register</a>
                  ';
}
if (isset($_GET['action']) and $_GET['action'] == 'logout') {
    //logouting
    $user->logout();
}
if (isset($_POST['login'])) {
    //logging
    if ($user->login($_POST['nick'], $_POST['pass'])) {
    } else {
        echo $user->error_msg;
    }
}
if (isset($_POST['register'])) {
    //registering
    if ($user->register($_POST['nick'], $_POST['email'], $_POST['pass'], $_POST['r_pass'], $_POST['name'])) {
    } else {
        echo $user->error_msg;
    }
}
if (isset($_POST['check'])) {
    //validating
    if (!$user->verify($_POST['code'])) {
        echo $user->error_msg;
Пример #14
0
            $func->error(t('Bitte gib ein Kennwort ein!'), "index.php?mod=install&action=wizard&step=6");
        } elseif ($_POST["password"] != $_POST["password2"]) {
            $func->error(t('Das Passwort und seine Verifizierung stimmen nicht überein!'), "index.php?mod=install&action=wizard&step=6");
        } else {
            // Check for existing Admin-Account.
            $row = $db->qry_first("SELECT email FROM %prefix%user WHERE email=%string%", $_POST["email"]);
            // If found, update password
            if ($row['email']) {
                $db->qry("UPDATE %prefix%user SET password = %string%, type = '3' WHERE email=%string%", md5($_POST["password"]), $_POST["email"]);
            } else {
                $db->qry("INSERT INTO %prefix%user SET username = '******', firstname = 'ADMIN', name = 'ADMIN', email=%string%, password = %string%, type = '3'", $_POST["email"], md5($_POST["password"]));
                $userid = $db->insert_id();
            }
            include_once "inc/classes/class_auth.php";
            $authentication = new auth();
            $authentication->login($_POST["email"], $_POST["password"]);
        }
        // No break!
    // No break!
    case 8:
        if (!$func->admin_exists()) {
            $func->information(t('Du musst einen Admin-Account anlegen, um fortfahren zu können'));
            $_GET['step'] = 6;
        }
        break;
}
switch ($_GET["step"]) {
    // Check Environment
    default:
        $dsp->NewContent(t('Lansuite Installation und Administration'), t('Willkommen bei der Installation von Lansuite.<br />Im ersten Schritt wird die Konfiguration deines Webservers überprüft.<br />Sollte alles korrekt sein, so drücke bitte am Ende der Seite auf <b>Weiter</b> um mit der Eingabe der Grundeinstellungen fortzufahren.'));
        $dsp->SetForm("index.php?mod=install&action=wizard");
Пример #15
0
 private function _login(&$input, &$reply)
 {
     $uname = trim($input->post('uname'));
     if (empty($uname)) {
         $reply->send(gallery_remote::LOGIN_MISSING);
     } else {
         $user = user::lookup_by_name($uname);
         $password = trim($input->post('password'));
         if ($user && user::is_correct_password($user, $password)) {
             auth::login($user);
             Session::instance()->regenerate();
             $reply->set('debug_user', $user->name);
             $reply->set('status_text', 'Login successful.');
             $reply->send();
         } else {
             $reply->send(gallery_remote::PASSWD_WRONG);
         }
     }
 }
Пример #16
0
 public function __construct($parts = array())
 {
     // Initialize
     global $config, $template;
     // Set variables
     if ($config['is_setup'] == 1 && preg_match("/^admin/", trim($_GET['route'], '/'))) {
         $panel = 'admin';
         $require_login = true;
     } else {
         $panel = 'public';
         $require_login = false;
     }
     // Check IP restrictions
     if ($panel == 'admin' && isset($config['ipallow']) && $config['ipallow'] != '') {
         $ok = false;
         $ips = explode("\n", $config['ipallow']);
         foreach ($ips as $ip) {
             if (preg_match("/^{$ip}/", $_SERVER['REMOTE_ADDR'])) {
                 $ok = true;
                 break;
             }
         }
         if ($ok === false) {
             echo "Access dened by IP restrictions.";
             exit(0);
         }
     }
     // Continue setup, if needed
     if (DBNAME == '' && isset($_POST['submit']) && $_POST['submit'] == tr('Continue to Next Step')) {
         // Initialize
         $template = new template('admin/setup/first_time2');
         require_once SITE_PATH . '/data/lib/sqlparser.php';
         // Check database connection
         if (!mysqli_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpass'], $_POST['dbname'], $_POST['dbport'])) {
             $template->add_message("Unable to connect to mySQL database using information supplied.  Please double check the mySQL information, and try again.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/config.php')) {
             $template->add_message("Unable to write to file at /data/config.php.  Please change file permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/backups')) {
             $template->add_message("Unable to write to directory at /data/backups/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/log')) {
             $template->add_message("Unable to write to directory at /data/log/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/tpl_c')) {
             $template->add_message("Unable to write to directory at /data/tpl_c/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time';
             echo $template->parse();
             exit(0);
         }
         // Define MeekroDB settings
         DB::$dbName = $_POST['dbname'];
         DB::$user = $_POST['dbuser'];
         DB::$password = $_POST['dbpass'];
         DB::$host = $_POST['dbhost'];
         DB::$port = $_POST['dbport'];
         // Parse sql
         $sql_lines = SqlParser::parse(file_get_contents(SITE_PATH . '/data/sql/install.sql'));
         foreach ($sql_lines as $line) {
             DB::query($line);
         }
         // Save config.php file
         $conf = "<?php\n";
         $conf .= "define('DBNAME', '" . $_POST['dbname'] . "');\n";
         $conf .= "define('DBUSER', '" . $_POST['dbuser'] . "');\n";
         $conf .= "define('DBPASS', '" . $_POST['dbpass'] . "');\n";
         $conf .= "define('DBHOST', '" . $_POST['dbhost'] . "');\n";
         $conf .= "define('DBPORT', '" . $_POST['dbport'] . "');\n";
         $conf .= "define('COOKIE_NAME', '" . generate_random_string(6) . "');\n";
         $conf .= "define('ENCRYPT_PASS', '" . generate_random_string(32) . "');\n";
         $conf .= "define('TESTNET', 0);\n";
         $conf .= "?>\n";
         // Save config file
         file_put_contents(SITE_PATH . '/data/config.php', $conf);
         // Parse template
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '2') {
         // Initialize
         $template = new template('admin/setup/first_time3');
         if (strlen($_POST['username']) < 4) {
             $template->add_message('Administrator username must be at least 4 characters in length.', 'error');
         }
         // Create user
         $user = new user();
         $user->create(1);
         // Update config vars
         update_config_var('site_name', $_POST['site_name']);
         update_config_var('company_name', $_POST['company_name']);
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time2';
         } else {
             // Login
             $auth = new auth();
             $auth->login('admin', false);
         }
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '3') {
         // Initialize
         $template = new template('admin/setup/first_time4');
         // Update config vars
         update_config_var('btc_rpc_host', $_POST['btc_rpc_host']);
         update_config_var('btc_rpc_user', $_POST['btc_rpc_user']);
         update_config_var('btc_rpc_pass', $_POST['btc_rpc_pass']);
         update_config_var('btc_rpc_port', $_POST['btc_rpc_port']);
         // Test connection
         $client = new transaction();
         if (!$client->get_info()) {
             $template->route = 'admin/setup/first_time3';
             $template->add_message('Unable to connect to RPC using the provided settings.  Please check the connection information, restart bitcoind, and try again.  If you have just started bitcoind for the first time, you will need to wait a while for all blocks to download before continuing.', 'error');
             $template->parse();
             exit(0);
         }
         // Parse template
         echo $template->parse();
         exit(0);
         // Complete setup, if needed
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '4') {
         // Initialize
         $template = new template('admin/setup/first_time5');
         // Update config vars
         update_config_var('is_setup', '1');
         // Get exchange date
         $rate = get_coin_exchange_rate($config['currency']);
         if ($rate != 0) {
             update_config_var('exchange_rate', $rate);
         }
         // Add wallet
         $bip32 = new bip32();
         $bip32->add_wallet();
         // Display template
         if ($template->has_errors != 1) {
             //$template->add_message("Successfully completed first time setup.");
         }
         echo $template->parse();
         exit(0);
     }
     // Check if setup
     if ($config['is_setup'] == 0) {
         $template = new template('admin/setup/first_time');
         echo $template->parse();
         exit(0);
     }
     // Check login
     $auth = new auth();
     if ($userid = $auth->check_login($panel, $require_login)) {
         define('LOGIN', true);
         $GLOBALS['userid'] = $userid;
     } else {
         define('LOGIN', false);
         $GLOBALS['userid'] = 0;
     }
     // Check admin permission, if needed
     if ($panel == 'admin') {
         $group_id = DB::queryFirstField("SELECT group_id FROM users WHERE id = %d", $GLOBALS['userid']);
         if ($group_id != 1) {
             trigger_error("You do not have permission to access this area.", E_USER_ERROR);
         }
     }
     // Parse template
     $template = new template();
     echo $template->parse();
     // Exit
     exit(0);
 }
Пример #17
0
<?php

require dirname(__FILE__) . '/../dbConnection.php';
require dirname(__FILE__) . '/../lib/auth.class.php';
$auth = new auth();
$username = $_POST["username"];
$password = $_POST["password"];
echo $auth->login($username, $password);
Пример #18
0
 static function cron()
 {
     $owner_id = 2;
     $debug = !empty($_SERVER['argv']) && isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == "debug";
     // Login as Admin
     $debug and print "Starting user session\n";
     $session = Session::instance();
     $session->delete("user");
     auth::login(IdentityProvider::instance()->admin_user());
     // check if some folders are still unprocessed from previous run
     $entry = ORM::factory("folder_sync_entry")->where("is_directory", "=", 1)->where("checked", "=", 0)->order_by("id", "ASC")->find();
     if (!$entry->loaded()) {
         $debug and print "Adding default folders\n";
         $paths = unserialize(module::get_var("folder_sync", "authorized_paths"));
         foreach (array_keys($paths) as $path) {
             if (folder_sync::is_valid_path($path)) {
                 $path = rtrim($path, "/");
                 $debug and print " * {$path}\n";
                 $entry = ORM::factory("folder_sync_entry")->where("is_directory", "=", 1)->where("path", "=", $path)->find();
                 if ($entry && $entry->loaded()) {
                     $entry->checked = 0;
                     $entry->save();
                 } else {
                     $entry = ORM::factory("folder_sync_entry");
                     $entry->path = $path;
                     $entry->is_directory = 1;
                     $entry->parent_id = null;
                     $entry->item_id = module::get_var("folder_sync", "destination_album_id", 1);
                     $entry->md5 = '';
                     $entry->save();
                 }
             }
         }
     }
     // Scan and add files
     $debug and print "Starting the loop\n";
     $done = false;
     $limit = 500;
     while (!$done && $limit > 0) {
         $debug and print "Loop started: Limit = {$limit}\n";
         $entry = ORM::factory("folder_sync_entry")->where("is_directory", "=", 1)->where("checked", "=", 0)->order_by("id", "ASC")->find();
         if ($entry->loaded()) {
             // get the parrent
             $parent = ORM::factory("item", $entry->item_id);
             if (!$parent->loaded()) {
                 $debug and print "Deleting entry #{$entry->id} pointing to missing item #{$entry->item_id}\n";
                 //$entry->delete();
                 //continue;
             }
             $debug and print "Scanning folder: {$entry->path}\n";
             $child_paths = glob(preg_quote($entry->path) . "/*");
             if (!$child_paths) {
                 $child_paths = glob("{$entry->path}/*");
             }
             foreach ($child_paths as $child_path) {
                 $name = basename($child_path);
                 $title = item::convert_filename_to_title($name);
                 $debug and print "Found {$child_path}...";
                 if (is_dir($child_path)) {
                     $debug and print "folder\n";
                     $entry_exists = ORM::factory("folder_sync_entry")->where("is_directory", "=", 1)->where("path", "=", $child_path)->find();
                     if ($entry_exists && $entry_exists->loaded()) {
                         $debug and print "Folder is already imported, marked to re-sync.\n";
                         $entry_exists->checked = 0;
                         $entry_exists->save();
                     } else {
                         $debug and print "Adding new folder.\n";
                         $album = ORM::factory("item");
                         $album->type = "album";
                         $album->parent_id = $parent->id;
                         $album->name = $name;
                         $album->title = $title;
                         $album->owner_id = $owner_id;
                         $album->sort_order = $parent->sort_order;
                         $album->sort_column = $parent->sort_column;
                         $album->save();
                         $child_entry = ORM::factory("folder_sync_entry");
                         $child_entry->path = $child_path;
                         $child_entry->parent_id = $entry->id;
                         $child_entry->item_id = $album->id;
                         $child_entry->is_directory = 1;
                         $child_entry->md5 = "";
                         $child_entry->save();
                     }
                 } else {
                     $debug and print "file\n";
                     $ext = strtolower(pathinfo($child_path, PATHINFO_EXTENSION));
                     if (!in_array($ext, legal_file::get_extensions()) || !filesize($child_path)) {
                         // Not importable, skip it.
                         $debug and print "File is incompatible. Skipping.\n";
                         continue;
                     }
                     // check if file was already imported
                     $entry_exists = ORM::factory("folder_sync_entry")->where("is_directory", "=", 0)->where("path", "=", $child_path)->find();
                     if ($entry_exists && $entry_exists->loaded()) {
                         $debug and print "Image is already imported...";
                         if (empty($entry_exists->added) || empty($entry_exists->md5) || $entry_exists->added != filemtime($child_path) || $entry_exists->md5 != md5_file($child_path)) {
                             $item = ORM::factory("item", $entry_exists->item_id);
                             if ($item->loaded()) {
                                 $item->set_data_file($child_path);
                                 $debug and print "updating.\n";
                                 try {
                                     $item->save();
                                 } catch (ORM_Validation_Exception $e) {
                                     print "Error saving the image (ID = {$item->id}) with the new data file.\n";
                                     exit;
                                 }
                             } else {
                                 $debug and print "deleting.\n";
                                 $entry_exists->delete();
                             }
                         } else {
                             $debug and print "skipping.\n";
                         }
                         // since it's an update, don't count too much towards the limit
                         $limit -= 0.25;
                     } else {
                         if (in_array($ext, legal_file::get_photo_extensions())) {
                             $debug and print "Adding new photo.\n";
                             $item = ORM::factory("item");
                             $item->type = "photo";
                             $item->parent_id = $parent->id;
                             $item->set_data_file($child_path);
                             $item->name = $name;
                             $item->title = $title;
                             $item->owner_id = $owner_id;
                             $item->save();
                         } else {
                             if (in_array($ext, legal_file::get_movie_extensions())) {
                                 $debug and print "Adding new video.\n";
                                 $item = ORM::factory("item");
                                 $item->type = "movie";
                                 $item->parent_id = $parent->id;
                                 $item->set_data_file($child_path);
                                 $item->name = $name;
                                 $item->title = $title;
                                 $item->owner_id = $owner_id;
                                 $item->save();
                             }
                         }
                         $entry_exists = ORM::factory("folder_sync_entry");
                         $entry_exists->path = $child_path;
                         $entry_exists->parent_id = $entry->id;
                         // null if the parent was a staging dir
                         $entry_exists->is_directory = 0;
                         $entry_exists->md5 = md5_file($child_path);
                         $entry_exists->added = filemtime($child_path);
                         $entry_exists->item_id = $item->id;
                         $entry_exists->save();
                         $limit--;
                     }
                 }
                 // Did we hit the limit?
                 if ($limit <= 0) {
                     $debug and print "Reached the limit. Exiting.\n";
                     exit;
                 }
             }
             // We've processed this entry unless we reached a limit.
             if ($limit > 0) {
                 $entry->checked = 1;
                 $entry->save();
             }
         } else {
             $done = true;
             $debug and print "All folders are processed. Exiting.\n";
         }
     }
     // process deletes
     if (module::get_var("folder_sync", "process_deletes", false)) {
         $entries = ORM::factory("folder_sync_entry")->order_by("id", "ASC")->find_all();
         foreach ($entries as $entry) {
             if (!file_exists($entry->path) && $entry->item_id > 1) {
                 $item = ORM::factory("item", $entry->item_id);
                 if ($item->loaded()) {
                     $item->delete();
                 }
             }
         }
     }
     exit;
 }
Пример #19
0
<?php

require_once '../init.inc.php';
require_once '../class/auth.class.php';
require_once '../class/user.class.php';
$auth = new auth();
$auth->login('admin', 'secret');
$user = new user();