Exemplo n.º 1
0
 public function __construct()
 {
     $f = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'cache');
     $f->create();
     $this->_cacheFile = \GO::config()->file_storage_path . 'cache/script-';
     if (\GO::user()) {
         $this->_cacheFile .= \GO::user()->username;
     } else {
         $this->_cacheFile .= "loggedoff";
     }
     $this->_cacheFile .= '.js';
 }
Exemplo n.º 2
0
 public function getThemeNames()
 {
     $folder = new \GO\Base\Fs\Folder(\GO::config()->root_path . 'views/Extjs3/themes');
     $items = $folder->ls();
     $themes = array();
     foreach ($items as $folder) {
         if ($folder->isFolder() && $folder->child('Layout.php')) {
             $themes[] = $folder->name();
         }
     }
     return $themes;
 }
Exemplo n.º 3
0
 public function __construct($prefixString = '')
 {
     if (!\GO::modules()->isInstalled('files')) {
         throw new \Exception('The current action requires the files module to be activated for the current user.');
     }
     // Make sure the current user's folder exists.
     $userFolderModel = \GO\Files\Model\Folder::model()->findHomeFolder(\GO::user());
     if (empty($userFolderModel)) {
         $userFolder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'users/' . \GO::user()->username);
         $userFolder->create();
         $userFolderModel = new \GO\Files\Model\Folder();
         $userFolderModel->findByPath('users/' . \GO::user()->username, true);
     }
     parent::__construct(\GO::config()->file_storage_path . $userFolderModel->path . '/' . $prefixString . \GO\Base\Util\Date::get_timestamp(time(), true) . '.log');
 }
Exemplo n.º 4
0
 /**
  * The code that needs to be called when the cron is running
  * 
  * If $this->enableUserAndGroupSupport() returns TRUE then the run function 
  * will be called for each $user. (The $user parameter will be given)
  * 
  * If $this->enableUserAndGroupSupport() returns FALSE then the 
  * $user parameter is null and the run function will be called only once.
  * 
  * @param CronJob $cronJob
  * @param \GO\Base\Model\User $user [OPTIONAL]
  */
 public function run(CronJob $cronJob, \GO\Base\Model\User $user = null)
 {
     $stmt = \GO::getDbConnection()->query("SHOW TABLE STATUS FROM `" . \GO::config()->db_name . "`;");
     $database_usage = 0;
     while ($r = $stmt->fetch()) {
         $database_usage += $r['Data_length'];
         $database_usage += $r['Index_length'];
     }
     \GO::config()->save_setting('database_usage', $database_usage);
     $folder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path);
     \GO::config()->save_setting('file_storage_usage', $folder->calculateSize());
     if (\GO::modules()->postfixadmin) {
         $findParams = \GO\Base\Db\FindParams::newInstance()->select('sum(`usage`) AS `usage`')->ignoreAcl()->single();
         $result = \GO\Postfixadmin\Model\Mailbox::model()->find($findParams);
         \GO::config()->save_setting('mailbox_usage', $result->usage * 1024);
     }
 }
Exemplo n.º 5
0
 protected function actionSend($params)
 {
     if (empty($params['addresslist_id'])) {
         throw new \Exception(\GO::t('feedbackNoReciepent', 'email'));
     } else {
         try {
             //$params = $this->_convertOldParams($params);
             if (\GO::modules()->isAvailable('campaigns') && isset($params['campaign_id']) && $params['campaign_id'] > 0 && (empty(\GO::config()->campaigns_imap_user) || empty(\GO::config()->campaigns_imap_pass) || empty(\GO::config()->campaigns_imap_server) || empty(\GO::config()->campaigns_imap_port) || !isset(\GO::config()->campaigns_smtp_user) || !isset(\GO::config()->campaigns_smtp_pass) || empty(\GO::config()->campaigns_smtp_server) || empty(\GO::config()->campaigns_smtp_port) || empty(\GO::config()->campaigns_from) || empty(\GO::config()->campaigns_max_mails_per_period))) {
                 throw new \Exception(\GO::t('mustSetCampaignsConfig', 'campaigns'));
             }
             $message = \GO\Base\Mail\Message::newInstance();
             $message->handleEmailFormInput($params);
             // insert the inline and regular attachments in the MIME message
             $mailing['alias_id'] = $params['alias_id'];
             $mailing['subject'] = $params['subject'];
             $mailing['addresslist_id'] = $params['addresslist_id'];
             $mailing['campaign_id'] = $params['campaign_id'];
             $mailing['message_path'] = 'mailings/' . \GO::user()->id . '_' . date('Ymd_Gis') . '.eml';
             $folder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'mailings');
             $folder->create();
             // Write message MIME source to message path
             file_put_contents(\GO::config()->file_storage_path . $mailing['message_path'], $message->toString());
             \GO::debug('===== MAILING PARAMS =====');
             \GO::debug(var_export($mailing, true));
             $sentMailing = new \GO\Addressbook\Model\SentMailing();
             $sentMailing->setAttributes($mailing);
             if (!$sentMailing->save()) {
                 \GO::debug('===== VALIDATION ERRORS =====');
                 \GO::debug('Could not create new mailing:<br />' . implode('<br />', $sentMailing->getValidationErrors()));
                 throw new \Exception('Could not create new mailing:<br />' . implode('<br />', $sentMailing->getValidationErrors()) . '<br />MAILING PARAMS:<br />' . var_export($mailing, true));
             }
             $this->_launchBatchSend($sentMailing->id);
             $response['success'] = true;
         } catch (\Exception $e) {
             $response['feedback'] = \GO::t('feedbackUnexpectedError', 'email') . $e->getMessage();
         }
     }
     return $response;
 }
Exemplo n.º 6
0
 static function render($params, $tag, \GO\Site\Model\Content $content)
 {
     $html = '';
     if (empty($params['path'])) {
         return "Error: path attribute must be set in img tag!";
     }
     //Change Tickets.png into public/site/1/files/Tickets.png
     $folder = new \GO\Base\Fs\Folder(Site::model()->getPublicPath());
     $fullRelPath = $folder->stripFileStoragePath() . '/files/' . $params['path'];
     //		var_dump($p);
     $thumbParams = $params;
     unset($thumbParams['path'], $thumbParams['lightbox'], $thumbParams['alt'], $thumbParams['class'], $thumbParams['style'], $thumbParams['astyle'], $thumbParams['caption'], $thumbParams['aclass']);
     if (!isset($thumbParams['lw']) && !isset($thumbParams['w'])) {
         $thumbParams['lw'] = 300;
     }
     if (!isset($thumbParams['ph']) && !isset($thumbParams['ph'])) {
         $thumbParams['ph'] = 300;
     }
     $thumb = Site::thumb($fullRelPath, $thumbParams);
     if (!isset($params['caption'])) {
         $file = new \GO\Base\Fs\File($fullRelPath);
         $params['caption'] = $file->nameWithoutExtension();
     }
     if (!isset($params['alt'])) {
         $params['alt'] = isset($params['caption']) ? $params['caption'] : basename($tag['params']['path']);
     }
     $html .= '<img src="' . $thumb . '" alt="' . $params['alt'] . '"';
     $html .= 'class="thumb-img"';
     $html .= ' />';
     if (!isset($params['lightbox'])) {
         $params['lightbox'] = "thumb";
     }
     if (!empty($params['lightbox'])) {
         $a = '<a';
         if (isset($params['caption'])) {
             $a .= ' title="' . $params['caption'] . '"';
         }
         if (!isset($params['aclass'])) {
             $params['aclass'] = 'thumb-a';
         }
         $a .= ' class="' . $params['aclass'] . '"';
         if (isset($params['astyle'])) {
             $a .= ' style="' . $params['astyle'] . '"';
         }
         $a .= ' data-lightbox="' . $params['lightbox'] . '" href="' . \Site::file($params['path'], false) . '">' . $html . '</a>';
         // Create an url to the original image
         $html = $a;
     }
     if (isset($params['caption'])) {
         $html .= '<div class="thumb-caption">' . $params['caption'] . '</div>';
     }
     if (!isset($params['class'])) {
         $params['class'] = 'thumb-wrap';
     }
     $wrap = '<div class="' . $params['class'] . '"';
     if (isset($params['style'])) {
         $wrap .= 'style="' . $params['style'] . '"';
     }
     $wrap .= '>';
     $html = $wrap . $html . '</div>';
     return $html;
 }
Exemplo n.º 7
0
 public function setPhoto(\GO\Base\Fs\File $file)
 {
     if ($this->isNew) {
         throw new \Exception("Cannot save a photo on a new contact that is not yet saved.");
     }
     $this->getPhotoFile()->delete();
     $photoPath = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'addressbook/photos/' . $this->addressbook_id . '/');
     $photoPath->create();
     //		if(strtolower($file->extension())!='jpg'){
     $filename = $photoPath->path() . '/com_' . $this->id . '.jpg';
     $img = new \GO\Base\Util\Image();
     if (!$img->load($file->path())) {
         throw new \Exception(\GO::t('imageNotSupported', 'addressbook'));
     }
     $aspectRatio = $img->getHeight() > $img->getWidth() ? $img->getHeight() / $img->getWidth() : $img->getWidth() / $img->getHeight();
     //resize it to small image so we don't get in trouble with sync clients
     if ($img->getHeight() > $img->getWidth()) {
         $img->fitBox(320 / $aspectRatio, 320);
     } else {
         $img->fitBox(320, 320 / $aspectRatio);
     }
     if (!$img->save($filename, IMAGETYPE_JPEG)) {
         throw new \Exception("Could not save photo!");
     }
     $file = new \GO\Base\Fs\File($filename);
     //		}else
     //		{
     //			$file->move($photoPath, $this->id.'.'.strtolower($file->extension()));
     //		}
     $this->photo = $file->stripFileStoragePath();
 }
Exemplo n.º 8
0
 /**
  * Get all the available holiday files
  * 
  * @return array key => label
  */
 public static function getAvailableHolidayFiles()
 {
     $holidays = array();
     $folderPath = \GO::config()->root_path . 'language/holidays/';
     $folder = new \GO\Base\Fs\Folder($folderPath);
     $children = $folder->ls();
     foreach ($children as $child) {
         $label = \GO::t($child->nameWithoutExtension());
         $holidays[$label] = array('filename' => $child->nameWithoutExtension(), 'label' => $label);
     }
     ksort($holidays);
     return array_values($holidays);
 }
Exemplo n.º 9
0
 *  LOGLEVEL_OFF            - no logging
 *  LOGLEVEL_FATAL          - log only critical errors
 *  LOGLEVEL_ERROR          - logs events which might require corrective actions
 *  LOGLEVEL_WARN           - might lead to an error or require corrective actions in the future
 *  LOGLEVEL_INFO           - usually completed actions
 *  LOGLEVEL_DEBUG          - debugging information, typically only meaningful to developers
 *  LOGLEVEL_WBXML          - also prints the WBXML sent to/from the device
 *  LOGLEVEL_DEVICEID       - also prints the device id for every log entry
 *  LOGLEVEL_WBXMLSTACK     - also prints the contents of WBXML stack
 *
 *  The verbosity increases from top to bottom. More verbose levels include less verbose
 *  ones, e.g. setting to LOGLEVEL_DEBUG will also output LOGLEVEL_FATAL, LOGLEVEL_ERROR,
 *  LOGLEVEL_WARN and LOGLEVEL_INFO level entries.
 */
//define('LOGFILEDIR', '/var/log/z-push/');
$folder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'log/z-push/');
$folder->create();
define('LOGFILEDIR', $folder->path() . '/');
define('LOGFILE', LOGFILEDIR . 'z-push.log');
define('LOGERRORFILE', LOGFILEDIR . 'z-push-error.log');
//note: you can't use z-push constants in the GO config file!
//use 16 for debug or 32 for wbxml
if (!isset(\GO::config()->zpush2_loglevel)) {
    \GO::config()->zpush2_loglevel = LOGLEVEL_OFF;
}
define('LOGLEVEL', \GO::config()->zpush2_loglevel);
define('LOGAUTHFAIL', false);
// To save e.g. WBXML data only for selected users, add the usernames to the array
// The data will be saved into a dedicated file per user in the LOGFILEDIR
// Users have to be encapusulated in quotes, several users are comma separated, like:
//   $specialLogUsers = array('*****@*****.**', 'myusername');
Exemplo n.º 10
0
 public function getFileStorageCronJobClasses($folderName = 'cron')
 {
     $foundCronJobClasses = array();
     $folderPath = \GO::config()->file_storage_path . 'php/' . $folderName;
     $folder = new \GO\Base\Fs\Folder($folderPath);
     \GO::debug("CRONFILE SEARCH IN FOLDER: " . $folder->path());
     if ($folder->exists()) {
         $items = $folder->ls();
         $reflectionClasses = array();
         foreach ($items as $item) {
             if (is_file($item)) {
                 $className = 'GOFS\\Cron\\' . $item->nameWithoutExtension();
                 $reflectionClasses[] = new \ReflectionClass($className);
             }
         }
         foreach ($reflectionClasses as $reflectionClass) {
             if ($this->_checkIsCronJobClassFile($reflectionClass)) {
                 \GO::debug("CRONFILE FOUND: " . $reflectionClass->name);
                 $cronJob = new $reflectionClass->name();
                 $foundCronJobClasses[$reflectionClass->name] = $cronJob->getLabel();
             }
         }
     }
     return $foundCronJobClasses;
 }
Exemplo n.º 11
0
 /**
  * Get URL to a public template file that is accessible with the browser.
  * 
  * @param string $relativePath
  * @return string
  */
 public static function file($relativePath, $template = true)
 {
     if (!$template) {
         $folder = new \GO\Base\Fs\Folder(\Site::model()->getPublicPath());
         $relativePath = str_replace($folder->stripFileStoragePath() . '/files/', '', $relativePath);
         return \Site::model()->getPublicUrl() . 'files/' . \GO\Base\Util\String::rawurlencodeWithourSlash($relativePath);
     } else {
         return self::template()->getUrl() . \GO\Base\Util\String::rawurlencodeWithourSlash($relativePath);
     }
 }
Exemplo n.º 12
0
 public function send(\Swift_Mime_Message $message, &$failedRecipients = null)
 {
     if (!empty(\GO::config()->disable_mail)) {
         throw new \Exception("E-mail sending is disabled!");
     }
     if (\GO::config()->debug) {
         $getTo = $message->getTo();
         if (!empty($getTo)) {
             $getTo = implode(",", array_keys($getTo));
         } else {
             $getTo = '';
         }
         \GO::debug("Sending e-mail to " . $getTo);
     }
     if (\GO::modules()->isInstalled("log")) {
         $str = "";
         $from = $message->getFrom();
         if (!empty($from)) {
             $str .= implode(",", array_keys($from));
         } else {
             $str .= "unknown";
         }
         $str .= " -> ";
         $to = $message->getTo();
         if (!empty($to)) {
             $str .= implode(",", array_keys($to));
         }
         $to = $message->getCc();
         if (!empty($to)) {
             $str .= implode(",", array_keys($to));
         }
         $to = $message->getBcc();
         if (!empty($to)) {
             $str .= implode(",", array_keys($to));
         }
         \GO\Log\Model\Log::create("email", $str);
     }
     //		debug_print_backtrace();
     //		exit("NO MAIL");
     //workaround https://github.com/swiftmailer/swiftmailer/issues/335
     $messageId = $message->getId();
     $count = parent::send($message, $failedRecipients);
     $message->setId($messageId);
     // Check if a tmp dir is created to store attachments.
     // If so, then remove the tmp dir if the mail is send successfully.
     $tmpDir = $message->getTmpDir();
     if (!empty($tmpDir)) {
         $folder = new \GO\Base\Fs\Folder($tmpDir);
         // Check if folder is deleted successfully
         if ($folder->delete()) {
             \GO::debug('Clear attachments tmp directory: ' . $tmpDir);
         } else {
             \GO::debug('Failed to clear attachments tmp directory: ' . $tmpDir);
         }
     }
     return $count;
 }
Exemplo n.º 13
0
 /**
  * Flush all values 
  */
 public function flush()
 {
     $this->_ttls = array();
     $this->_ttlsDirty = true;
     $folder = new \GO\Base\Fs\Folder($this->_dir);
     $folder->delete();
     $folder->create(0777);
 }
Exemplo n.º 14
0
 /**
  * Moves the node
  *
  * @param string $name The new name
  * @return void
  */
 public function move($newPath)
 {
     \GO::debug("FSD::move({$newPath})");
     if (!is_dir(dirname($newPath))) {
         throw new \Exception('Invalid move!');
     }
     $folder = $this->_getFolder();
     if (!$folder->checkPermissionLevel(\GO\Base\Model\Acl::WRITE_PERMISSION)) {
         throw new Sabre\DAV\Exception\Forbidden();
     }
     $destFsFolder = new \GO\Base\Fs\Folder($newPath);
     //\GO::debug("Dest folder: ".$destFsFolder->stripFileStoragePath());
     $destFolder = \GO\Files\Model\Folder::model()->findByPath($destFsFolder->parent()->stripFileStoragePath());
     $folder->parent_id = $destFolder->id;
     $folder->name = $destFsFolder->name();
     $folder->save();
     $this->relpath = $folder->path;
     $this->path = \GO::config()->file_storage_path . $this->relpath;
 }
Exemplo n.º 15
0
 /**
  * Move the folder to another folder.
  * 
  * @param Folder $destinationFolder 
  * @param string $newFolderName Optionally rename the folder too.
  * @param boolean $appendNumberToNameIfDestinationExists Rename the folder like "folder (1)" if it already exists.	 * 
  * @return Folder $destinationFolder
  */
 public function move(Folder $destinationFolder, $newFolderName = false, $appendNumberToNameIfDestinationExists = false)
 {
     if (!$this->exists()) {
         throw new \Exception("Folder '" . $this->path() . "' does not exist");
     }
     if (is_link($this->path)) {
         $link = new File($this->path);
         return $link->move($destinationFolder, $newFolderName, false, $appendNumberToNameIfDestinationExists);
     }
     $this->_validateSrcAndDestPath($destinationFolder->path(), $this->path());
     if (!$newFolderName) {
         $newFolderName = $this->name();
     }
     $newPath = $destinationFolder->path() . '/' . $newFolderName;
     if ($appendNumberToNameIfDestinationExists) {
         $folder = new Folder($newPath);
         $folder->appendNumberToNameIfExists();
         $newPath = $folder->path();
     }
     //do nothing if path is the same.
     if ($newPath == $this->path()) {
         return true;
     }
     if (!@rename($this->path(), $newPath)) {
         // Notice suppressed by @
         //	throw new Exception("Rename failed");
         // If renaming is throwing an error then do it the old way.
         // This is done because of problems when moving items across partitions.
         // See https://bugs.php.net/bug.php?id=50676 for more info about this.
         // If rename fails then try the old method
         $movedFolder = new \GO\Base\Fs\Folder($newPath);
         $movedFolder->create();
         $ls = $this->ls(true);
         foreach ($ls as $fsObject) {
             $fsObject->move($movedFolder);
         }
         $this->delete();
         $newPath = $movedFolder->path();
     }
     $this->path = $newPath;
     return true;
 }
 public function getHome($uid)
 {
     $home = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'owncloud/' . $this->_getUser($uid)->username);
     $home->create();
     return $home->path();
 }
Exemplo n.º 17
0
         }
         if (empty(\GO::config()->title)) {
             \GO::config()->title = 'Group-Office';
         }
         //set this to a default otherwise GO will keep autodetecting values
         if (empty(\GO::config()->db_user)) {
             \GO::config()->db_user = '******';
         }
         $f = new \GO\Base\Fs\Folder($_POST['file_storage_path']);
         if (!$f->exists()) {
             \GO\Base\Html\Input::setError("file_storage_path", "File storage folder doesn't exist. Please make sure it exists and it must be writable for the webserver user.");
         } elseif (!$f->isWritable()) {
             \GO\Base\Html\Input::setError("file_storage_path", "File storage must be writable for the webserver user.");
         }
         \GO::config()->file_storage_path = $f->path() . '/';
         $f = new \GO\Base\Fs\Folder($_POST['tmpdir']);
         if (!$f->exists() && !$f->create(0777)) {
             \GO\Base\Html\Input::setError("tmpdir", "Temporary folder doesn't exist. Please make sure it exists and it must be writable for the webserver user.");
         } elseif (!$f->isWritable()) {
             \GO\Base\Html\Input::setError("tmpdir", "Temporary folder must be writable for the webserver user.");
         }
         \GO::config()->tmpdir = $f->path() . '/';
         \GO::config()->save($config);
         if (!\GO\Base\Html\Input::hasErrors()) {
             redirect("regional.php");
         }
     }
 } catch (Exception $e) {
     \GO\Base\Html\Input::setError("form", $e->getMessage());
 }
 printHead();
Exemplo n.º 18
0
 /**
  * Publishes a file or a directory.
  * This method will copy the specified asset to a web accessible directory
  * and return the URL for accessing the published asset.
  * <ul>
  * <li>If the asset is a file, its file modification time will be checked
  * to avoid unnecessary file copying;</li>
  * <li>If the asset is a directory, all files and subdirectories under it will
  * be published recursively. Note, the method only checks the
  * existence of the target directory to avoid repetitive copying.</li>
  * </ul>
  *
  * @param string $path the asset (file or directory) to be published
  * @param boolean $hashByName whether the published directory should be named as the hashed basename.
  * If false, the name will be the hash taken from dirname of the path being published and path mtime.
  * Defaults to false. Set true if the path being published is shared among
  * different extensions.
  * @return string an absolute URL to the published asset
  * @throws Exception if the asset to be published does not exist.
  */
 public function publish($path, $hashByName = false)
 {
     if (isset($this->_published[$path])) {
         return $this->_published[$path];
     } else {
         if (($src = realpath($path)) !== false) {
             if (is_file($src)) {
                 $dir = $this->hash($hashByName ? basename($src) : dirname($src) . filemtime($src));
                 $fileName = basename($src);
                 $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir;
                 $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
                 if ($this->linkAssets) {
                     if (!is_file($dstFile)) {
                         if (!is_dir($dstDir)) {
                             mkdir($dstDir);
                             @chmod($dstDir, $this->newDirMode);
                         }
                         symlink($src, $dstFile);
                     }
                 } else {
                     if (@filemtime($dstFile) < @filemtime($src)) {
                         if (!is_dir($dstDir)) {
                             mkdir($dstDir);
                             @chmod($dstDir, $this->newDirMode);
                         }
                         copy($src, $dstFile);
                         @chmod($dstFile, $this->newFileMode);
                     }
                 }
                 return $this->_published[$path] = $this->getBaseUrl() . "/{$dir}/{$fileName}";
             } else {
                 if (is_dir($src)) {
                     $dir = $this->hash($hashByName ? basename($src) : $src . filemtime($src));
                     $dstDir = $this->getBasePath() . DIRECTORY_SEPARATOR . $dir;
                     if ($this->linkAssets) {
                         if (!is_dir($dstDir)) {
                             symlink($src, $dstDir);
                         }
                     } else {
                         if (!is_dir($dstDir)) {
                             $dstF = new \GO\Base\Fs\Folder($dstDir);
                             $folder = new \GO\Base\Fs\Folder($src);
                             $folder->copy($dstF);
                         }
                     }
                     return $this->_published[$path] = $this->getBaseUrl() . '/' . $dir;
                 }
             }
         }
     }
     throw new \Exception('The asset "' . $path . '" to be published does not exist.');
 }
Exemplo n.º 19
0
 /**
  * Movesthe node
  *
  * @param string $name The new name
  * @return void
  */
 public function move($newPath)
 {
     $this->checkWritePermission();
     \GO::debug('DAVFile::move(' . $this->path . ' -> ' . $newPath . ')');
     $destFsFolder = new \GO\Base\Fs\Folder(dirname($newPath));
     $destFolder = \GO\Files\Model\Folder::model()->findByPath($destFsFolder->stripFileStoragePath());
     $file = \GO\Files\Model\File::model()->findByPath($this->relpath);
     $file->folder_id = $destFolder->id;
     $file->name = \GO\Base\Fs\File::utf8Basename($newPath);
     $file->save();
     $this->relpath = $file->path;
     $this->path = \GO::config()->file_storage_path . $this->relpath;
 }
Exemplo n.º 20
0
 protected function actionUpload($params)
 {
     $relpath = 'public/bookmarks/';
     $folder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . $relpath);
     $folder->create();
     $files = \GO\Base\Fs\File::moveUploadedFiles($_FILES['attachments'], $folder);
     $file = $files[0];
     $file->rename($params['thumb_id'] . '.' . $file->extension());
     $response['logo'] = $file->stripFileStoragePath();
     $response['success'] = true;
     return $response;
 }
Exemplo n.º 21
0
 public static function handleUpload()
 {
     $tmpFolder = new \GO\Base\Fs\Folder(\GO::config()->tmpdir . 'uploadqueue');
     //$tmpFolder->delete();
     $tmpFolder->create();
     //		$files = \GO\Base\Fs\File::moveUploadedFiles($_FILES['attachments'], $tmpFolder);
     //		\GO::session()->values['files']['uploadqueue'] = array();
     //		foreach ($files as $file) {
     //			\GO::session()->values['files']['uploadqueue'][] = $file->path();
     //		}
     if (!isset(\GO::session()->values['files']['uploadqueue'])) {
         \GO::session()->values['files']['uploadqueue'] = array();
     }
     $targetDir = $tmpFolder->path();
     // Get parameters
     $chunk = isset($_POST["chunk"]) ? $_POST["chunk"] : 0;
     $chunks = isset($_POST["chunks"]) ? $_POST["chunks"] : 0;
     $fileName = isset($_POST["name"]) ? $_POST["name"] : '';
     // Clean the fileName for security reasons
     $fileName = \GO\Base\Fs\File::stripInvalidChars($fileName);
     // Make sure the fileName is unique but only if chunking is disabled
     //		if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
     //			$ext = strrpos($fileName, '.');
     //			$fileName_a = substr($fileName, 0, $ext);
     //			$fileName_b = substr($fileName, $ext);
     //
     //			$count = 1;
     //			while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
     //				$count++;
     //
     //			$fileName = $fileName_a . '_' . $count . $fileName_b;
     //		}
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     if (!in_array($targetDir . DIRECTORY_SEPARATOR . $fileName, \GO::session()->values['files']['uploadqueue'])) {
         \GO::session()->values['files']['uploadqueue'][] = $targetDir . DIRECTORY_SEPARATOR . $fileName;
     }
     $file = new \GO\Base\Fs\File($targetDir . DIRECTORY_SEPARATOR . $fileName);
     if ($file->exists() && $file->size() > \GO::config()->max_file_size) {
         throw new \Exception("File too large");
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($_FILES['file']['tmp_name'], "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     // Return JSON-RPC response
     die('{"jsonrpc" : "2.0", "result": null, "success":true, "id" : "id"}');
 }
Exemplo n.º 22
0
 protected function actionHandleUploads($params)
 {
     if (!isset(\GO::session()->values['files']['uploadqueue'])) {
         \GO::session()->values['files']['uploadqueue'] = array();
     }
     try {
         $chunkTmpFolder = new \GO\Base\Fs\Folder(\GO::config()->tmpdir . 'juploadqueue/chunks');
         $tmpFolder = new \GO\Base\Fs\Folder(\GO::config()->tmpdir . 'juploadqueue');
         $tmpFolder->create();
         $chunkTmpFolder->create();
         $count = 0;
         while ($uploadedFile = array_shift($_FILES)) {
             if (isset($params['jupart'])) {
                 $originalFileName = $uploadedFile['name'];
                 $uploadedFile['name'] = $uploadedFile['name'] . '.part' . $params['jupart'];
                 $chunkTmpFolder->create();
                 \GO\Base\Fs\File::moveUploadedFiles($uploadedFile, $chunkTmpFolder);
                 if (!empty($params['jufinal'])) {
                     $file = new \GO\Base\Fs\File($tmpFolder . '/' . $originalFileName);
                     $fp = fopen($file->path(), 'w+');
                     for ($i = 1; $i <= $params['jupart']; $i++) {
                         $part = new \GO\Base\Fs\File($chunkTmpFolder . '/' . $originalFileName . '.part' . $i);
                         fwrite($fp, $part->contents());
                         $part->delete();
                     }
                     fclose($fp);
                     $chunkTmpFolder->delete();
                 } else {
                     echo "SUCCESS\n";
                     return;
                 }
             } else {
                 $files = \GO\Base\Fs\File::moveUploadedFiles($uploadedFile, $tmpFolder);
                 if (!$files) {
                     throw new \Exception("No file received");
                 }
                 $file = $files[0];
             }
             $subdir = false;
             if (!empty($params['relpathinfo' . $count]) && !isset($params['jupart']) || !empty($params['relpathinfo' . $count]) && isset($params['jupart']) && !empty($params['jufinal'])) {
                 $fullpath = \GO::config()->tmpdir . 'juploadqueue' . '/' . str_replace('\\', '/', $params['relpathinfo' . $count]);
                 $dir = new \GO\Base\Fs\Folder($fullpath);
                 $dir->create();
                 $subdir = true;
                 $file->move($dir);
             }
             $count++;
             if ($subdir) {
                 $parent = $this->_findHighestParent($dir);
                 \GO::debug($parent);
                 if (!in_array($parent->path(), \GO::session()->values['files']['uploadqueue'])) {
                     \GO::session()->values['files']['uploadqueue'][] = $parent->path();
                 }
             } else {
                 \GO::session()->values['files']['uploadqueue'][] = $file->path();
             }
         }
     } catch (\Exception $e) {
         echo 'WARNING: ' . $e->getMessage() . "\n";
     }
     echo "SUCCESS\n";
 }
Exemplo n.º 23
0
//define ('K_PATH_IMAGES', '');
/**
 * Deafult image logo used be the default Header() method.
 * Please set here your own logo or an empty string to disable it.
 */
//define ('PDF_HEADER_LOGO', '');
/**
 * Header logo image width in user units.
 */
//define ('PDF_HEADER_LOGO_WIDTH', 0);
/**
 * Cache directory for temporary files (full path).
 */
//define ('K_PATH_CACHE', sys_get_temp_dir().'/');
define('K_PATH_CACHE', \GO::config()->file_storage_path . 'tcpdfcache/');
$f = new \GO\Base\Fs\Folder(K_PATH_CACHE);
$f->create();
/**
 * Generic name for a blank image.
 */
define('K_BLANK_IMAGE', '_blank.png');
/**
 * Page format.
 */
define('PDF_PAGE_FORMAT', 'A4');
/**
 * Page orientation (P=portrait, L=landscape).
 */
define('PDF_PAGE_ORIENTATION', 'P');
/**
 * Document creator.
Exemplo n.º 24
0
 /**
  * Find classes in a folder
  *
  * @param string $path Relative from $config['file_storage_path'].'php/'
  * @return \ReflectionClass[]
  */
 public static function findFsClasses($subfolder, $subClassOf = null)
 {
     $classes = array();
     $folder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'php/' . $subfolder);
     if ($folder->exists()) {
         $items = $folder->ls();
         foreach ($items as $item) {
             if ($item instanceof \GO\Base\Fs\File) {
                 $className = 'GOFS\\';
                 $subFolders = explode('/', $subfolder);
                 foreach ($subFolders as $sf) {
                     $className .= ucfirst($sf) . '\\';
                 }
                 $className .= $item->nameWithoutExtension();
                 $rc = new \ReflectionClass($className);
                 if ($subClassOf == null || $rc->isSubclassOf($subClassOf)) {
                     $classes[] = $rc;
                 }
             }
         }
     }
     return $classes;
 }