Beispiel #1
0
 /**
  *
  * @return Fz_Ldap
  */
 protected function getLdap()
 {
     if ($this->_ldapCon === null) {
         $this->_ldapCon = new Fz_Ldap($this->_options);
         try {
             $this->_ldapCon->bind();
         } catch (Zend_Ldap_Exception $zle) {
             fz_log('Fz_User_Factory_Ldap: Can\'t bind ldap server', FZ_LOG_ERROR);
             throw $zle;
         }
     }
     return $this->_ldapCon;
 }
Beispiel #2
0
 /**
  * Delete files whose lifetime expired
  */
 public function deleteExpiredFiles()
 {
     $select = 'SELECT * FROM ' . $this->getTableName();
     $where = ' WHERE available_until<CURRENT_TIMESTAMP';
     foreach ($this->findBySql($select . $where) as $file) {
         if ($file->deleteFromDisk() === true) {
             fz_log('Deleted file "' . $file->getOnDiskLocation() . '"', FZ_LOG_CRON);
         } else {
             fz_log('Failed deleting file "' . $file->getOnDiskLocation() . '"', FZ_LOG_CRON_ERROR);
         }
     }
     option('db_conn')->exec('DELETE FROM ' . $this->getTableName() . $where);
 }
Beispiel #3
0
 /**
  * Notify the owner of the file passed as parameter that its file is going
  * to be deleted
  *
  * @param App_Model_File $file
  */
 private function notifyDeletionByEmail(App_Model_File $file)
 {
     try {
         $mail = $this->createMail();
         $subject = __r('[FileZ] Your file "%file_name%" is going to be deleted', array('file_name' => $file->file_name));
         $msg = __r('email_delete_notif (%file_name%, %file_url%, %filez_url%, %available_until%)', array('file_name' => $file->file_name, 'file_url' => $file->getDownloadUrl(), 'filez_url' => url_for('/'), 'available_until' => $file->getAvailableUntil()->toString(Zend_Date::DATE_FULL)));
         $mail->setBodyText($msg);
         $mail->setSubject($subject);
         $mail->addTo($file->uploader_email);
         $mail->send();
         fz_log('Delete notification sent to ' . $file->uploader_email, FZ_LOG_CRON);
     } catch (Exception $e) {
         fz_log('Can\'t send email to ' . $file->uploader_email . ' file_id:' . $file->id, FZ_LOG_CRON_ERROR);
     }
 }
Beispiel #4
0
 /**
  * Translate profile var name from their original name.
  *
  * @param array   $profile
  * @return array            Translated profile
  */
 protected function buildUserProfile(array $profile)
 {
     $p = array();
     $translation = fz_config_get('user_attributes_translation', null, array());
     foreach ($translation as $key => $value) {
         if (array_key_exists($value, $profile)) {
             if (is_array($profile[$value])) {
                 $p[$key] = count($profile[$value]) > 0 ? $profile[$value][0] : null;
             } else {
                 $p[$key] = $profile[$value];
             }
         } else {
             fz_log('User_Factory: Missing attribute "' . $value . '" in user profile :', FZ_LOG_ERROR, $profile);
         }
     }
     return $p;
 }
Beispiel #5
0
 /**
  * Move upoaded file
  *
  * @param array     uploaded file informations from $_FILES
  * @return boolean  whether the file was successfully moved or not.
  */
 public function moveUploadedFile($uploadedFile)
 {
     if (is_uploaded_file($uploadedFile['tmp_name']) && move_uploaded_file($uploadedFile['tmp_name'], $this->getOnDiskLocation())) {
         return true;
     } else {
         fz_log('Can\'t move the uploaded file ' . $uploadedFile['tmp_name'] . ' to its final destination "' . $this->getOnDiskLocation(), FZ_LOG_ERROR);
         return false;
     }
 }
Beispiel #6
0
function fz_exception_handler(Exception $e)
{
    fz_log($e, FZ_LOG_ERROR);
    return error_handler_dispatcher(SERVER_ERROR, $e->getMessage(), $e->getFile(), $e->getLine());
}
Beispiel #7
0
 /**
  * Destroy the user session
  */
 public function logout()
 {
     $uid = $this->getUserId();
     if ($uid !== null) {
         fz_log('user id:' . $uid . ' logs out.');
         session_unset();
         session_destroy();
     }
 }
Beispiel #8
0
 /**
  * Notify the file's owner by email that its file has been downloaded
  *
  * @param App_Model_File $file
  */
 private function sendFileDownloadedMail(App_Model_File $file)
 {
     if (!$file->notify_uploader) {
         return;
     }
     // find user IP
     // TODO: extract this function to generic place
     $ipaddress = '';
     if ($_SERVER['HTTP_CLIENT_IP']) {
         $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
     } else {
         if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
             $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
         } else {
             if ($_SERVER['HTTP_X_FORWARDED']) {
                 $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
             } else {
                 if ($_SERVER['HTTP_FORWARDED_FOR']) {
                     $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
                 } else {
                     if ($_SERVER['HTTP_FORWARDED']) {
                         $ipaddress = $_SERVER['HTTP_FORWARDED'];
                     } else {
                         if ($_SERVER['REMOTE_ADDR']) {
                             $ipaddress = $_SERVER['REMOTE_ADDR'];
                         } else {
                             $ipaddress = 'UNKNOWN';
                         }
                     }
                 }
             }
         }
     }
     // Send confirmation mail
     $user = Fz_Db::getTable('User')->findById($file->created_by);
     // I don't get why $user = $this->getUser (); doesn't work ???
     $mail = $this->createMail();
     $mail->addTo($user->email);
     $mail->addTo($user->email, $user->firstname . ' ' . $user->lastname);
     $subject = __r('[FileZ] "%file_name%" downloaded', array('file_name' => $file->file_name));
     $msg = __r('email_file_downloaded (%file_name%, %file_url%, %sender%, %ip%)', array('file_name' => $file->file_name, 'file_url' => $file->getDownloadUrl(), 'sender' => $user, 'ip' => $ipaddress));
     $mail->setBodyText($msg);
     $mail->setSubject($subject);
     $mail->setReplyTo($user->email, $user);
     $mail->clearFrom();
     $mail->setFrom(fz_config_get('email', 'from_email'), fz_config_get('email', 'from_name'));
     try {
         $mail->send();
     } catch (Exception $e) {
         fz_log('Can\'t send email "File Downloaded" : ' . $e, FZ_LOG_ERROR);
     }
 }
Beispiel #9
0
 /**
  * Share a file url by mail
  */
 public function emailAction()
 {
     $this->secure();
     $user = $this->getUser();
     $file = $this->getFile();
     $this->checkOwner($file, $user);
     set('file', $file);
     // Send mails
     $user = $this->getUser();
     $mail = $this->createMail();
     $subject = __r('[FileZ] "%sender%" wants to share a file with you', array('sender' => $user['firstname'] . ' ' . $user['lastname']));
     $msg = __r('email_share_file (%file_name%, %file_url%, %sender%, %msg%)', array('file_name' => $file->file_name, 'file_url' => $file->getDownloadUrl(), 'msg' => $_POST['msg'], 'sender' => $user['firstname'] . ' ' . $user['lastname']));
     $mail->setBodyText($msg);
     $mail->setSubject($subject);
     $mail->setReplyTo($user['email'], $user['firstname'] . ' ' . $user['lastname']);
     $mail->clearFrom();
     $mail->setFrom($user['email'], $user['firstname'] . ' ' . $user['lastname']);
     $emailValidator = new Zend_Validate_EmailAddress();
     foreach (explode(' ', $_POST['to']) as $email) {
         $email = trim($email);
         if (empty($email)) {
             continue;
         }
         if ($emailValidator->isValid($email)) {
             $mail->addBcc($email);
         } else {
             $msg = __r('Email address "%email%" is incorrect, please correct it.', array('email' => $email));
             return $this->returnError($msg, 'file/email.php');
         }
     }
     try {
         $mail->send();
         return $this->returnSuccessOrRedirect('/');
     } catch (Exception $e) {
         fz_log('Error while sending email', FZ_LOG_ERROR, $e);
         $msg = __('An error occured during email submission. Please try again.');
         return $this->returnError($msg, 'file/email.php');
     }
 }
Beispiel #10
0
 /**
  * Save a new row into the database
  *
  * @return self
  */
 protected function insert()
 {
     $db = option('db_conn');
     $table = $this->getTableName();
     $columnsName = $this->getUpdatedColumns();
     $sqlModifiersColumnsName = array_keys($this->_sqlModifiers);
     $unmodifiedColumns = array_diff($columnsName, $sqlModifiersColumnsName);
     $sql = "INSERT INTO `{$table}` (" . implode(', ', array_merge($unmodifiedColumns, $sqlModifiersColumnsName)) . ') VALUES (' . implode(', ', array_merge(array_map(array('Fz_Db', 'addColon'), $unmodifiedColumns), $this->_sqlModifiers)) . ')';
     fz_log($sql, FZ_LOG_DEBUG);
     $stmt = $db->prepare($sql);
     $this->bindUpdatedColumnsValues($stmt);
     $stmt->execute();
     return $db->lastInsertId();
 }
Beispiel #11
0
 /**
  * Function called on file upload error. A message corresponding to the error
  * code passed as parameter is return to the user. Error codes come from
  * $_FILES['userfile']['error'] plus a custom error code called
  * 'UPLOAD_ERR_QUOTA_EXCEEDED'
  *
  * @param integer $errorCode
  */
 private function onFileUploadError($errorCode = null)
 {
     $response['status'] = 'error';
     $response['statusText'] = __('An error occurred while uploading the file.') . ' ';
     if ($errorCode === null) {
         return $this->returnData($response);
     }
     switch ($errorCode) {
         case UPLOAD_ERR_NO_TMP_DIR:
             fz_log('upload error (Missing a temporary folder)', FZ_LOG_ERROR);
             break;
         case UPLOAD_ERR_CANT_WRITE:
             fz_log('upload error (Failed to write file to disk)', FZ_LOG_ERROR);
             break;
             // These errors come from the client side, let him know what's wrong
         // These errors come from the client side, let him know what's wrong
         case UPLOAD_ERR_INI_SIZE:
         case UPLOAD_ERR_FORM_SIZE:
             $response['statusText'] .= __('The uploaded file exceeds the max file size.') . ' : (' . ini_get('upload_max_filesize') . ')';
             break;
         case UPLOAD_ERR_PARTIAL:
             $response['statusText'] .= __('The uploaded file was only partially uploaded.');
             break;
         case UPLOAD_ERR_NO_FILE:
             $response['statusText'] .= __('No file was uploaded.');
             break;
         case UPLOAD_ERR_QUOTA_EXCEEDED:
             $response['statusText'] .= __r('You exceeded your disk space quota (%space%).', array('space' => fz_config_get('app', 'user_quota')));
         case UPLOAD_ERR_ALLOWED_EXTS:
             $response['statusText'] .= __r('The file is not allowed to be uploaded. Note that files allowed need to be %allowed_exts%.', array('allowed_exts' => fz_config_get('app', 'allowed_exts')));
     }
     return $this->returnData($response);
 }
Beispiel #12
0
 /**
  * Save a new row into the database
  *
  * @return self
  */
 protected function insert()
 {
     $db = option('db_conn');
     $table = $this->getTableName();
     $obj_columns = $this->getUpdatedColumns();
     $sql = "INSERT INTO `{$table}` (" . implode(', ', $obj_columns) . ') VALUES (' . implode(', ', array_map(array('Fz_Db', 'addColon'), $obj_columns)) . ')';
     fz_log($sql, FZ_LOG_DEBUG);
     $stmt = $db->prepare($sql);
     foreach ($obj_columns as $column) {
         $stmt->bindValue(':' . $column, $this->{$column});
     }
     $stmt->execute();
     return $db->lastInsertId();
 }
Beispiel #13
0
/**
 * configuring Filez
 */
function before()
{
    if (fz_config_get('app', 'use_url_rewriting')) {
        option('base_uri', option('base_path'));
    }
    // error handling
    if (fz_config_get('app', 'debug', false)) {
        ini_set('display_errors', true);
        option('debug', true);
        option('env', ENV_DEVELOPMENT);
    } else {
        ini_set('display_errors', false);
        option('debug', false);
    }
    // I18N
    Zend_Locale::setDefault(fz_config_get('app', 'default_locale', 'fr'));
    $currentLocale = new Zend_Locale('auto');
    $translate = new Zend_Translate('gettext', option('root_dir') . DIRECTORY_SEPARATOR . 'i18n', $currentLocale, array('scan' => Zend_Translate::LOCALE_DIRECTORY));
    option('translate', $translate);
    option('locale', $currentLocale);
    Zend_Registry::set('Zend_Locale', $currentLocale);
    // Execute DB configuration only if Filez is configured
    if (!option('installing')) {
        // check log dir
        if (!is_writable(fz_config_get('app', 'log_dir'))) {
            trigger_error('Log dir is not writeable "' . fz_config_get('app', 'log_dir') . '"', E_USER_WARNING);
        }
        // check upload dir
        if (!is_writable(fz_config_get('app', 'upload_dir'))) {
            trigger_error('Upload dir is not writeable "' . fz_config_get('app', 'upload_dir') . '"', E_USER_ERROR);
        }
        // Database configuration
        try {
            $db = new PDO(fz_config_get('db', 'dsn'), fz_config_get('db', 'user'), fz_config_get('db', 'password'));
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->exec('SET NAMES \'utf8\'');
            option('db_conn', $db);
        } catch (Exception $e) {
            halt(SERVER_ERROR, 'Can\'t connect to the database');
        }
        // Initialise and save the user factory
        $factoryClass = fz_config_get('app', 'user_factory_class');
        $userFactory = new $factoryClass();
        $userFactory->setOptions(fz_config_get('user_factory_options', null, array()));
        option('userFactory', $userFactory);
        // Check the database version and migrate if necessary
        $dbSchema = new Fz_Db_Schema(option('root_dir') . '/config/db');
        if ($dbSchema->isOutdated()) {
            fz_log('Migration needed (db_version: ' . $dbSchema->getCurrentVersion() . '), executing the scripts...');
            $dbSchema->migrate();
        }
    }
}
Beispiel #14
0
 /**
  * Evaluate a criterion.
  *
  * @param string $operator    The operator (currently, only = is supported)
  * @param string $attribute   Name of the attribute to check
  * @param string $regexp      PERL regular expression
  *
  * @return boolean            Returns true if the value of $_SERVER['attribute']
  *                            matches the regular expression
  */
 private function evaluateCriterion($operator, $attribute, $regexp, &$array)
 {
     $criterion = "{$attribute}{$operator}{$regexp}";
     if (empty($attribute) || empty($regexp)) {
         throw new Exception("filter: illegal criterion \"{$criterion}\"");
     }
     if (!array_key_exists($attribute, $array)) {
         fz_log("filter: no value for attribute \"{$attribute}\" in \"{$criterion}\"");
         return false;
     }
     $value = $array[$attribute];
     $regexp = str_replace("/", "\\/", $regexp);
     $regexp = "/{$regexp}/i";
     $return = preg_match($regexp, $value);
     fz_log("filter: checking \"{$criterion}\" with value \"{$value}\" returns {$return}");
     return $return;
 }