Ejemplo n.º 1
0
 public function actionImportIcs($params)
 {
     $response = array('success' => true);
     $count = 0;
     $failed = array();
     if (!file_exists($_FILES['ical_file']['tmp_name'][0])) {
         throw new \Exception($lang['common']['noFileUploaded']);
     } else {
         $file = new \GO\Base\Fs\File($_FILES['ical_file']['tmp_name'][0]);
         $file->convertToUtf8();
         $contents = $file->getContents();
         $vcal = \GO\Base\VObject\Reader::read($contents);
         \GO\Base\VObject\Reader::convertVCalendarToICalendar($vcal);
         foreach ($vcal->vtodo as $vtask) {
             $event = new \GO\Tasks\Model\Task();
             try {
                 $event->importVObject($vtask, array('tasklist_id' => $params['tasklist_id']));
                 $count++;
             } catch (\Exception $e) {
                 $failed[] = $e->getMessage();
             }
         }
     }
     $response['feedback'] = sprintf(\GO::t('import_success', 'tasks'), $count);
     if (count($failed)) {
         $response['feedback'] .= "\n\n" . count($failed) . " tasks failed: " . implode('\\n', $failed);
     }
     return $response;
 }
Ejemplo n.º 2
0
 public function __construct(\GO\Site\Model\Site $siteModel)
 {
     $file = new \GO\Base\Fs\File($siteModel->getSiteModule()->moduleManager->path() . 'siteconfig.php');
     if ($file->exists()) {
         require $file->path();
     }
     if (isset($siteconfig)) {
         $this->_configOptions = $siteconfig;
     }
 }
Ejemplo n.º 3
0
 /**
  * This will copy a file in the files module to a public accessable folder
  * 
  * @param array $params
  * - stromg src: path the the file relative the the sites public storage folder.
  * @return the rsult of the thumb action on the core controller
  * @throws \GO\Base\Exception\AccessDenied when unable to create the folder?
  */
 protected function actionThumb($params)
 {
     $rootFolder = new \GO\Base\Fs\Folder(\GO::config()->file_storage_path . 'site/' . \Site::model()->id);
     $file = new \GO\Base\Fs\File(\GO::config()->file_storage_path . 'site/' . \Site::model()->id . '/' . $params['src']);
     $folder = $file->parent();
     $ok = $folder->isSubFolderOf($rootFolder);
     if (!$ok) {
         throw new \GO\Base\Exception\AccessDenied();
     }
     $c = new \GO\Core\Controller\CoreController();
     return $c->run('thumb', $params, true, false);
 }
Ejemplo n.º 4
0
 public function createTempFile()
 {
     if (!$this->hasTempFile()) {
         $tmpFile = new \GO\Base\Fs\File($this->getTempDir() . \GO\Base\Fs\File::stripInvalidChars($this->name));
         //			This fix for duplicate filenames in forwards caused screwed up attachment names!
         //			A possible new fix should be made in ImapMessage->getAttachments()
         //
         //			$file = new \GO\Base\Fs\File($this->name);
         //			$tmpFile = new \GO\Base\Fs\File($this->getTempDir().uniqid(time()).'.'.$file->extension());
         if (!$tmpFile->exists()) {
             $imap = $this->account->openImapConnection($this->mailbox);
             $imap->save_to_file($this->uid, $tmpFile->path(), $this->number, $this->encoding, true);
         }
         $this->setTempFile($tmpFile);
     }
     return $this->getTempFile();
 }
Ejemplo n.º 5
0
 protected function actionCreateFile($params)
 {
     $filename = \GO\Base\Fs\File::stripInvalidChars($params['filename']);
     if (empty($filename)) {
         throw new \Exception("Filename can not be empty");
     }
     $template = \GO\Files\Model\Template::model()->findByPk($params['template_id']);
     $folder = \GO\Files\Model\Folder::model()->findByPk($params['folder_id']);
     $path = \GO::config()->file_storage_path . $folder->path . '/' . $filename;
     if (!empty($template->extension)) {
         $path .= '.' . $template->extension;
     }
     $fsFile = new \GO\Base\Fs\File($path);
     $fsFile->putContents($template->content);
     $fileModel = \GO\Files\Model\File::importFromFilesystem($fsFile);
     if (!$fileModel) {
         throw new Exception("Could not create file");
     }
     return array('id' => $fileModel->id, 'success' => true);
 }
Ejemplo n.º 6
0
 private function _saveHeaders()
 {
     if (!$this->saved_headers) {
         $tempInFile = new \GO\Base\Fs\File(\GO::config()->tmpdir . "smime_tempin.txt");
         $tempInFile->parent()->create();
         $tempInFile->delete();
         $tempOutFile = new \GO\Base\Fs\File(\GO::config()->tmpdir . "smime_tempout.txt");
         $tempOutFile->delete();
         $this->tempin = $tempInFile->path();
         $this->tempout = $tempOutFile->path();
         /*
          * Store the headers of the current message because the PHP function
          * openssl_pkcs7_sign will rebuilt the MIME structure and will put the main
          * headers in a nested mimepart. We don't want that so we remove them now 
          * and add them to the new structure later.
          */
         $headers = $this->getHeaders();
         $headers->removeAll('MIME-Version');
         //		$headers->removeAll('Content-Type');
         $this->saved_headers = array();
         //$headers->toString();
         $ignored_headers = array('Content-Transfer-Encoding', 'Content-Type');
         $h = $headers->getAll();
         foreach ($h as $header) {
             $name = $header->getFieldName();
             if (!in_array($name, $ignored_headers)) {
                 $this->saved_headers[$name] = $header->getFieldBody();
                 $headers->removeAll($name);
             }
         }
         /*
          * This class will stream the MIME structure to the tempin text file in 
          * a memory efficient way.
          */
         $fbs = new \Swift_ByteStream_FileByteStream($this->tempin, true);
         parent::toByteStream($fbs);
         if (!file_exists($this->tempin)) {
             throw new \Exception('Could not write temporary message for signing');
         }
     }
 }
Ejemplo n.º 7
0
 /**
  * Creates a new file in the directory
  *
  * data is a readable stream resource
  *
  * @param string $name Name of the file
  * @param resource $data Initial payload
  * @return void
  */
 public function createFile($name, $data = null)
 {
     \GO::debug("FSD::createFile({$name})");
     $folder = $this->_getFolder();
     if (!$folder->checkPermissionLevel(\GO\Base\Model\Acl::WRITE_PERMISSION)) {
         throw new Sabre\DAV\Exception\Forbidden();
     }
     $newFile = new \GO\Base\Fs\File($this->path . '/' . $name);
     if ($newFile->exists()) {
         throw new \Exception("File already exists!");
     }
     $tmpFile = \GO\Base\Fs\File::tempFile();
     $tmpFile->putContents($data);
     if (!\GO\Files\Model\File::checkQuota($tmpFile->size())) {
         $tmpFile->delete();
         throw new Sabre\DAV\Exception\InsufficientStorage();
     }
     //		$newFile->putContents($data);
     $tmpFile->move($folder->fsFolder, $name);
     $folder->addFile($name);
 }
Ejemplo n.º 8
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 \GO\Base\Cron\CronJob $cronJob
  * @param \GO\Base\Model\User $user [OPTIONAL]
  */
 public function run(\GO\Base\Cron\CronJob $cronJob, \GO\Base\Model\User $user = null)
 {
     \GO::session()->runAsRoot();
     \GO::debug("Start updating public calendars.");
     $calendars = \GO\Calendar\Model\Calendar::model()->findByAttribute('public', true);
     foreach ($calendars as $calendar) {
         $file = new \GO\Base\Fs\File($calendar->getPublicIcsPath());
         if (!$file->exists()) {
             \GO::debug("Creating " . $file->path() . ".");
             $file->touch(true);
         }
         $file->putContents($calendar->toVObject());
         \GO::debug("Updating " . $calendar->name . " to " . $file->path() . ".");
     }
     \GO::debug("Finished updating public calendars.");
 }
Ejemplo n.º 9
0
 protected function actionImportIcs($params)
 {
     $file = new \GO\Base\Fs\File($params['file']);
     $data = $file->getContents();
     $vcalendar = \GO\Base\VObject\Reader::read($data);
     \GO\Base\VObject\Reader::convertVCalendarToICalendar($vcalendar);
     foreach ($vcalendar->vtodo as $vtodo) {
         $task = new \GO\Tasks\Model\Task();
         $task->importVObject($vtodo);
     }
 }
Ejemplo n.º 10
0
 /**
  * Get a thumbnail URL for user uploaded files. This does not work for template
  * images.
  * 
  * @param string $relativePath
  * @param array $thumbParams
  * @return string URL to thumbnail
  */
 public static function thumb($relativePath, $thumbParams = array("lw" => 100, "ph" => 100, "zc" => 1))
 {
     $file = new \GO\Base\Fs\File(\GO::config()->file_storage_path . $relativePath);
     $thumbParams['filemtime'] = $file->mtime();
     $thumbParams['src'] = $relativePath;
     return \Site::urlManager()->createUrl('site/front/thumb', $thumbParams);
 }
Ejemplo n.º 11
0
 /**
  * Saves the report to a file
  * output path and filename should be set before calling this function
  * @param \GO\Projects2\Model\Project $project the project object
  * @return \GO\Files\Model\File
  */
 public function save()
 {
     $file = new \GO\Base\Fs\File($this->_outputPath . '/' . $this->filename . '.' . $this->fileExtension());
     $file->appendNumberToNameIfExists();
     $this->_outputPath = $file->path();
     $str = $this->render(true);
     if (!isset($this->_fp)) {
         $this->_fp = fopen($this->_outputPath, 'w+');
     }
     fputs($this->_fp, $str);
     $folder = \GO\Files\Model\Folder::model()->findByPath($file->parent()->stripFileStoragePath());
     $fileModel = $folder->addFile($file->name());
     return $fileModel;
 }
Ejemplo n.º 12
0
 /**
  * Returns the mime-type for a file
  *
  * If null is returned, we'll assume application/octet-stream
  *
  * @return mixed
  */
 public function getContentType()
 {
     $fsFile = new \GO\Base\Fs\File($this->path);
     return $fsFile->mimeType();
 }
Ejemplo n.º 13
0
 /**
  * Returns the path to the viewfile based on the used template and module
  * It will search for a template first if not found look in the views/site/ folder
  * the default viewfile provided by the module
  * @param string $viewName name to the viewfile
  * @return string path of the viewfile
  */
 public function getViewFile($viewName)
 {
     $module = \Site::model()->getSiteModule();
     if (substr($viewName, 0, 1) != "/") {
         $classParts = explode('\\', get_class($this));
         $moduleId = strtolower($classParts[1]);
         $viewName = '/' . $moduleId . '/' . $viewName;
     }
     $file = new \GO\Base\Fs\File($module->moduleManager->path() . 'views/site/' . $viewName . '.php');
     if (!$file->exists()) {
         throw new \Exception("View '{$viewName}' not found!");
     }
     return $file->path();
 }
Ejemplo n.º 14
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";
 }
Ejemplo n.º 15
0
 function process_form()
 {
     \GO::$ignoreAclPermissions = true;
     $this->check_required();
     if (!isset($_POST['salutation'])) {
         $_POST['salutation'] = isset($_POST['sex']) ? \GO::t('default_salutation_' . $_POST['sex']) : \GO::t('default_salutation_unknown');
     }
     //user registation
     //		if(!empty($_POST['username'])){
     //			$credentials = array ('username','first_name','middle_name','last_name','title','initials','sex','email',
     //			'home_phone','fax','cellular','address','address_no',
     //			'zip','city','state','country','company','department','function','work_phone',
     //			'work_fax');
     //
     //			if($_POST['password1'] != $_POST['password2'])
     //			{
     //				throw new Exception(\GO::t('error_match_pass','users'));
     //			}
     //
     //			foreach($credentials as $key)
     //			{
     //				if(!empty($_REQUEST[$key]))
     //				{
     //					$userCredentials[$key] = $_REQUEST[$key];
     //				}
     //			}
     //			$userCredentials['password']=$_POST['password1'];
     //
     //			$userModel = new \GO\Base\Model\User();
     //			$userModel->setAttributes($userCredentials);
     //			$userModel->save();
     //			foreach($this->user_groups as $groupId) {
     //				$currentGroupModel = \GO\Base\Model\Group::model()->findByPk($groupId);
     //				if($groupId>0 && $groupId!=\GO::config()->group_everyone && !$currentGroupModel->hasUser($userModel->id)) {
     //					$currentGroupModel->addUser($userModel->id);
     //				}
     //			}
     //			foreach($this->visible_user_groups as $groupId) {
     //				$userAclModel = \GO\Base\Model\Acl::model()->findByPk($userModel->acl_id);
     //				if($groupId>0 && !empty($userAclModel) && $userAclModel->hasGroup($groupId)) {
     //					$userAclModel->addGroup($groupId);
     //				}
     //			}
     //
     //			\GO::session()->login($userCredentials['username'], $userCredentials['password']);
     //		}
     if (!empty($_POST['email']) && !\GO\Base\Util\String::validate_email($_POST['email'])) {
         throw new Exception(\GO::t('invalidEmailError'));
     }
     if (!empty($_REQUEST['addressbook'])) {
         //			require($GO_LANGUAGE->get_language_file('addressbook'));
         //			require_once($GO_MODULES->modules['addressbook']['class_path'].'addressbook.class.inc.php');
         //			$ab = new addressbook();
         //
         //			$addressbook = $ab->get_addressbook_by_name($_REQUEST['addressbook']);
         $addressbookModel = \GO\Addressbook\Model\Addressbook::model()->findSingleByAttribute('name', $_REQUEST['addressbook']);
         if (!$addressbookModel) {
             throw new Exception('Addressbook not found!');
         }
         $credentials = array('first_name', 'middle_name', 'last_name', 'title', 'initials', 'sex', 'email', 'email2', 'email3', 'home_phone', 'fax', 'cellular', 'comment', 'address', 'address_no', 'zip', 'city', 'state', 'country', 'company', 'department', 'function', 'work_phone', 'work_fax', 'salutation', 'url_linkedin', 'url_facebook', 'url_twitter', 'skype_name');
         foreach ($credentials as $key) {
             if (!empty($_REQUEST[$key])) {
                 $contactCredentials[$key] = $_REQUEST[$key];
             }
         }
         if (isset($contactCredentials['comment']) && is_array($contactCredentials['comment'])) {
             $comments = '';
             foreach ($contactCredentials['comment'] as $key => $value) {
                 if ($value == 'date') {
                     $value = date($_SESSION['GO_SESSION']['date_format'] . ' ' . $_SESSION['GO_SESSION']['time_format']);
                 }
                 if (!empty($value)) {
                     $comments .= trim($key) . ":\n" . trim($value) . "\n\n";
                 }
             }
             $contactCredentials['comment'] = $comments;
         }
         if ($this->no_urls && isset($contactCredentials['comment']) && stripos($contactCredentials['comment'], 'http')) {
             throw new Exception('Sorry, but to prevent spamming we don\'t allow URL\'s in the message');
         }
         $contactCredentials['addressbook_id'] = $addressbookModel->id;
         $contactCredentials['email_allowed'] = isset($_POST['email_allowed']) ? '1' : '0';
         if (!empty($contactCredentials['company']) && empty($contactCredentials['company_id'])) {
             $companyModel = \GO\Addressbook\Model\Company::model()->findSingleByAttributes(array('name' => $contactCredentials['company'], 'addressbook_id' => $contactCredentials['addressbook_id']));
             if (empty($companyModel)) {
                 $companyModel = new \GO\Addressbook\Model\Company();
                 $companyModel->addressbook_id = $contactCredentials['addressbook_id'];
                 $companyModel->name = $contactCredentials['company'];
                 // bedrijfsnaam
                 $companyModel->user_id = \GO::user()->id;
                 $companyModel->save();
                 $contactCredentials['company_id'] = $companyModel->id;
             }
         }
         if (isset($_POST['birthday'])) {
             try {
                 $contactCredentials['birthday'] = \GO\Base\Util\Date::to_db_date($_POST['birthday'], false);
             } catch (Exception $e) {
                 throw new Exception(\GO::t('birthdayFormatMustBe') . ': ' . $_SESSION['GO_SESSION']['date_format'] . '.');
             }
             if (!empty($_POST['birthday']) && $contactCredentials['birthday'] == '0000-00-00') {
                 throw new Exception(\GO::t('invalidDateError'));
             }
         }
         unset($contactCredentials['company']);
         $existingContactModel = false;
         if (!empty($_POST['contact_id'])) {
             $existingContactModel = \GO\Addressbook\Model\Contact::model()->findByPk($_POST['contact_id']);
         } elseif (!empty($contactCredentials['email'])) {
             $existingContactModel = \GO\Addressbook\Model\Contact::model()->findSingleByAttributes(array('email' => $contactCredentials['email'], 'addressbook_id' => $contactCredentials['addressbook_id']));
         }
         if ($existingContactModel) {
             $this->contact_id = $contactId = $existingContactModel->id;
             $filesFolderId = $existingContactModel->files_folder_id = $existingContactModel->getFilesFolder()->id;
             /*
              * Only update empty fields
              */
             if (empty($_POST['contact_id'])) {
                 foreach ($contactCredentials as $key => $value) {
                     if ($key != 'comment') {
                         if (!empty($existingContactModel->{$key})) {
                             unset($contactCredentials[$key]);
                         }
                     }
                 }
             }
             $contactCredentials['id'] = $contactId;
             if (!empty($existingContactModel->comment) && !empty($contactCredentials['comment'])) {
                 $contactCredentials['comment'] = $existingContactModel->comment . "\n\n----\n\n" . $contactCredentials['comment'];
             }
             if (empty($contactCredentials['comment'])) {
                 unset($contactCredentials['comment']);
             }
             $existingContactModel->setAttributes($contactCredentials);
             $existingContactModel->save();
         } else {
             $newContactModel = new \GO\Addressbook\Model\Contact();
             $newContactModel->setAttributes($contactCredentials);
             $newContactModel->save();
             $this->contact_id = $contactId = $newContactModel->id;
             $filesFolderId = $newContactModel->files_folder_id = $newContactModel->getFilesFolder()->id;
             $newContactModel->save();
             if (isset($_POST['contact_id']) && empty($userId) && \GO::user()->id > 0) {
                 $userId = $this->user_id = \GO::user()->id;
             }
             if (!empty($userId)) {
                 $userModel = \GO\Base\Model\User::model()->findByPk($userId);
                 $userModel->contact_id = $contactId;
                 $userModel->save();
             }
         }
         if (!$contactId) {
             throw new Exception(\GO::t('saveError'));
         }
         if (\GO::modules()->isInstalled('files')) {
             $folderModel = \GO\Files\Model\Folder::model()->findByPk($filesFolderId);
             $path = $folderModel->path;
             $response['files_folder_id'] = $filesFolderId;
             $full_path = \GO::config()->file_storage_path . $path;
             foreach ($_FILES as $key => $file) {
                 if ($key != 'photo') {
                     //photo is handled later
                     if (is_uploaded_file($file['tmp_name'])) {
                         $fsFile = new \GO\Base\Fs\File($file['tmp_name']);
                         $fsFile->move(new \GO\Base\Fs\Folder($full_path), $file['name'], false, true);
                         $fsFile->setDefaultPermissions();
                         \GO\Files\Model\File::importFromFilesystem($fsFile);
                     }
                 }
             }
         }
         if (\GO::modules()->isInstalled('customfields')) {
             $cfFields = array();
             foreach ($_POST as $k => $v) {
                 if (strpos($k, 'col_') === 0) {
                     $cfFields[$k] = $v;
                 }
             }
             $contactCfModel = \GO\Addressbook\Customfields\Model\Contact::model()->findByPk($contactId);
             if (!$contactCfModel) {
                 $contactCfModel = new \GO\Addressbook\Customfields\Model\Contact();
                 $contactCfModel->model_id = $contactId;
             }
             $contactCfModel->setAttributes($cfFields);
             $contactCfModel->save();
         }
         if (isset($_POST['mailings'])) {
             foreach ($_POST['mailings'] as $mailingName) {
                 if (!empty($mailingName)) {
                     $addresslistModel = \GO\Addressbook\Model\Addresslist::model()->findSingleByAttribute('name', $mailingName);
                     if (empty($addresslistModel)) {
                         throw new Exception('Addresslist not found!');
                     }
                     $addresslistModel->addManyMany('contacts', $contactId);
                 }
             }
         }
         if ($this->contact_id > 0) {
             if (isset($_FILES['photo']['tmp_name']) && is_uploaded_file($_FILES['photo']['tmp_name'])) {
                 $fsFile = new \GO\Base\Fs\File($_FILES['photo']['tmp_name']);
                 $fsFile->move(new \GO\Base\Fs\Folder(\GO::config()->tmpdir), $_FILES['photo']['name'], false, false);
                 $contactModel = \GO\Addressbook\Model\Contact::model()->findByPk($contactId);
                 $contactModel->setPhoto(\GO::config()->tmpdir . $_FILES['photo']['name']);
             }
         }
         if (!isset($_POST['contact_id'])) {
             /**
              * Send notification of new contact to (1) users specified by 'notify_users'
              * in the form itself and to (2) the addressbook owner if so specified. 
              */
             // Send the email to the admin users in the language of the addressbook owner.
             $oldLanguage = \GO::language()->getLanguage();
             \GO::language()->setLanguage($addressbookModel->user->language);
             $usersToNotify = isset($_POST['notify_users']) ? explode(',', $_POST['notify_users']) : array();
             if (!empty($_POST['notify_addressbook_owner'])) {
                 $usersToNotify[] = $addressbookModel->user_id;
             }
             $mailTo = array();
             foreach ($usersToNotify as $userToNotifyId) {
                 $userModel = \GO\Base\Model\User::model()->findByPk($userToNotifyId);
                 $mailTo[] = $userModel->email;
             }
             if (count($mailTo)) {
                 $viewContactUrl = \GO::createExternalUrl('addressbook', 'showContact', array($contactId));
                 $contactModel = \GO\Addressbook\Model\Contact::model()->findByPk($contactId);
                 $companyModel = \GO\Addressbook\Model\Company::model()->findByPk($contactModel->company_id);
                 if (!empty($companyModel)) {
                     $companyName = $companyModel->name;
                 } else {
                     $companyName = '';
                 }
                 $values = array('address_no', 'address', 'zip', 'city', 'state', 'country');
                 $formatted_address = nl2br(\GO\Base\Util\Common::formatAddress('{country}', '{address}', '{address_no}', '{zip}', '{city}', '{state}'));
                 foreach ($values as $val) {
                     $formatted_address = str_replace('{' . $val . '}', $contactModel->{$val}, $formatted_address);
                 }
                 $body = \GO::t('newContactFromSite', 'addressbook') . ':<br />';
                 $body .= \GO::t('name', 'addressbook') . ': ' . $contactModel->addressbook->name . '<br />';
                 $body .= "<br />" . $contactModel->name;
                 $body .= "<br />" . $formatted_address;
                 if (!empty($contactModel->home_phone)) {
                     $body .= "<br />" . \GO::t('phone') . ': ' . $contactModel->home_phone;
                 }
                 if (!empty($contactModel->cellular)) {
                     $body .= "<br />" . \GO::t('cellular') . ': ' . $contactModel->cellular;
                 }
                 if (!empty($companyName)) {
                     $body .= "<br /><br />" . $companyName;
                 }
                 if (!empty($contactModel->work_phone)) {
                     $body .= "<br />" . \GO::t('workphone') . ': ' . $contactModel->work_phone;
                 }
                 $body .= '<br /><a href="' . $viewContactUrl . '">' . \GO::t('clickHereToView', 'addressbook') . '</a>' . "<br />";
                 $mailFrom = !empty($_POST['mail_from']) ? $_POST['mail_from'] : \GO::config()->webmaster_email;
                 $mailMessage = \GO\Base\Mail\Message::newInstance(\GO::t('newContactAdded', 'addressbook'), $body, 'text/html')->setFrom($mailFrom, \GO::config()->title);
                 foreach ($mailTo as $v) {
                     $mailMessage->addTo($v);
                 }
                 \GO\Base\Mail\Mailer::newGoInstance()->send($mailMessage);
             }
             // Restore the language
             \GO::language()->setLanguage($oldLanguage);
         }
         //
         //
         //	Maybe make this workable with GO 4.0 later....
         //
         //
         //			if(isset($_POST['confirmation_template']))
         //			{
         //				if(empty($_POST['email']))
         //				{
         //					throw new Exception('Fatal error: No email given for confirmation e-mail!');
         //				}
         //
         //				$url = create_direct_url('addressbook', 'showContact', array($contactId));
         //				$body = $lang['addressbook']['newContactFromSite'].'<br /><a href="'.$url.'">'.$lang['addressbook']['clickHereToView'].'</a>';
         //
         //				global $smarty;
         //				$email = $smarty->fetch($_POST['confirmation_template']);
         //
         //				$pos = strpos($email,"\n");
         //
         //				$subject = trim(substr($email, 0, $pos));
         //				$body = trim(substr($email,$pos));
         //
         //				require_once(\GO::config()->class_path.'mail/GoSwift.class.inc.php');
         //				$swift = new GoSwift($_POST['email'], $subject);
         //				$swift->set_body($body);
         //				$swift->set_from(\GO::config()->webmaster_email, \GO::config()->title);
         //				$swift->sendmail();
         //			}
         if (isset($_POST['confirmation_email']) && !empty($_POST['email'])) {
             if (strpos($_POST['confirmation_email'], '../') !== false || strpos($_POST['confirmation_email'], '..\\') !== false) {
                 throw new Exception('Invalid path');
             }
             $path = \GO::config()->file_storage_path . $_POST['confirmation_email'];
             if (!file_exists($path)) {
                 $path = dirname(\GO::config()->get_config_file()) . '/' . $_POST['confirmation_email'];
             }
             //$email = file_get_contents($path);
             //$messageModel = \GO\Email\Model\SavedMessage::model()->createFromMimeFile($path);
             //				$htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceUserTags($messageModel->getHtmlBody());
             //				$htmlBodyString = \GO\Addressbook\Model\Template::model()
             //								->replaceContactTags(
             //												$htmlBodyString,
             //												\GO\Addressbook\Model\Contact::model()->findByPk($contactId),
             //												false);
             //				$messageModel->body =
             $mailMessage = \GO\Base\Mail\Message::newInstance()->loadMimeMessage(file_get_contents($path));
             $htmlBodyString = $mailMessage->getBody();
             foreach ($this->confirmation_replacements as $tag => $replacement) {
                 $htmlBodyString = str_replace('{' . $tag . '}', $replacement, $htmlBodyString);
             }
             $htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceUserTags($htmlBodyString, true);
             $htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceContactTags($htmlBodyString, \GO\Addressbook\Model\Contact::model()->findByPk($contactId), false);
             $mailMessage->setBody($htmlBodyString);
             $mailMessage->setFrom($mailMessage->getFrom(), $mailMessage->getSender());
             $mailMessage->addTo($_POST['email']);
             \GO\Base\Mail\Mailer::newGoInstance()->send($mailMessage);
         }
     }
 }
Ejemplo n.º 16
0
 /**
  *
  * @return ImapMessageAttachment [] 
  */
 public function &getAttachments()
 {
     if (!$this->_imapAttachmentsLoaded) {
         $this->_imapAttachmentsLoaded = true;
         $imap = $this->getImapConnection();
         $this->_loadBodyParts();
         $parts = $imap->find_message_attachments($this->_getStruct(), $this->_bodyPartNumbers);
         $uniqueNames = array();
         foreach ($parts as $part) {
             //ignore applefile's
             //	Don't ignore it as it seems to be a valid attachment in some mails.
             //				if($part['subtype']=='applefile')
             //					continue;
             $a = new ImapMessageAttachment();
             $a->setImapParams($this->account, $this->mailbox, $this->uid);
             if (empty($part['name']) || $part['name'] == 'false') {
                 if (!empty($part['subject'])) {
                     $a->name = \GO\Base\Fs\File::stripInvalidChars(\GO\Base\Mail\Utils::mimeHeaderDecode($part['subject'])) . '.eml';
                 } elseif ($part['type'] == 'message') {
                     $a->name = isset($part['description']) ? \GO\Base\Fs\File::stripInvalidChars($part['description']) . '.eml' : 'message.eml';
                 } elseif ($part['subtype'] == 'calendar') {
                     $a->name = \GO::t('event', 'email') . '.ics';
                 } else {
                     if ($part['type'] == 'text') {
                         $a->name = $part['subtype'] . '.txt';
                     } else {
                         $a->name = $part['type'] . '-' . $part['subtype'];
                     }
                 }
             } else {
                 $a->name = \GO\Base\Mail\Utils::mimeHeaderDecode($part['name']);
                 $extension = \GO\Base\Fs\File::getExtension($a->name);
                 if (!empty($part['filename']) && empty($extension)) {
                     $a->name = \GO\Base\Mail\Utils::mimeHeaderDecode($part['filename']);
                 }
             }
             $i = 1;
             $a->name = !empty($a->name) ? $a->name : \GO::t('noname', 'email');
             $file = new \GO\Base\Fs\File($a->name);
             while (in_array($a->name, $uniqueNames)) {
                 $a->name = $file->nameWithoutExtension() . ' (' . $i . ').' . $file->extension();
                 $i++;
             }
             $uniqueNames[] = $a->name;
             $a->disposition = isset($part['disposition']) ? strtolower($part['disposition']) : '';
             $a->number = $part['number'];
             $a->content_id = '';
             if (!empty($part["id"])) {
                 //when an image has an id it belongs somewhere in the text we gathered above so replace the
                 //source id with the correct link to display the image.
                 $tmp_id = $part["id"];
                 if (strpos($tmp_id, '>')) {
                     $tmp_id = substr($part["id"], 1, -1);
                 }
                 $id = $tmp_id;
                 $a->content_id = $id;
             }
             $a->mime = $part['type'] . '/' . $part['subtype'];
             $a->index = count($this->attachments);
             $a->size = intval($part['size']);
             $a->encoding = $part['encoding'];
             $a->charset = !empty($part['charset']) ? $part['charset'] : $this->charset;
             $this->addAttachment($a);
         }
     }
     return $this->attachments;
 }
Ejemplo n.º 17
0
 /**
  * Get the holiday locale from the $countryCode that is provided.
  * 
  * If no match can be found then the self::$systemDefaultLocale variable is used.
  * 
  * @param string $countryCode
  * @return mixed the locale for the holidays or false when none found
  */
 public static function localeFromCountry($countryCode)
 {
     if (key_exists($countryCode, self::$mapping)) {
         $countryCode = self::$mapping[$countryCode];
     } else {
         if (key_exists(strtolower($countryCode), self::$mapping)) {
             $countryCode = self::$mapping[strtolower($countryCode)];
         }
     }
     $languageFolderPath = \GO::config()->root_path . 'language/holidays/';
     $file = new \GO\Base\Fs\File($languageFolderPath . $countryCode . '.php');
     if ($file->exists()) {
         return $countryCode;
     } else {
         $file = new \GO\Base\Fs\File($languageFolderPath . strtolower($countryCode) . '.php');
         if ($file->exists()) {
             return strtolower($countryCode);
         }
     }
     return false;
 }
Ejemplo n.º 18
0
 /**
  * Get the file extension
  * 
  * @return string
  */
 public function getExtension()
 {
     $file = new \GO\Base\Fs\File($this->name);
     return strtolower($file->extension());
 }
Ejemplo n.º 19
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();
 }
Ejemplo n.º 20
0
    protected function actionCreate($params)
    {
        if ($this->isCli()) {
            \GO::session()->runAsRoot();
        } elseif (!\GO::user()->isAdmin()) {
            throw new \GO\Base\Exception\AccessDenied();
        }
        if (\GO::modules()->customfields) {
            $customfieldModels = \GO\Customfields\CustomfieldsModule::getCustomfieldModels();
            $types = \GO\Customfields\CustomfieldsModule::getCustomfieldTypes();
            foreach ($customfieldModels as $model) {
                //				echo $model->getName(),'<br />';
                $category = \GO\Customfields\Model\Category::model()->createIfNotExists(\GO::getModel($model->getName())->extendsModel(), "Demo Custom fields");
                $category->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
                if (strpos(\GO::getModel($model->getName())->extendsModel(), 'Addressbook\\')) {
                    foreach ($types as $t) {
                        \GO\Customfields\Model\Field::model()->createIfNotExists($category->id, $t['type'], array('datatype' => $t['className'], 'helptext' => $t['className'] == "GO\\Customfields\\Customfieldtype\\Text" ? "Some help text for this field" : ""));
                    }
                } else {
                    \GO\Customfields\Model\Field::model()->createIfNotExists($category->id, "Custom", array('datatype' => "GO\\Customfields\\Customfieldtype\\Text", 'helptext' => "Some help text for this field"));
                }
            }
        }
        $addressbook = \GO\Addressbook\Model\Addressbook::model()->findSingleByAttribute('name', \GO::t('customers', 'addressbook'));
        if (!$addressbook) {
            $addressbook = new \GO\Addressbook\Model\Addressbook();
            $addressbook->setAttributes(array('user_id' => 1, 'name' => \GO::t('prospects', 'addressbook'), 'default_salutation' => \GO::t('defaultSalutation', 'addressbook')));
            $addressbook->save();
            $addressbook->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
        }
        $company = \GO\Addressbook\Model\Company::model()->findSingleByAttribute('email', '*****@*****.**');
        if (!$company) {
            $company = new \GO\Addressbook\Model\Company();
            $company->setAttributes(array('addressbook_id' => $addressbook->id, 'name' => 'Smith Inc', 'address' => 'Kalverstraat', 'address_no' => '1', 'zip' => '1012 NX', 'city' => 'Amsterdam', 'state' => 'Noord-Holland', 'country' => 'NL', 'post_address' => 'Kalverstraat', 'post_address_no' => '1', 'post_zip' => '1012 NX', 'post_city' => 'Amsterdam', 'post_state' => 'Noord-Brabant', 'post_country' => 'NL', 'phone' => '+31 (0) 10 - 1234567', 'fax' => '+31 (0) 1234567', 'email' => '*****@*****.**', 'homepage' => 'http://www.smith.demo', 'bank_no' => '', 'vat_no' => 'NL 1234.56.789.B01', 'user_id' => 1, 'comment' => 'Just a demo company'));
            $company->save();
        }
        $john = \GO\Addressbook\Model\Contact::model()->findSingleByAttribute('email', '*****@*****.**');
        if (!$john) {
            $john = new \GO\Addressbook\Model\Contact();
            $john->addressbook_id = $addressbook->id;
            $john->company_id = $company->id;
            $john->salutation = 'Dear Mr. Smith';
            $john->first_name = 'John';
            $john->last_name = 'Smith';
            $john->function = 'CEO';
            $john->cellular = '06-12345678';
            $john->email = '*****@*****.**';
            $john->address = 'Kalverstraat';
            $john->address_no = '1';
            $john->zip = '1012 NX';
            $john->city = 'Amsterdam';
            $john->state = 'Noord-Holland';
            $john->country = 'NL';
            $john->url_facebook = 'http://www.facebook.com';
            $john->url_linkedin = 'http://www.linkedin.com';
            $john->url_twitter = 'http://www.twitter.com';
            $john->skype_name = 'echo123';
            $john->save();
            $john->setPhoto(new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/noperson.jpg'));
            $john->save();
        }
        $acme = \GO\Addressbook\Model\Company::model()->findSingleByAttribute('email', '*****@*****.**');
        if (!$acme) {
            $acme = new \GO\Addressbook\Model\Company();
            $acme->setAttributes(array('addressbook_id' => $addressbook->id, 'name' => 'ACME Corporation', 'address' => '1111 Broadway', 'address_no' => '', 'zip' => '10019', 'city' => 'New York', 'state' => 'NY', 'country' => 'US', 'post_address' => '1111 Broadway', 'post_address_no' => '', 'post_zip' => '10019', 'post_city' => 'New York', 'post_state' => 'NY', 'post_country' => 'US', 'phone' => '(555) 123-4567', 'fax' => '(555) 123-4567', 'email' => '*****@*****.**', 'homepage' => 'http://www.acme.demo', 'bank_no' => '', 'vat_no' => 'US 1234.56.789.B01', 'user_id' => 1, 'comment' => 'The name Acme became popular for businesses by the 1920s, when alphabetized business telephone directories such as the Yellow Pages began to be widespread. There were a flood of businesses named Acme (some of these still survive[1]). For example, early Sears catalogues contained a number of products with the "Acme" trademark, including anvils, which are frequently used in Warner Bros. cartoons.[2]'));
            $acme->save();
            $acme->addComment("The company is never clearly defined in Road Runner cartoons but appears to be a conglomerate which produces every product type imaginable, no matter how elaborate or extravagant - none of which ever work as desired or expected. In the Road Runner cartoon Beep, Beep, it was referred to as \"Acme Rocket-Powered Products, Inc.\" based in Fairfield, New Jersey. Many of its products appear to be produced specifically for Wile E. Coyote; for example, the Acme Giant Rubber Band, subtitled \"(For Tripping Road Runners)\".");
            $acme->addComment("Sometimes, Acme can also send living creatures through the mail, though that isn't done very often. Two examples of this are the Acme Wild-Cat, which had been used on Elmer Fudd and Sam Sheepdog (which doesn't maul its intended victim); and Acme Bumblebees in one-fifth bottles (which sting Wile E. Coyote). The Wild Cat was used in the shorts Don't Give Up the Sheep and A Mutt in a Rut, while the bees were used in the short Zoom and Bored.");
        }
        $wile = \GO\Addressbook\Model\Contact::model()->findSingleByAttribute('email', '*****@*****.**');
        if (!$wile) {
            $wile = new \GO\Addressbook\Model\Contact();
            $wile->addressbook_id = $addressbook->id;
            $wile->company_id = $acme->id;
            $wile->salutation = 'Dear Mr. Coyote';
            $wile->first_name = 'Wile';
            $wile->middle_name = 'E.';
            $wile->last_name = 'Coyote';
            $wile->function = 'CEO';
            $wile->cellular = '06-12345678';
            $wile->email = '*****@*****.**';
            $wile->address = '1111 Broadway';
            $wile->address_no = '';
            $wile->zip = '10019';
            $wile->city = 'New York';
            $wile->state = 'NY';
            $wile->country = 'US';
            $wile->url_facebook = 'http://www.facebook.com';
            $wile->url_linkedin = 'http://www.linkedin.com';
            $wile->url_twitter = 'http://www.twitter.com';
            $wile->skype_name = 'test';
            $wile->save();
            $wile->setPhoto(new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/wecoyote.png'));
            $wile->save();
            $wile->addComment("Wile E. Coyote (also known simply as \"The Coyote\") and The Road Runner are a duo of cartoon characters from a series of Looney Tunes and Merrie Melodies cartoons. The characters (a coyote and Greater Roadrunner) were created by animation director Chuck Jones in 1948 for Warner Bros., while the template for their adventures was the work of writer Michael Maltese. The characters star in a long-running series of theatrical cartoon shorts (the first 16 of which were written by Maltese) and occasional made-for-television cartoons.");
            $wile->addComment("In each episode, instead of animal senses and cunning, Wile E. Coyote uses absurdly complex contraptions (sometimes in the manner of Rube Goldberg) and elaborate plans to pursue his quarry. It was originally meant to parody chase cartoons like Tom and Jerry, but became popular in its own right, much to Jones' chagrin.");
            $file = new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/Demo letter.docx');
            $copy = $file->copy($wile->filesFolder->fsFolder);
            $wile->filesFolder->addFile($copy->name());
        }
        $internalUserGroup = \GO\Base\Model\Group::model()->findByPk(\GO::config()->group_internal);
        \GO::config()->password_validate = false;
        $elmer = \GO\Base\Model\User::model()->findSingleByAttribute('username', 'elmer');
        if (!$elmer) {
            $elmer = new \GO\Base\Model\User();
            $elmer->username = '******';
            $elmer->first_name = 'Elmer';
            $elmer->last_name = 'Fudd';
            $elmer->email = '*****@*****.**';
            $elmer->password = '******';
            if ($elmer->save()) {
                //make sure he's member of the internal group.
                $internalUserGroup->addUser($elmer->id);
                $this->_setUserContact($elmer);
                $elmer->checkDefaultModels();
            } else {
                var_dump($elmer->getValidationErrors());
                exit;
            }
        }
        $demo = \GO\Base\Model\User::model()->findSingleByAttribute('username', 'demo');
        if (!$demo) {
            $demo = new \GO\Base\Model\User();
            $demo->username = '******';
            $demo->first_name = 'Demo';
            $demo->last_name = 'User';
            $demo->email = '*****@*****.**';
            $demo->password = '******';
            if ($demo->save()) {
                //make sure he's member of the internal group.
                $internalUserGroup->addUser($demo->id);
                $this->_setUserContact($demo);
                $demo->checkDefaultModels();
            } else {
                var_dump($demo->getValidationErrors());
                exit;
            }
        }
        $linda = \GO\Base\Model\User::model()->findSingleByAttribute('username', 'linda');
        if (!$linda) {
            $linda = new \GO\Base\Model\User();
            $linda->username = '******';
            $linda->first_name = 'Linda';
            $linda->last_name = 'Smith';
            $linda->email = '*****@*****.**';
            $linda->password = '******';
            if ($linda->save()) {
                //make sure she's member of the internal group.
                $internalUserGroup->addUser($linda->id);
                $this->_setUserContact($linda);
                $linda->checkDefaultModels();
            } else {
                var_dump($linda->getValidationErrors());
                exit;
            }
        }
        if (\GO::modules()->calendar) {
            //share calendars
            \GO\Calendar\Model\Calendar::model()->getDefault($demo)->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::READ_PERMISSION);
            \GO\Calendar\Model\Calendar::model()->getDefault($elmer)->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::READ_PERMISSION);
            \GO\Calendar\Model\Calendar::model()->getDefault($linda)->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::READ_PERMISSION);
            $events = array(array('Project meeting', 10), array('Meet Wile', 12), array('MT Meeting', 14));
            //start on tuesday.
            $time = \GO\Base\Util\Date::date_add(\GO\Base\Util\Date::get_last_sunday(time()), 2);
            foreach ($events as $e) {
                $event = new \GO\Calendar\Model\Event();
                $event->name = $e[0];
                $event->location = "ACME NY Office";
                $event->start_time = \GO\Base\Util\Date::clear_time($time, $e[1]);
                $event->end_time = $event->start_time + 3600;
                $event->user_id = $demo->id;
                $event->calendar_id = \GO\Calendar\Model\Calendar::model()->getDefault($demo)->id;
                $event->save();
                $participant = new \GO\Calendar\Model\Participant();
                $participant->is_organizer = true;
                $participant->setContact($demo->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($linda->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($elmer->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($wile);
                $event->addParticipant($participant);
                $wile->link($event);
            }
            $events = array(array('Project meeting', 11), array('Meet John', 13), array('MT Meeting', 16));
            foreach ($events as $e) {
                $event = new \GO\Calendar\Model\Event();
                $event->name = $e[0];
                $event->location = "ACME NY Office";
                $event->start_time = \GO\Base\Util\Date::date_add(\GO\Base\Util\Date::clear_time($time, $e[1]), 1);
                $event->end_time = $event->start_time + 3600;
                $event->user_id = $linda->id;
                $event->calendar_id = \GO\Calendar\Model\Calendar::model()->getDefault($linda)->id;
                $event->save();
                $participant = new \GO\Calendar\Model\Participant();
                $participant->is_organizer = true;
                $participant->setContact($linda->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($demo->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($john);
                $event->addParticipant($participant);
                $john->link($event);
            }
            $events = array(array('Rocket testing', 8), array('Blast impact test', 15), array('Test range extender', 19));
            foreach ($events as $e) {
                $event = new \GO\Calendar\Model\Event();
                $event->name = $e[0];
                $event->location = "ACME Testing fields";
                $event->start_time = \GO\Base\Util\Date::date_add(\GO\Base\Util\Date::clear_time(time(), $e[1]), 1);
                $event->end_time = $event->start_time + 3600;
                $event->user_id = $linda->id;
                $event->calendar_id = \GO\Calendar\Model\Calendar::model()->getDefault($linda)->id;
                $event->save();
                $participant = new \GO\Calendar\Model\Participant();
                $participant->is_organizer = true;
                $participant->setContact($linda->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($demo->createContact());
                $event->addParticipant($participant);
                $participant = new \GO\Calendar\Model\Participant();
                $participant->setContact($john);
                $event->addParticipant($participant);
                $john->link($event);
            }
            $view = new \GO\Calendar\Model\View();
            $view->name = \GO::t('group_everyone');
            if ($view->save()) {
                $view->addManyMany('groups', \GO::config()->group_everyone);
                //share view
                $view->acl->addGroup(\GO::config()->group_internal);
            }
            $view = new \GO\Calendar\Model\View();
            $view->name = \GO::t('group_everyone') . ' (' . \GO::t('merge', 'calendar') . ')';
            $view->merge = true;
            $view->owncolor = true;
            if ($view->save()) {
                $view->addManyMany('groups', \GO::config()->group_everyone);
                //share view
                $view->acl->addGroup(\GO::config()->group_internal);
            }
            //resource groups
            $resourceGroup = \GO\Calendar\Model\Group::model()->findSingleByAttribute('name', "Meeting rooms");
            if (!$resourceGroup) {
                $resourceGroup = new \GO\Calendar\Model\Group();
                $resourceGroup->name = "Meeting rooms";
                $resourceGroup->save();
                //$resourceGroup->acl->addGroup(\GO::config()->group_internal);
            }
            $resourceCalendar = \GO\Calendar\Model\Calendar::model()->findSingleByAttribute('name', 'Road Runner Room');
            if (!$resourceCalendar) {
                $resourceCalendar = new \GO\Calendar\Model\Calendar();
                $resourceCalendar->group_id = $resourceGroup->id;
                $resourceCalendar->name = 'Road Runner Room';
                $resourceCalendar->save();
                $resourceCalendar->acl->addGroup(\GO::config()->group_internal);
            }
            $resourceCalendar = \GO\Calendar\Model\Calendar::model()->findSingleByAttribute('name', 'Don Coyote Room');
            if (!$resourceCalendar) {
                $resourceCalendar = new \GO\Calendar\Model\Calendar();
                $resourceCalendar->group_id = $resourceGroup->id;
                $resourceCalendar->name = 'Don Coyote Room';
                $resourceCalendar->save();
                $resourceCalendar->acl->addGroup(\GO::config()->group_internal);
            }
            //setup elmer as a resource admin
            $resourceGroup->addManyMany('admins', $elmer->id);
        }
        if (\GO::modules()->tasks) {
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($demo)->id;
            $task->name = 'Feed the dog';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 2);
            $task->save();
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($linda)->id;
            $task->name = 'Feed the dog';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 1);
            $task->save();
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($elmer)->id;
            $task->name = 'Feed the dog';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 1);
            $task->save();
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($demo)->id;
            $task->name = 'Prepare meeting';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 1);
            $task->save();
            $task->link($wile);
            $task->link($event);
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($linda)->id;
            $task->name = 'Prepare meeting';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 1);
            $task->save();
            $task->link($wile);
            $task->link($event);
            $task = new \GO\Tasks\Model\Task();
            $task->tasklist_id = \GO\Tasks\Model\Tasklist::model()->getDefault($elmer)->id;
            $task->name = 'Prepare meeting';
            $task->start_time = time();
            $task->due_time = \GO\Base\Util\Date::date_add(time(), 1);
            $task->save();
            $task->link($wile);
            $task->link($event);
        }
        if (\GO::modules()->billing) {
            $rocket = \GO\Billing\Model\Product::model()->findSingleByAttribute('article_id', '12345');
            if (!$rocket) {
                $rocket = new \GO\Billing\Model\Product();
                $rocket->article_id = 12345;
                $rocket->supplier_company_id = $acme->id;
                $rocket->unit = 'pcs';
                $rocket->cost_price = 1000;
                $rocket->list_price = 2999.99;
                $rocket->total_price = 2999.99;
                $rocket->vat = 0;
                if (!$rocket->save()) {
                    var_dump($rocket->getValidationErrors());
                }
                $lang = new \GO\Billing\Model\ProductLanguage();
                $lang->language_id = 1;
                $lang->product_id = $rocket->id;
                $lang->name = 'Master Rocket 1000';
                $lang->description = 'Master Rocket 1000. The ultimate rocket to blast rocky mountains.';
                $lang->save();
            }
            $rocketLauncher = \GO\Billing\Model\Product::model()->findSingleByAttribute('article_id', '234567');
            if (!$rocketLauncher) {
                $rocketLauncher = new \GO\Billing\Model\Product();
                $rocketLauncher->article_id = 234567;
                $rocketLauncher->supplier_company_id = $acme->id;
                $rocketLauncher->unit = 'pcs';
                $rocketLauncher->cost_price = 3000;
                $rocketLauncher->list_price = 8999.99;
                $rocketLauncher->total_price = 8999.99;
                $rocketLauncher->vat = 0;
                if (!$rocketLauncher->save()) {
                    var_dump($rocket->getValidationErrors());
                }
                $lang = new \GO\Billing\Model\ProductLanguage();
                $lang->language_id = 1;
                $lang->product_id = $rocketLauncher->id;
                $lang->name = 'Rocket Launcher 1000';
                $lang->description = 'Rocket Launcher 1000. Required to launch rockets.';
                $lang->save();
            }
            $books = \GO\Billing\Model\Book::model()->find();
            foreach ($books as $book) {
                //give demo access
                $book->acl->addUser($demo->id, \GO\Base\Model\Acl::WRITE_PERMISSION);
                $book->acl->addUser($elmer->id, \GO\Base\Model\Acl::WRITE_PERMISSION);
                $order = new \GO\Billing\Model\Order();
                $order->book_id = $book->id;
                $order->btime = time();
                $order->setCustomerFromContact($john);
                $order->setCustomerFromCompany($company);
                $order->save();
                $order->addProduct($rocketLauncher, 1);
                $order->addProduct($rocket, 4);
                $status = $book->statuses(\GO\Base\Db\FindParams::newInstance()->single());
                $order->status_id = $status->id;
                $order->syncItems();
                $order = new \GO\Billing\Model\Order();
                $order->book_id = $book->id;
                $order->btime = time();
                $order->setCustomerFromContact($wile);
                $order->setCustomerFromCompany($acme);
                $order->save();
                $order->addProduct($rocketLauncher, 1);
                $order->addProduct($rocket, 10);
                $status = $book->statuses(\GO\Base\Db\FindParams::newInstance()->single());
                $order->status_id = $status->id;
                $order->syncItems();
            }
        }
        if (\GO::modules()->tickets) {
            $ticket = new \GO\Tickets\Model\Ticket();
            $ticket->subject = 'Malfunctioning rockets';
            $ticket->setFromContact($wile);
            if (!$ticket->save()) {
                var_dump($ticket->getValidationErrors());
                exit;
            }
            $message = new \GO\Tickets\Model\Message();
            $message->sendEmail = false;
            $message->content = "My rocket always circles back right at me? How do I aim right?";
            $message->is_note = false;
            $message->user_id = 0;
            $ticket->addMessage($message);
            //elmer picks up the ticket
            $ticket->agent_id = $elmer->id;
            $ticket->save();
            //make elmer and demo a ticket agent
            $ticket->type->acl->addUser($elmer->id, \GO\Base\Model\Acl::MANAGE_PERMISSION);
            $ticket->type->acl->addUser($demo->id, \GO\Base\Model\Acl::MANAGE_PERMISSION);
            $message = new \GO\Tickets\Model\Message();
            $message->sendEmail = false;
            $message->content = "Haha, good thing he doesn't know Accelleratii Incredibus designed this rocket and he can't read this note.";
            $message->is_note = true;
            $message->user_id = $elmer->id;
            $ticket->addMessage($message);
            $message = new \GO\Tickets\Model\Message();
            $message->sendEmail = false;
            $message->content = "Gee I don't know how that can happen. I'll send you some new ones!";
            $message->is_note = false;
            $message->status_id = \GO\Tickets\Model\Ticket::STATUS_CLOSED;
            $message->has_status = true;
            $message->user_id = $elmer->id;
            $ticket->addMessage($message);
            $ticket = new \GO\Tickets\Model\Ticket();
            $ticket->subject = 'Can I speed up my rockets?';
            $ticket->setFromContact($wile);
            $ticket->ctime = $ticket->mtime = \GO\Base\Util\Date::date_add(time(), -2);
            if (!$ticket->save()) {
                var_dump($ticket->getValidationErrors());
                exit;
            }
            $message = new \GO\Tickets\Model\Message();
            $message->sendEmail = false;
            $message->content = "The rockets are too slow to hit my fast moving target. Is there a way to speed them up?";
            $message->is_note = false;
            $message->user_id = 0;
            $message->ctime = $message->mtime = \GO\Base\Util\Date::date_add(time(), -2);
            $ticket->addMessage($message);
            //elmer picks up the ticket
            //			$ticket->agent_id=$elmer->id;
            //			$ticket->save();
            $message = new \GO\Tickets\Model\Message();
            $message->sendEmail = false;
            $message->content = "Please respond faster. Can't you see this ticket is marked in red?";
            $message->is_note = false;
            $message->user_id = 0;
            $ticket->addMessage($message);
            if (!\GO::modules()->isInstalled('site') && \GO::modules()->isAvailable('site')) {
                $module = new \GO\Base\Model\Module();
                $module->id = 'site';
                $module->save();
            }
            if (!\GO::modules()->isInstalled('defaultsite') && \GO::modules()->isAvailable('defaultsite')) {
                $module = new \GO\Base\Model\Module();
                $module->id = 'defaultsite';
                $module->save();
            }
            $settings = \GO\Tickets\Model\Settings::model()->findModel();
            $settings->enable_external_page = true;
            $settings->use_alternative_url = true;
            $settings->allow_anonymous = true;
            $settings->alternative_url = \GO::config()->full_url . 'modules/site/index.php?r=tickets/externalpage/ticket';
            $settings->save();
            if (\GO::modules()->summary) {
                $title = "Submit support ticket";
                $announcement = \GO\Summary\Model\Announcement::model()->findSingleByAttribute('title', $title);
                if (!$announcement) {
                    $newTicketUrl = \GO::config()->full_url . 'modules/site/index.php?r=tickets/externalpage/newTicket';
                    $announcement = new \GO\Summary\Model\Announcement();
                    $announcement->title = $title;
                    $announcement->content = 'Anyone can submit tickets to the support system here:' . '<br /><br /><a href="' . $newTicketUrl . '">' . $newTicketUrl . '</a><br /><br />Anonymous ticket posting can be disabled in the ticket module settings.';
                    if ($announcement->save()) {
                        $announcement->acl->addGroup(\GO::config()->group_everyone);
                    }
                }
            }
        }
        if (\GO::modules()->notes) {
            $category = \GO\Notes\Model\Category::model()->findSingleByAttribute('name', \GO::t('general', 'notes'));
            if (!$category) {
                $category = new \GO\Notes\Model\Category();
                $category->name = \GO::t('general', 'notes');
                $category->save();
                $category->acl->addGroup(\GO::config()->group_everyone, \GO\Base\Model\Acl::READ_PERMISSION);
            }
            $note = new \GO\Notes\Model\Note();
            $note->user_id = $elmer->id;
            //$category = \GO\Notes\Model\Category::model()->getDefault($elmer);
            $note->category_id = $category->id;
            $note->name = "Laws and rules";
            $note->content = 'As in other cartoons, the Road Runner and the coyote follow the laws of cartoon physics. For example, the Road Runner has the ability to enter the painted image of a cave, while the coyote cannot (unless there is an opening through which he can fall). Sometimes, however, this is reversed, and the Road Runner can burst through a painting of a broken bridge and continue on his way, while the Coyote will instead enter the mirage painting and fall down the precipice of the cliff where the bridge is out. Sometimes the coyote is allowed to hang in midair until he realizes that he is about to plummet into a chasm (a process occasionally referred to elsewhere as Road-Runnering or Wile E. Coyote moment). The coyote can overtake rocks (or cannons) which fall earlier than he does, and end up being squashed by them. If a chase sequence happens upon a cliff, the Road Runner is not affected by gravity, whereas the Coyote will realize his error eventually and fall to the ground below. A chase sequence that happens upon railroad tracks will always result in the Coyote being run over by a train. If the Coyote uses an explosive (for instance, dynamite) that is triggered by a mechanism that is supposed to force the explosive in a forward motion toward its target, the actual mechanism itself will always shoot forward, leaving the explosive behind to detonate in the Coyote\'s face. Similarly, a complex apparatus that is supposed to propel an object like a boulder or steel ball forward, or trigger a trap, will not work on the Road Runner, but always will on the Coyote. For instance, the Road Runner can jump up and down on the trigger of a large animal trap and eat bird seed off from it, going completely unharmed and not setting off the trap; when the Coyote places the tiniest droplet of oil on the trigger, the trap snaps shut on him without fail. At certain times, the Coyote may don an exquisite Acme costume or propulsion device that briefly allows him to catch up to the Road Runner. This will always result in him losing track of his proximity to large cliffs or walls, and the Road Runner will dart around an extremely sharp turn on a cliff, but the Coyote will rocket right over the edge and fall to the ground.

In his book Chuck Amuck: The Life and Times Of An Animated Cartoonist,[13] Chuck Jones claimed that he and the artists behind the Road Runner and Wile E. cartoons adhered to some simple but strict rules:

The Road Runner cannot harm the Coyote except by going "beep, beep."
No outside force can harm the Coyote — only his own ineptitude or the failure of Acme products. Trains and trucks were the exception from time to time.
The Coyote could stop anytime — if he were not a fanatic. (Repeat: "A fanatic is one who redoubles his effort when he has forgotten his aim." — George Santayana).
Dialogue must never be used, except "beep, beep" and yowling in pain. (This rule, however, was violated in some cartoons.)
The Road Runner must stay on the road — for no other reason than that he\'s a roadrunner. This rule was broken in Beep, Beep, in a sequence where Wile E. chased the Road Runner into a cactus mine. And also in Fastest with the Mostestwhen Coyote lures Road Runner to the edge of a cliff.
All action must be confined to the natural environment of the two characters — the southwest American desert.
All (or at least almost all) tools, weapons, or mechanical conveniences must be obtained from the Acme Corporation. There were sometimes exceptions when the Coyote obtained other items from the desert such as boulders to use in his attempts.
Whenever possible, make gravity the Coyote\'s greatest enemy (e.g., falling off a cliff).
The Coyote is always more humiliated than harmed by his failures.
The audience\'s sympathy must remain with the Coyote.
The Coyote is not allowed to catch or eat the Road Runner, unless he escapes from the grasp. (The robot that the Coyote created in The Solid Tin Coyote caught the Road Runner so this does not break this rule. The Coyote does catch the Road Runner in Soup or Sonic but is too small to eat him. There is also two CGI shorts on The Looney Tunes Show were he caught the bird, but was not able to eat him because the Road Runner got away in both shorts.)';
            $note->save();
            $note->link($john);
            $note = new \GO\Notes\Model\Note();
            $note->user_id = $demo->id;
            $note->category_id = $category->id;
            $note->name = "Wile E. Coyote and Bugs Bunny";
            $note->content = 'Wile E. Coyote has also unsuccessfully attempted to catch and eat Bugs Bunny in another series of cartoons. In these cartoons, the coyote takes on the guise of a self-described "super genius" and speaks with a smooth, generic upper-class accent provided by Mel Blanc. While he is incredibly intelligent, he is limited by technology and his own short-sighted arrogance, and is thus often easily outsmarted, a somewhat physical symbolism of "street smarts" besting "book smarts".

In one short (Hare-Breadth Hurry, 1963), Bugs Bunny — with the help of "speed pills" — even stands in for Road Runner, who has "sprained a giblet", and carries out the duties of outsmarting the hungry scavenger. That is the only Bugs Bunny/Wile E. Coyote short in which the coyote does not speak. As usual Wile E. Coyote ends up falling down a canyon. In a later, made-for-TV short, which had a young Elmer Fudd chasing a young Bugs Bunny, Elmer also falls down a canyon. On the way down he is overtaken by Wile E. Coyote who shows a sign telling Elmer to get out of the way for someone who is more experienced in falling.';
            $note->save();
            $note->link($wile);
        }
        if (\GO::modules()->summary) {
            $title = "Welcome to " . \GO::config()->product_name;
            $announcement = \GO\Summary\Model\Announcement::model()->findSingleByAttribute('title', $title);
            if (!$announcement) {
                $announcement = new \GO\Summary\Model\Announcement();
                $announcement->title = $title;
                $announcement->content = 'This is a demo announcements that administrators can set.<br />Have a look around.<br /><br />We hope you\'ll enjoy Group-Office as much as we do!';
                if ($announcement->save()) {
                    $announcement->acl->addGroup(\GO::config()->group_everyone);
                }
            }
        }
        if (\GO::modules()->files) {
            $demoHome = \GO\Files\Model\Folder::model()->findHomeFolder($demo);
            $file = new \GO\Base\Fs\File(\GO::modules()->files->path . 'install/templates/empty.docx');
            $copy = $file->copy($demoHome->fsFolder);
            $file = new \GO\Base\Fs\File(\GO::modules()->files->path . 'install/templates/empty.odt');
            $copy = $file->copy($demoHome->fsFolder);
            $file = new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/Demo letter.docx');
            $copy = $file->copy($demoHome->fsFolder);
            $file = new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/wecoyote.png');
            $copy = $file->copy($demoHome->fsFolder);
            $file = new \GO\Base\Fs\File(\GO::modules()->addressbook->path . 'install/noperson.jpg');
            $copy = $file->copy($demoHome->fsFolder);
            //add files to db.
            $demoHome->syncFilesystem();
        }
        if (\GO::modules()->projects) {
            $templates = \GO\Projects\Model\Template::model()->find();
            $folderTemplate = $templates->fetch();
            $projectTemplate = $templates->fetch();
            $status = \GO\Projects\Model\Status::model()->findSingle();
            $type = \GO\Projects\Model\Type::model()->findSingleByAttribute('name', 'Demo');
            if (!$type) {
                $type = new \GO\Projects\Model\Type();
                $type->name = 'Demo';
                if (!$type->save()) {
                    var_dump($type->getValidationErrors());
                    exit;
                }
                $type->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
            }
            $folderProject = \GO\Projects\Model\Project::model()->findSingleByAttribute('name', 'Demo');
            if (!$folderProject) {
                $folderProject = new \GO\Projects\Model\Project();
                $folderProject->name = 'Demo';
                $folderProject->description = 'Just a placeholder for sub projects.';
                $folderProject->template_id = $folderTemplate->id;
                $folderProject->type_id = $type->id;
                $folderProject->status_id = $status->id;
                if (!$folderProject->save()) {
                    var_dump($folderProject->getValidationErrors());
                    exit;
                }
            }
            $rocketProject = \GO\Projects\Model\Project::model()->findSingleByAttribute('name', '[001] Develop Rocket 2000');
            if (!$rocketProject) {
                $rocketProject = new \GO\Projects\Model\Project();
                $rocketProject->type_id = $type->id;
                $rocketProject->status_id = $status->id;
                $rocketProject->name = '[001] Develop Rocket 2000';
                $rocketProject->description = 'Better range and accuracy';
                $rocketProject->template_id = $projectTemplate->id;
                $rocketProject->parent_project_id = $folderProject->id;
                $rocketProject->start_time = time();
                $rocketProject->due_time = \GO\Base\Util\Date::date_add(time(), 0, 1);
                $rocketProject->company_id = $acme->id;
                $rocketProject->contact_id = $wile->id;
                $rocketProject->save();
            }
            $launcherProject = \GO\Projects\Model\Project::model()->findSingleByAttribute('name', '[001] Develop Rocket Launcher');
            if (!$launcherProject) {
                $launcherProject = new \GO\Projects\Model\Project();
                $launcherProject->type_id = $type->id;
                $launcherProject->status_id = $status->id;
                $launcherProject->name = '[001] Develop Rocket Launcher';
                $launcherProject->description = 'Better range and accuracy';
                $launcherProject->template_id = $projectTemplate->id;
                $launcherProject->parent_project_id = $folderProject->id;
                $launcherProject->start_time = time();
                $launcherProject->due_time = \GO\Base\Util\Date::date_add(time(), 0, 1);
                $launcherProject->company_id = $acme->id;
                $launcherProject->contact_id = $wile->id;
                $launcherProject->save();
            }
        }
        if (\GO::modules()->projects2) {
            if (!\GO\Projects2\Model\Employee::model()->count()) {
                $employee = new \GO\Projects2\Model\Employee();
                $employee->user_id = $elmer->id;
                $employee->external_fee = 120;
                $employee->internal_fee = 60;
                $employee->save();
                $employee = new \GO\Projects2\Model\Employee();
                $employee->user_id = $demo->id;
                $employee->external_fee = 80;
                $employee->internal_fee = 40;
                $employee->save();
                $employee = new \GO\Projects2\Model\Employee();
                $employee->user_id = $linda->id;
                $employee->external_fee = 90;
                $employee->internal_fee = 45;
                $employee->save();
            } else {
                $employee = \GO\Projects2\Model\Employee::model()->findSingle();
            }
            $templates = \GO\Projects2\Model\Template::model()->find();
            $folderTemplate = $templates->fetch();
            $projectTemplate = $templates->fetch();
            $status = \GO\Projects2\Model\Status::model()->findSingle();
            $type = \GO\Projects2\Model\Type::model()->findSingleByAttribute('name', 'Demo');
            if (!$type) {
                $type = new \GO\Projects2\Model\Type();
                $type->name = 'Demo';
                if (!$type->save()) {
                    var_dump($type->getValidationErrors());
                    exit;
                }
                $type->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
            }
            $folderProject = \GO\Projects2\Model\Project::model()->findSingleByAttribute('name', 'Demo');
            if (!$folderProject) {
                $folderProject = new \GO\Projects2\Model\Project();
                $folderProject->name = 'Demo';
                $folderProject->start_time = time();
                $folderProject->description = 'Just a placeholder for sub projects.';
                $folderProject->template_id = $folderTemplate->id;
                $folderProject->type_id = $type->id;
                $folderProject->status_id = $status->id;
                if (!$folderProject->save()) {
                    var_dump($folderProject->getValidationErrors());
                    exit;
                }
            }
            $rocketProject = \GO\Projects2\Model\Project::model()->findSingleByAttribute('name', '[001] Develop Rocket 2000');
            if (!$rocketProject) {
                $rocketProject = new \GO\Projects2\Model\Project();
                $rocketProject->type_id = $type->id;
                $rocketProject->status_id = $status->id;
                $rocketProject->name = '[001] Develop Rocket 2000';
                $rocketProject->description = 'Better range and accuracy';
                $rocketProject->template_id = $projectTemplate->id;
                $rocketProject->parent_project_id = $folderProject->id;
                $rocketProject->start_time = time();
                $rocketProject->due_time = \GO\Base\Util\Date::date_add(time(), 0, 1);
                $rocketProject->company_id = $acme->id;
                $rocketProject->contact_id = $wile->id;
                //				$rocketProject->budget=20000;
                $rocketProject->save();
                $resource = new \GO\Projects2\Model\Resource();
                $resource->project_id = $rocketProject->id;
                $resource->user_id = $demo->id;
                $resource->budgeted_units = 100;
                $resource->external_fee = 80;
                $resource->internal_fee = 40;
                $resource->save();
                $resource = new \GO\Projects2\Model\Resource();
                $resource->project_id = $rocketProject->id;
                $resource->user_id = $elmer->id;
                $resource->budgeted_units = 16;
                $resource->external_fee = 120;
                $resource->internal_fee = 60;
                $resource->save();
                $resource = new \GO\Projects2\Model\Resource();
                $resource->project_id = $rocketProject->id;
                $resource->user_id = $linda->id;
                $resource->budgeted_units = 16;
                $resource->external_fee = 90;
                $resource->internal_fee = 45;
                $resource->save();
                $groupTask = new \GO\Projects2\Model\Task();
                $groupTask->project_id = $rocketProject->id;
                $groupTask->description = 'Design';
                $groupTask->duration = 8 * 60;
                $groupTask->user_id = $demo->id;
                $groupTask->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Functional design';
                $task->percentage_complete = 100;
                $task->duration = 8 * 60;
                $task->user_id = $demo->id;
                $task->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Technical design';
                $task->percentage_complete = 50;
                $task->duration = 8 * 60;
                $task->user_id = $demo->id;
                $task->save();
                $groupTask = new \GO\Projects2\Model\Task();
                $groupTask->project_id = $rocketProject->id;
                $groupTask->description = 'Implementation';
                $groupTask->duration = 8 * 60;
                $groupTask->user_id = $demo->id;
                $groupTask->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Models';
                $task->duration = 4 * 60;
                $task->user_id = $demo->id;
                $task->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Controllers';
                $task->duration = 2 * 60;
                $task->user_id = $demo->id;
                $task->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Views';
                $task->duration = 6 * 60;
                $task->user_id = $demo->id;
                $task->save();
                $groupTask = new \GO\Projects2\Model\Task();
                $groupTask->project_id = $rocketProject->id;
                $groupTask->description = 'Testing';
                $groupTask->duration = 8 * 60;
                $groupTask->user_id = $demo->id;
                $groupTask->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'GUI';
                $task->duration = 8 * 60;
                $task->user_id = $elmer->id;
                $task->save();
                $task = new \GO\Projects2\Model\Task();
                $task->parent_id = $groupTask->id;
                $task->project_id = $rocketProject->id;
                $task->description = 'Security';
                $task->duration = 8 * 60;
                $task->user_id = $elmer->id;
                $task->save();
                $expenseBudget = new \GO\Projects2\Model\ExpenseBudget();
                $expenseBudget->description = 'Machinery';
                $expenseBudget->nett = 10000;
                $expenseBudget->project_id = $rocketProject->id;
                $expenseBudget->save();
                $expense = new \GO\Projects2\Model\Expense();
                $expense->description = 'Rocket fuel';
                $expense->project_id = $rocketProject->id;
                $expense->nett = 3000;
                $expense->save();
                $expense = new \GO\Projects2\Model\Expense();
                $expense->expense_budget_id = $expenseBudget->id;
                $expense->description = 'Fuse machine';
                $expense->project_id = $rocketProject->id;
                $expense->nett = 2000;
                $expense->save();
            }
            $launcherProject = \GO\Projects2\Model\Project::model()->findSingleByAttribute('name', '[001] Develop Rocket Launcher');
            if (!$launcherProject) {
                $launcherProject = new \GO\Projects2\Model\Project();
                $launcherProject->type_id = $type->id;
                $launcherProject->status_id = $status->id;
                $launcherProject->name = '[001] Develop Rocket Launcher';
                $launcherProject->description = 'Better range and accuracy';
                $launcherProject->template_id = $projectTemplate->id;
                $launcherProject->parent_project_id = $folderProject->id;
                $launcherProject->start_time = time();
                $launcherProject->due_time = \GO\Base\Util\Date::date_add(time(), 0, 1);
                $launcherProject->company_id = $acme->id;
                $launcherProject->contact_id = $wile->id;
                $launcherProject->save();
                $resource = new \GO\Projects2\Model\Resource();
                $resource->project_id = $launcherProject->id;
                $resource->user_id = $demo->id;
                $resource->external_fee = 80;
                $resource->internal_fee = 40;
                $resource->budgeted_units = 16;
                $resource->save();
            }
        }
        if (\GO::modules()->bookmarks) {
            $category = \GO\Bookmarks\Model\Category::model()->findSingleByAttribute('name', \GO::t('general', 'bookmarks'));
            if (!$category) {
                $category = new \GO\Bookmarks\Model\Category();
                $category->name = \GO::t('general', 'bookmarks');
                $category->save();
                $category->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::READ_PERMISSION);
            }
            $bookmark = \GO\Bookmarks\Model\Bookmark::model()->findSingleByAttribute('name', 'Google Search');
            if (!$bookmark) {
                $bookmark = new \GO\Bookmarks\Model\Bookmark();
                $bookmark->category_id = $category->id;
                $bookmark->name = 'Google Search';
                $bookmark->content = 'http://www.google.com';
                $bookmark->logo = 'icons/viewmag.png';
                $bookmark->public_icon = true;
                $bookmark->description = 'Search the web';
                $bookmark->open_extern = true;
                $bookmark->save();
            }
            $bookmark = \GO\Bookmarks\Model\Bookmark::model()->findSingleByAttribute('name', 'Wikipedia');
            if (!$bookmark) {
                $bookmark = new \GO\Bookmarks\Model\Bookmark();
                $bookmark->category_id = $category->id;
                $bookmark->name = 'Wikipedia';
                $bookmark->content = 'http://www.wikipedia.com';
                $bookmark->logo = 'icons/agt_web.png';
                $bookmark->public_icon = true;
                $bookmark->description = 'The Free Encyclopedia';
                $bookmark->behave_as_module = true;
                $bookmark->save();
            }
        }
        if (\GO::modules()->postfixadmin) {
            $domainModel = \GO\Postfixadmin\Model\Domain::model()->findSingleByAttribute('domain', 'acmerpp.demo');
            if (!$domainModel) {
                $domainModel = new \GO\Postfixadmin\Model\Domain();
                $domainModel->domain = 'acmerpp.demo';
                $domainModel->save();
            }
            $this->_createMailbox($domainModel, $demo);
            $this->_createMailbox($domainModel, $elmer);
            $this->_createMailbox($domainModel, $linda);
        }
        if (\GO::modules()->savemailas) {
            //link some demo mails
            $mimeFile = new \GO\Base\Fs\File(\GO::modules()->savemailas->path . 'install/demo.eml');
            \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $wile);
            \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $john);
            if (\GO::modules()->projects) {
                \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $rocketProject);
                \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $launcherProject);
            }
            $mimeFile = new \GO\Base\Fs\File(\GO::modules()->savemailas->path . 'install/demo2.eml');
            \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $wile);
            \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $john);
            if (\GO::modules()->projects) {
                \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $rocketProject);
                \GO\Savemailas\Model\LinkedEmail::model()->createFromMimeFile($mimeFile, $launcherProject);
            }
        }
        //useful for other modules to create stuff
        $this->fireEvent('demodata', array('users' => array('demo' => $demo, 'linda' => $linda, 'elmer' => $elmer)));
        if (\GO::modules()->demodata) {
            \GO::modules()->demodata->delete();
        }
        if (!$this->isCli()) {
            //login as demo
            \GO::session()->restart();
            \GO::session()->setCurrentUser($demo->id);
            $this->redirect();
        }
    }
Ejemplo n.º 21
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;
 }
Ejemplo n.º 22
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"}');
 }
Ejemplo n.º 23
0
 private function _getParts($structure, $part_number_prefix = '')
 {
     if (isset($structure->parts)) {
         $structure->ctype_primary = strtolower($structure->ctype_primary);
         $structure->ctype_secondary = strtolower($structure->ctype_secondary);
         //$part_number=0;
         foreach ($structure->parts as $part_number => $part) {
             $part->ctype_primary = strtolower($part->ctype_primary);
             $part->ctype_secondary = strtolower($part->ctype_secondary);
             //text part and no attachment so it must be the body
             if ($structure->ctype_primary == 'multipart' && $structure->ctype_secondary == 'alternative' && $part->ctype_primary == 'text' && $part->ctype_secondary == 'plain') {
                 //check if html part is there
                 if ($this->_hasHtmlPart($structure)) {
                     continue;
                 }
             }
             if ($part->ctype_primary == 'text' && ($part->ctype_secondary == 'plain' || $part->ctype_secondary == 'html') && (!isset($part->disposition) || $part->disposition != 'attachment') && empty($part->d_parameters['filename'])) {
                 $charset = isset($part->ctype_parameters['charset']) ? $part->ctype_parameters['charset'] : 'UTF-8';
                 $body = \GO\Base\Util\String::clean_utf8($part->body, $charset);
                 if (stripos($part->ctype_secondary, 'plain') !== false) {
                     $body = nl2br($body);
                 } else {
                     $body = \GO\Base\Util\String::convertLinks($body);
                     $body = \GO\Base\Util\String::sanitizeHtml($body);
                     $body = $body;
                 }
                 $this->_loadedBody .= $body;
             } elseif ($part->ctype_primary == 'multipart') {
             } else {
                 //attachment
                 if (!empty($part->ctype_parameters['name'])) {
                     $filename = $part->ctype_parameters['name'];
                 } elseif (!empty($part->d_parameters['filename'])) {
                     $filename = $part->d_parameters['filename'];
                 } elseif (!empty($part->d_parameters['filename*'])) {
                     $filename = $part->d_parameters['filename*'];
                 } else {
                     $filename = uniqid(time());
                 }
                 $mime_type = $part->ctype_primary . '/' . $part->ctype_secondary;
                 if (isset($part->headers['content-id'])) {
                     $content_id = trim($part->headers['content-id']);
                     if (strpos($content_id, '>')) {
                         $content_id = substr($part->headers['content-id'], 1, strlen($part->headers['content-id']) - 2);
                     }
                 } else {
                     $content_id = '';
                 }
                 $f = new \GO\Base\Fs\File($filename);
                 $a = new MessageAttachment();
                 $a->name = $filename;
                 $a->number = $part_number_prefix . $part_number;
                 $a->content_id = $content_id;
                 $a->mime = $mime_type;
                 $tmp_file = new \GO\Base\Fs\File($this->_getTempDir() . $filename);
                 if (!empty($part->body)) {
                     $tmp_file = new \GO\Base\Fs\File($this->_getTempDir() . $filename);
                     if (!$tmp_file->exists()) {
                         $tmp_file->putContents($part->body);
                     }
                     $a->setTempFile($tmp_file);
                 }
                 $a->index = count($this->attachments);
                 $a->size = isset($part->body) ? strlen($part->body) : 0;
                 $a->encoding = isset($part->headers['content-transfer-encoding']) ? $part->headers['content-transfer-encoding'] : '';
                 $a->disposition = isset($part->disposition) ? $part->disposition : '';
                 $this->addAttachment($a);
             }
             //$part_number++;
             if (isset($part->parts)) {
                 $this->_getParts($part, $part_number_prefix . $part_number . '.');
             }
         }
     } elseif (isset($structure->body)) {
         $charset = isset($structure->ctype_parameters['charset']) ? $structure->ctype_parameters['charset'] : 'UTF-8';
         $text_part = \GO\Base\Util\String::clean_utf8($structure->body, $charset);
         //convert text to html
         if (stripos($structure->ctype_secondary, 'plain') !== false) {
             $this->extractUuencodedAttachments($text_part);
             $text_part = nl2br($text_part);
         } else {
             $text_part = \GO\Base\Util\String::convertLinks($text_part);
             $text_part = \GO\Base\Util\String::sanitizeHtml($text_part);
         }
         $this->_loadedBody .= $text_part;
     }
 }
Ejemplo n.º 24
0
 protected function afterSave($wasNew)
 {
     if ($wasNew && $this->group) {
         $stmt = $this->group->admins;
         foreach ($stmt as $user) {
             if ($user->user_id != $this->user_id) {
                 //the owner has already been added automatically with manage permission
                 $this->acl->addUser($user->user_id, \GO\Base\Model\Acl::DELETE_PERMISSION);
             }
         }
     }
     $file = new \GO\Base\Fs\File($this->getPublicIcsPath());
     if (!$this->public) {
         if ($file->exists()) {
             $file->delete();
         }
     } else {
         if (!$file->exists()) {
             $file->touch(true);
         }
         $file->putContents($this->toVObject());
     }
     return parent::afterSave($wasNew);
 }
Ejemplo n.º 25
0
 /**
  * Check if a file is encoded and if so check if it can be decrypted with
  * Ioncube.
  * 
  * @param string $path
  * @return boolean
  */
 public static function scriptCanBeDecoded($packagename = "Professional")
 {
     //		if(!empty(self::$ioncubeWorks)){
     //			return true;
     //		}
     $majorVersion = GO::config()->getMajorVersion();
     switch ($packagename) {
         case 'Billing':
             $className = 'LicenseBilling';
             $licenseFile = 'billing-' . $majorVersion . '-license.txt';
             break;
         case 'Documents':
             $className = 'LicenseDocuments';
             $licenseFile = 'documents-' . $majorVersion . '-license.txt';
             break;
         default:
             $className = 'License';
             $licenseFile = 'groupoffice-pro-' . $majorVersion . '-license.txt';
             break;
             //			default:
             //				throw new Exception("Unkonwn package ".$packagename);
     }
     $path = GO::config()->root_path . 'modules/professional/' . $className . '.php';
     if (!file_exists($path)) {
         return false;
     }
     //echo $path;
     //check data for presence of ionCube in code.
     $data = file_get_contents($path, false, null, -1, 100);
     if (strpos($data, 'ionCube') === false) {
         return true;
     }
     if (!extension_loaded('ionCube Loader')) {
         return false;
     }
     //		$lf = self::getLicenseFile();
     $file = new \GO\Base\Fs\File(GO::config()->root_path . $licenseFile);
     //Empty license file is provided in download so we must check the size.
     if (!$file->exists()) {
         return false;
     }
     $fullClassName = "\\GO\\Professional\\" . $className;
     $check = $fullClassName::check();
     //		var_dump($check);
     return $check;
     //		self::$ioncubeWorks = true;
     //		return self::$ioncubeWorks;
 }