Example #1
0
 function save($array, &$queryModel, $rrule, $dryrun = false)
 {
     $cfg =& JEVConfig::getInstance();
     $db =& JFactory::getDBO();
     $user = JFactory::getUser();
     // Allow plugins to check data validity
     $dispatcher =& JDispatcher::getInstance();
     JPluginHelper::importPlugin("jevents");
     $res = $dispatcher->trigger('onBeforeSaveEvent', array(&$array, &$rrule, $dryrun));
     // TODO do error and hack checks here
     $ev_id = intval(JArrayHelper::getValue($array, "evid", 0));
     $newevent = $ev_id == 0;
     $data = array();
     // TODO add UID to edit form
     $data["UID"] = JArrayHelper::getValue($array, "uid", md5(uniqid(rand(), true)));
     $data["X-EXTRAINFO"] = JArrayHelper::getValue($array, "extra_info", "");
     $data["LOCATION"] = JArrayHelper::getValue($array, "location", "");
     $data["allDayEvent"] = JArrayHelper::getValue($array, "allDayEvent", "off");
     $data["CONTACT"] = JArrayHelper::getValue($array, "contact_info", "");
     $data["DESCRIPTION"] = JArrayHelper::getValue($array, "jevcontent", "");
     $data["publish_down"] = JArrayHelper::getValue($array, "publish_down", "2006-12-12");
     $data["publish_up"] = JArrayHelper::getValue($array, "publish_up", "2006-12-12");
     $data["SUMMARY"] = JArrayHelper::getValue($array, "title", "");
     $data["URL"] = JArrayHelper::getValue($array, "url", "");
     // If user is jevents can deleteall or has backend access then allow them to specify the creator
     $jevuser = JEVHelper::getAuthorisedUser();
     $creatorid = JRequest::getInt("jev_creatorid", 0);
     if ($creatorid > 0) {
         if (JVersion::isCompatible("1.6.0")) {
             //$access = JAccess::check($user->id, "core.deleteall","com_jevents");
             $access = $user->authorise('core.admin', 'com_jevents');
         } else {
             // Get an ACL object
             $acl =& JFactory::getACL();
             $grp = $acl->getAroGroup($user->get('id'));
             $access = $acl->is_group_child_of($grp->name, 'Public Backend');
         }
         if ($jevuser && $jevuser->candeleteall || $access) {
             $data["X-CREATEDBY"] = $creatorid;
         }
     }
     $ics_id = JArrayHelper::getValue($array, "ics_id", 0);
     if ($data["allDayEvent"] == "on") {
         $start_time = "00:00";
     } else {
         $start_time = JArrayHelper::getValue($array, "start_time", "08:00");
     }
     $publishstart = $data["publish_up"] . ' ' . $start_time . ':00';
     $data["DTSTART"] = JevDate::strtotime($publishstart);
     if ($data["allDayEvent"] == "on") {
         $end_time = "00:00";
     } else {
         $end_time = JArrayHelper::getValue($array, "end_time", "15:00");
     }
     $publishend = $data["publish_down"] . ' ' . $end_time . ':00';
     if (isset($array["noendtime"]) && $array["noendtime"]) {
         $publishend = $data["publish_down"] . ' 23:59:59';
     }
     $data["DTEND"] = JevDate::strtotime($publishend);
     // iCal for whole day uses 00:00:00 on the next day JEvents uses 23:59:59 on the same day
     list($h, $m, $s) = explode(":", $end_time . ':00');
     if ($h + $m + $s == 0 && $data["allDayEvent"] == "on" && $data["DTEND"] > $data["DTSTART"]) {
         //if (($h+$m+$s)==0 && $data["allDayEvent"]=="on" && $data["DTEND"]>=$data["DTSTART"]) {
         //$publishend = JevDate::strftime('%Y-%m-%d 23:59:59',($data["DTEND"]-86400));
         $publishend = JevDate::strftime('%Y-%m-%d 23:59:59', $data["DTEND"]);
         $data["DTEND"] = JevDate::strtotime($publishend);
     }
     $data["RRULE"] = $rrule;
     $data["MULTIDAY"] = JArrayHelper::getValue($array, "multiday", "1");
     $data["NOENDTIME"] = JArrayHelper::getValue($array, "noendtime", "0");
     $data["X-COLOR"] = JArrayHelper::getValue($array, "color", "");
     $data["LOCKEVENT"] = JArrayHelper::getValue($array, "lockevent", "0");
     // Add any custom fields into $data array
     foreach ($array as $key => $value) {
         if (strpos($key, "custom_") === 0) {
             $data[$key] = $value;
         }
     }
     $vevent = iCalEvent::iCalEventFromData($data);
     $vevent->catid = JArrayHelper::getValue($array, "catid", 0);
     if (is_array($vevent->catid)) {
         JArrayHelper::toInteger($vevent->catid);
     }
     // if catid is empty then use the catid of the ical calendar
     if (is_string($vevent->catid) && $vevent->catid <= 0 || is_array($vevent->catid) && count($vevent->catid) == 0) {
         $query = "SELECT catid FROM #__jevents_icsfile WHERE ics_id={$ics_id}";
         $db->setQuery($query);
         $vevent->catid = $db->loadResult();
     }
     $vevent->access = intval(JArrayHelper::getValue($array, "access", 0));
     if (!JVersion::isCompatible("1.6.0")) {
         $vevent->access = $vevent->access > $user->aid ? $user->aid : $vevent->access;
     }
     $vevent->state = intval(JArrayHelper::getValue($array, "state", 0));
     // Shouldn't really do this like this
     $vevent->_detail->priority = intval(JArrayHelper::getValue($array, "priority", 0));
     // FRONT END AUTO PUBLISHING CODE
     $frontendPublish = JEVHelper::isEventPublisher();
     if (!$frontendPublish) {
         $frontendPublish = JEVHelper::canPublishOwnEvents($ev_id);
     }
     // Always unpublish if no Publisher otherwise publish automatically (for new events)
     // Should we always notify of new events
     $notifyAdmin = $cfg->get("com_notifyallevents", 0);
     if (!JFactory::getApplication()->isAdmin()) {
         if ($frontendPublish && $ev_id == 0) {
             $vevent->state = 1;
         } else {
             if (!$frontendPublish) {
                 $vevent->state = 0;
                 // In this case we send a notification email to admin
                 $notifyAdmin = true;
             }
         }
     }
     $vevent->icsid = $ics_id;
     if ($ev_id > 0) {
         $vevent->ev_id = $ev_id;
     }
     $rp_id = intval(JArrayHelper::getValue($array, "rp_id", 0));
     if ($rp_id > 0) {
         // I should be able to do this in one operation but that can come later
         $testevent = $queryModel->listEventsById(intval($rp_id), 1, "icaldb");
         if (!JEVHelper::canEditEvent($testevent)) {
             JError::raiseError(403, JText::_('ALERTNOTAUTH'));
         }
     }
     $db =& JFactory::getDBO();
     $success = true;
     //echo "class = ".get_class($vevent);
     if (!$dryrun) {
         if (!$vevent->store()) {
             echo $db->getErrorMsg() . "<br/>";
             $success = false;
             JError::raiseWarning(101, JText::_('COULD_NOT_SAVE_EVENT_'));
         }
     } else {
         // need a value for eventid to pretend we have saved the event so we can get the repetitions
         if (!isset($vevent->ev_id)) {
             $vevent->ev_id = 0;
         }
         $vevent->rrule->eventid = $vevent->ev_id;
     }
     // Only update the repetitions if the event edit says the reptitions will have changed or a new event
     if ($newevent || JRequest::getInt("updaterepeats", 1)) {
         $repetitions = $vevent->getRepetitions(true);
         if (!$dryrun) {
             if (!$vevent->storeRepetitions()) {
                 echo $db->getErrorMsg() . "<br/>";
                 $success = false;
                 JError::raiseWarning(101, JText::_('COULD_NOT_SAVE_REPETITIONS'));
             }
         }
     }
     $res = $dispatcher->trigger('onAfterSaveEvent', array(&$vevent, $dryrun));
     if ($dryrun) {
         return $vevent;
     }
     // If not authorised to publish in the frontend then notify the administrator
     if (!$dryrun && $success && $notifyAdmin && !JFactory::getApplication()->isAdmin()) {
         JLoader::register('JEventsCategory', JEV_ADMINPATH . "/libraries/categoryClass.php");
         $cat = new JEventsCategory($db);
         $cat->load($vevent->catid);
         $adminuser = $cat->getAdminUser();
         $adminEmail = $adminuser->email;
         $config = new JConfig();
         $sitename = $config->sitename;
         $subject = JText::_('JEV_MAIL_ADDED') . ' ' . $sitename;
         $subject = $vevent->state == '1' ? '[Info] ' . $subject : '[Approval] ' . $subject;
         $Itemid = JEVHelper::getItemid();
         // reload the event to get the reptition ids
         $evid = intval($vevent->ev_id);
         $testevent = $queryModel->getEventById($evid, 1, "icaldb");
         $rp_id = $testevent->rp_id();
         list($year, $month, $day) = JEVHelper::getYMD();
         //http://joomlacode1.5svn/index.php?option=com_jevents&task=icalevent.edit&evid=1&Itemid=68&rp_id=72&year=2008&month=09&day=10&lang=cy
         $uri =& JURI::getInstance(JURI::base());
         $root = $uri->toString(array('scheme', 'host', 'port'));
         $modifylink = '<a href="' . $root . JRoute::_('index.php?option=' . JEV_COM_COMPONENT . '&task=icalevent.edit&evid=' . $evid . '&rp_id=' . $rp_id . '&Itemid=' . $Itemid . "&year={$year}&month={$month}&day={$day}") . '"><b>' . JText::_('JEV_MODIFY') . '</b></a>' . "\n";
         $viewlink = '<a href="' . $root . JRoute::_('index.php?option=' . JEV_COM_COMPONENT . '&task=icalrepeat.detail&evid=' . $rp_id . '&Itemid=' . $Itemid . "&year={$year}&month={$month}&day={$day}&login=1") . '"><b>' . JText::_('JEV_VIEW') . '</b></a>' . "\n";
         $created_by = $user->name;
         if ($created_by == null) {
             $created_by = "Anonymous";
             if (JRequest::getString("custom_anonusername", "") != "") {
                 $created_by = JRequest::getString("custom_anonusername", "") . " (" . JRequest::getString("custom_anonemail", "") . ")";
             }
         }
         JEV_CommonFunctions::sendAdminMail($sitename, $adminEmail, $subject, $testevent->title(), $testevent->content(), $created_by, JURI::root(), $modifylink, $viewlink);
     }
     if ($success) {
         return $vevent;
     }
     return $success;
 }
Example #2
0
 function notifyAuthorPublished($event)
 {
     JLoader::register('JEventsCategory', JEV_ADMINPATH . "/libraries/categoryClass.php");
     $db = JFactory::getDBO();
     $cat = new JEventsCategory($db);
     $cat->load($event->catid());
     $adminuser = $cat->getAdminUser();
     $adminEmail = $adminuser->email;
     $adminName = $adminuser->name;
     $config = new JConfig();
     $sitename = $config->sitename;
     $subject = JText::sprintf('JEV_NOTIFY_AUTHOR_SUBJECT', $sitename);
     $Itemid = JEVHelper::getItemid();
     // reload the event to get the reptition ids
     $evid = intval($event->ev_id());
     $dataModel = new JEventsDataModel("JEventsAdminDBModel");
     $queryModel = new JEventsDBModel($dataModel);
     $testevent = $queryModel->getEventById($evid, 1, "icaldb");
     // attach anonymous creator etc.
     JPluginHelper::importPlugin('jevents');
     $dispatcher =& JDispatcher::getInstance();
     $dispatcher->trigger('onDisplayCustomFields', array(&$event));
     $rp_id = $testevent->rp_id();
     list($year, $month, $day) = JEVHelper::getYMD();
     $uri =& JURI::getInstance(JURI::base());
     if (JFactory::getApplication()->isAdmin()) {
         $root = $uri->toString(array('scheme', 'host', 'port', 'path'));
         $root = str_replace("/administrator", "", $root);
         $detaillink = '<a href="' . $root . 'index.php?option=' . JEV_COM_COMPONENT . '&task=icalrepeat.detail&rp_id=' . $evid . '&rp_id=' . $rp_id . '&Itemid=' . $Itemid . "&year={$year}&month={$month}&day={$day}" . '">' . $event->title() . '</a>' . "\n";
     } else {
         $root = $uri->toString(array('scheme', 'host', 'port'));
         $detaillink = '<a href="' . $root . JRoute::_('index.php?option=' . JEV_COM_COMPONENT . '&task=icalrepeat.detail&rp_id=' . $evid . '&rp_id=' . $rp_id . '&Itemid=' . $Itemid . "&year={$year}&month={$month}&day={$day}") . '">' . $event->title() . '</a>' . "\n";
     }
     $content = sprintf(JText::_('JEV_NOTIFY_AUTHOR_Message'), $detaillink, $sitename);
     $authorname = "";
     $authoremail = "";
     if ($event->created_by() > 0) {
         $author = JFactory::getUser($event->created_by());
         if (!$author) {
             return;
         }
         $authorname = $author->name;
         $authoremail = $author->email;
     } else {
         if (isset($event->authoremail) && $event->authoremail != "") {
             $authorname = $event->authorname;
             $authoremail = $event->authoremail;
         }
     }
     if ($authoremail == "") {
         return;
     }
     // mail function
     $mail =& JFactory::getMailer();
     $mail->setSender(array(0 => $adminEmail, 1 => $adminName));
     $mail->addRecipient($authoremail);
     $mail->setSubject($subject);
     $mail->setBody($content);
     $mail->IsHTML(true);
     $mail->send();
 }
Example #3
0
 function storeEvents($catid = false, $flush = true)
 {
     // clean out the cache
     $cache = JFactory::getCache('com_jevents');
     $cache->clean(JEV_COM_COMPONENT);
     $params = JComponentHelper::getParams(JEV_COM_COMPONENT);
     static $categories;
     if (is_null($categories)) {
         $db = JFactory::getDBO();
         $sql = "SELECT * FROM #__categories WHERE extension='com_jevents'";
         $db->setQuery($sql);
         $categories = $db->loadObjectList('title');
     }
     if (!$catid) {
         $catid = $this->catid;
     }
     // insert the data - this will need to deal with multiple rrule values
     foreach ($this->_icalInfo->vevents as &$vevent) {
         // Do I need to remove a duplicate event?
         $sql = "SELECT * FROM #__jevents_vevent WHERE uid=" . $db->Quote($vevent->uid);
         $db->setQuery($sql);
         $duplicate = $db->loadObject();
         if ($duplicate && !$vevent->isCancelled() && !$vevent->isRecurrence()) {
             $veventidstring = $duplicate->ev_id;
             // TODO the ruccurences should take care of all of these??
             // This would fail if all recurrances have been 'adjusted'
             $query = "SELECT DISTINCT (eventdetail_id) FROM #__jevents_repetition WHERE eventid IN ({$veventidstring})";
             $db->setQuery($query);
             $detailids = $db->loadColumn();
             $detailidstring = implode(",", $detailids);
             $query = "DELETE FROM #__jevents_rrule WHERE eventid IN ({$veventidstring})";
             $db->setQuery($query);
             $db->execute();
             $query = "DELETE FROM #__jevents_repetition WHERE eventid IN ({$veventidstring})";
             $db->setQuery($query);
             $db->execute();
             $query = "DELETE FROM #__jevents_exception WHERE eventid IN ({$veventidstring})";
             $db->setQuery($query);
             $db->execute();
             if (JString::strlen($detailidstring) > 0) {
                 $query = "DELETE FROM #__jevents_vevdetail WHERE evdet_id IN ({$detailidstring})";
                 $db->setQuery($query);
                 $db->execute();
                 // I also need to clean out associated custom data
                 $dispatcher = JEventDispatcher::getInstance();
                 // just incase we don't have jevents plugins registered yet
                 JPluginHelper::importPlugin("jevents");
                 $res = $dispatcher->trigger('onDeleteEventDetails', array($detailidstring));
             }
             $query = "DELETE FROM #__jevents_vevent WHERE ev_id IN ({$veventidstring})";
             $db->setQuery($query);
             $db->execute();
             // I also need to delete custom data
             $res = $dispatcher->trigger('onDeleteCustomEvent', array(&$veventidstring));
         }
         if (!$vevent->isCancelled() && !$vevent->isRecurrence()) {
             // if existing category then use it
             if (!$this->ignoreembedcat && JString::strlen($vevent->_detail->categories) > 0) {
                 $evcat = explode(",", $vevent->_detail->categories);
                 if (count($evcat) > 0 && array_key_exists($evcat[0], $categories)) {
                     if ($params->get("multicategory", 0) && count($evcat) > 1) {
                         $vevent->catid = array();
                         foreach ($evcat as $ct) {
                             $vevent->catid[] = $categories[$ct]->id;
                         }
                     }
                     if ($params->get("multicategory", 0) && count($evcat) == 1) {
                         $vevent->catid = array();
                         $vevent->catid[] = $categories[$evcat[0]]->id;
                     } else {
                         $vevent->catid = $categories[$evcat[0]]->id;
                     }
                 } else {
                     if (count($evcat) > 0) {
                         include_once JEV_ADMINLIBS . "categoryClass.php";
                         $cat = new JEventsCategory($db);
                         $cat->bind(array("title" => $evcat[0]));
                         $cat->published = 1;
                         $cat->store();
                         if ($params->get("multicategory", 0)) {
                             $vevent->catid[] = $cat->id;
                         } else {
                             $vevent->catid = $cat->id;
                         }
                         // must reset  the list of categories now
                         $sql = "SELECT * FROM #__categories WHERE extension='com_jevents'";
                         $db->setQuery($sql);
                         $categories = $db->loadObjectList('title');
                     }
                 }
             } else {
                 if ($params->get("multicategory", 0)) {
                     $vevent->catid[] = $catid;
                 } else {
                     $vevent->catid = $catid;
                 }
             }
             $vevent->icsid = $this->ics_id;
             // The refreshed field is used to track dropped events on reload
             $vevent->refreshed = $this->refreshed;
             // handle events running over midnight
             $params = JComponentHelper::getParams(JEV_COM_COMPONENT);
             $icalmultiday = $params->get("icalmultiday", 0);
             $icalmultiday24h = $params->get("icalmultiday24h", 0);
             // These booleans are the wrong way around.
             $vevent->_detail->multiday = $icalmultiday ? 0 : 1;
             if ($vevent->_detail->dtend - $vevent->_detail->dtstart < 86400) {
                 $vevent->_detail->multiday = $icalmultiday24h ? 0 : 1;
             }
             // force creator if appropriate
             if ($this->created_by > 0) {
                 $vevent->created_by = $this->created_by;
                 // force override of creator
                 $vevent->store(false, true);
             } else {
                 $vevent->store();
             }
             $repetitions = $vevent->getRepetitions(true);
             $vevent->storeRepetitions();
             // Save memory by clearing out the repetitions we no longer need
             $vevent->_repetitions = null;
             $repetitions = null;
             echo "Event Data read in<br/>";
             //echo "memory = ".memory_get_usage()." ".memory_get_usage(true)."<br/>";
             if ($flush) {
                 ob_flush();
                 flush();
             }
         }
     }
     unset($vevent);
     // Having stored all the repetitions - remove the cancelled instances
     // this should be done as a batch but for now I'll do them one at a time
     foreach ($this->_icalInfo->vevents as $vevent) {
         if (!is_null($vevent) && ($vevent->isCancelled() || $vevent->isRecurrence())) {
             // if existing category then use it
             if (JString::strlen($vevent->_detail->categories) > 0) {
                 $evcat = explode(",", $vevent->_detail->categories);
                 if (count($evcat) > 0 && array_key_exists($evcat[0], $categories)) {
                     if ($params->get("multicategory", 0) && count($evcat) > 1) {
                         $vevent->catid = array();
                         foreach ($evcat as $ct) {
                             $vevent->catid[] = $categories[$ct]->id;
                         }
                     } else {
                         $vevent->catid = $categories[$evcat[0]]->id;
                     }
                 } else {
                     if (count($evcat) > 0) {
                         include_once JEV_ADMINLIBS . "categoryClass.php";
                         $cat = new JEventsCategory($db);
                         $cat->bind(array("title" => $evcat[0]));
                         $cat->published = 1;
                         $cat->check();
                         $cat->store();
                         if ($params->get("multicategory", 0)) {
                             $vevent->catid[] = $cat->id;
                         } else {
                             $vevent->catid = $cat->id;
                         }
                         // must reset  the list of categories now
                         $sql = "SELECT * FROM #__categories WHERE extension='com_jevents'";
                         $db->setQuery($sql);
                         $categories = $db->loadObjectList('title');
                     }
                 }
             } else {
                 if ($params->get("multicategory", 0)) {
                     $vevent->catid[] = $catid;
                 } else {
                     $vevent->catid = $catid;
                 }
             }
             $vevent->access = $this->access;
             $vevent->state = $this->state;
             $vevent->icsid = $this->ics_id;
             // make sure I don't add the same events more than once
             if ($matchingEvent = $vevent->matchingEventDetails()) {
                 $vevent->ev_id = $matchingEvent->ev_id;
             }
             if ($vevent->isCancelled()) {
                 $vevent->cancelRepetition();
             } else {
                 // replace event that is only 'adjusted' with the correct settings
                 $vevent->adjustRepetition($matchingEvent);
             }
         }
     }
     return count($this->_icalInfo->vevents);
 }
Example #4
0
 private function createOrphanCategory()
 {
     $db = JFactory::getDBO();
     $sql = "SELECT id from #__categories where extension='com_jevents' AND title='Orphans'";
     $db->setQuery($sql);
     $catid = $db->loadResult();
     // Add orphan category if none exist already
     if (!$catid) {
         JLoader::register('JEventsCategory', JEV_ADMINPATH . "/libraries/categoryClass.php");
         $cat = new JEventsCategory($db);
         $cat->bind(array("title" => "Orphans", "published" => 0, "color" => "#CCCCFF", "access" => 1));
         $cat->store();
         $catid = $cat->id;
     }
     return $catid;
 }
Example #5
0
    function dbsetup()
    {
        $db =& JFactory::getDBO();
        $charset = $db->hasUTF() ? 'DEFAULT CHARACTER SET `utf8`' : '';
        /**
         * create table if it doesn't exit
         * 
         * For now : 
         * 
         * I'm ignoring attach,comment, resources, transp, attendee, related to, rdate, request-status
         * 
         * Separate tables for rrule and exrule
         */
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_vevent(
\tev_id int(12) NOT NULL auto_increment,
\ticsid int(12) NOT NULL default 0,
\tcatid int(11) NOT NULL default 1,
\tuid varchar(255) NOT NULL UNIQUE default "",
\trefreshed datetime  NOT NULL default '0000-00-00 00:00:00',
\tcreated datetime  NOT NULL default '0000-00-00 00:00:00',
\tcreated_by int(11) unsigned NOT NULL default '0',
\tcreated_by_alias varchar(100) NOT NULL default '',
\tmodified_by int(11) unsigned NOT NULL default '0',

\trawdata longtext NOT NULL default "",
\trecurrence_id varchar(30) NOT NULL default "",
\t
\tdetail_id int(12) NOT NULL default 0,
\t
\tstate tinyint(3) NOT NULL default 1,
\tlockevent tinyint(3) NOT NULL default 0,
\tauthor_notified tinyint(3) NOT NULL default 0,
\taccess int(11) unsigned NOT NULL default 0,
\t
\tPRIMARY KEY  (ev_id),
\tINDEX (icsid),
\tINDEX stateidx (state)
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "alter table #__jevents_vevent add column lockevent tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_vevent add column author_notified tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevent` ADD created datetime  NOT NULL default '0000-00-00 00:00:00'";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_vevent add index stateidx (`state`)";
        $db->setQuery($sql);
        @$db->query();
        /**
         * create table if it doesn't exit
         * 
         * For now : 
         * 
         * I'm ignoring attach,comment, resources, transp, attendee, related to, rdate, request-status
         * 
         * Separate tables for rrule and exrule
         */
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_vevdetail(
\tevdet_id int(12) NOT NULL auto_increment,

\trawdata longtext NOT NULL default "",
\tdtstart int(11) NOT NULL default 0,
\tdtstartraw varchar(30) NOT NULL default "",
\tduration int(11) NOT NULL default 0,
\tdurationraw varchar(30) NOT NULL default "",
\tdtend int(11) NOT NULL default 0,
\tdtendraw varchar(30) NOT NULL default "",
\tdtstamp varchar(30) NOT NULL default "",
\tclass  varchar(10) NOT NULL default "",
\tcategories varchar(120) NOT NULL default "",
\tcolor varchar(20) NOT NULL default "",
\tdescription longtext NOT NULL default "",
\tgeolon float NOT NULL default 0,
\tgeolat float NOT NULL default 0,
\tlocation VARCHAR(120) NOT NULL default "",
\tpriority tinyint unsigned NOT NULL default 0,
\tstatus varchar(20) NOT NULL default "",
\tsummary longtext NOT NULL default "",
\tcontact VARCHAR(120) NOT NULL default "",
\torganizer VARCHAR(120) NOT NULL default "",
\turl text NOT NULL default "",
\textra_info VARCHAR(240) NOT NULL DEFAULT '',
\tcreated varchar(30) NOT NULL default "",
\tsequence int(11) NOT NULL default 1,
\tstate tinyint(3) NOT NULL default 1,
\tmodified datetime  NOT NULL default '0000-00-00 00:00:00',

\tmultiday tinyint(3) NOT NULL default 1,
\thits int(11) NOT NULL default 0,
\tnoendtime tinyint(3) NOT NULL default 0,
\t\t
\tPRIMARY KEY  (evdet_id), 
\tFULLTEXT searchIdx (summary,description)
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_vevdetail` MODIFY COLUMN url text NOT NULL default ''";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevdetail` ADD modified datetime  NOT NULL default '0000-00-00 00:00:00' ";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevdetail` ADD color varchar(20) NOT NULL default ''";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevdetail` ADD multiday tinyint(3) NOT NULL default 1";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevdetail` ADD noendtime tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_vevdetail` ADD hits int(11) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE #__jevents_vevdetail ADD FULLTEXT searchIdx (summary,description)";
        $db->setQuery($sql);
        @$db->query();
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_rrule (
\trr_id int(12) NOT NULL auto_increment,
\teventid int(12) NOT NULL default 1,
\tfreq varchar(30) NOT NULL default "",
\tuntil int(12) NOT NULL default 1,
\tuntilraw varchar(30) NOT NULL default "",
\tcount int(6) NOT NULL default 1,
\trinterval int(6) NOT NULL default 1,
\tbysecond  varchar(50) NOT NULL default "",
\tbyminute  varchar(50) NOT NULL default "",
\tbyhour  varchar(50) NOT NULL default "",
\tbyday  varchar(50) NOT NULL default "",
\tbymonthday  varchar(50) NOT NULL default "",
\tbyyearday  varchar(50) NOT NULL default "",
\tbyweekno  varchar(50) NOT NULL default "",
\tbymonth  varchar(50) NOT NULL default "",
\tbysetpos  varchar(50) NOT NULL default "",
\twkst  varchar(50) NOT NULL default "",
\tPRIMARY KEY  (rr_id),
\tINDEX (eventid)
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_rrule` ADD INDEX eventid (eventid)";
        $db->setQuery($sql);
        @$db->query();
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_repetition (
\trp_id int(12) NOT NULL auto_increment,
\teventid int(12) NOT NULL default 1,
\teventdetail_id int(12) NOT NULL default 0,\t
\tduplicatecheck varchar(32) NOT NULL UNIQUE default "",
\tstartrepeat datetime  NOT NULL default '0000-00-00 00:00:00',
\tendrepeat datetime  NOT NULL default '0000-00-00 00:00:00',
\tPRIMARY KEY  (rp_id),
\tINDEX (eventid),
\tINDEX `eventstart` ( `eventid` , `startrepeat` ),
\tINDEX `eventend` ( `eventid` , `endrepeat` ),
\tINDEX `eventdetail` ( `eventdetail_id` ),
\tINDEX `startrepeat` ( `startrepeat` ),
\tINDEX `startend` ( `startrepeat`,`endrepeat` ),
\tINDEX `endrepeat` (  `endrepeat` )
\t
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_repetition` ADD INDEX `eventstart` ( `eventid` , `startrepeat` )";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_repetition` ADD INDEX `eventend` ( `eventid` , `endrepeat` )";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_repetition` ADD INDEX `eventdetail` ( `eventdetail_id`  )";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_repetition add index startrepeat (`startrepeat`)";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_repetition add index endrepeat (`endrepeat`)";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_repetition add index startend (`startrepeat`,`endrepeat`)";
        $db->setQuery($sql);
        @$db->query();
        // exception_type 0=delete, 1=other exception
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_exception (
\tex_id int(12) NOT NULL auto_increment,
\trp_id int(12) NOT NULL default 0,
\teventid int(12) NOT NULL default 1,
\teventdetail_id int(12) NOT NULL default 0,\t
\texception_type int(2) NOT NULL default 0,
\tstartrepeat datetime  NOT NULL default '0000-00-00 00:00:00',
\toldstartrepeat datetime  NOT NULL default '0000-00-00 00:00:00',
\ttempfield datetime  NOT NULL default '0000-00-00 00:00:00',
\tPRIMARY KEY  (ex_id),
\tKEY (eventid),
\tKEY (rp_id)
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_exception` add column startrepeat datetime  NOT NULL default '0000-00-00 00:00:00'";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_exception` add column oldstartrepeat datetime  NOT NULL default '0000-00-00 00:00:00'";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_exception` add column tempfield datetime  NOT NULL default '0000-00-00 00:00:00'";
        $db->setQuery($sql);
        @$db->query();
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_categories (
\tid int(12) NOT NULL default 0 PRIMARY KEY,
\tcolor VARCHAR(8) NOT NULL default '',
\toverlaps tinyint(3) NOT NULL default 0,
\tadmin int(12) NOT NULL default 0
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_categories` add column admin int(12) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jevents_categories` add column overlaps tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        // Add one category by default if none exist already
        $sql = "SELECT count(id) from #__jevents_categories";
        $db->setQuery($sql);
        $count = $db->loadResult();
        if ($count == 0) {
            JLoader::register('JEventsCategory', JEV_ADMINPATH . "/libraries/categoryClass.php");
            $cat = new JEventsCategory($db);
            if (JVersion::isCompatible("1.6.0")) {
                $cat->bind(array("title" => JText::_('DEFAULT'), "published" => 1, "color" => "#CCCCFF", "access" => 1));
            } else {
                $cat->bind(array("title" => JText::_('DEFAULT'), "published" => 1, "color" => "#CCCCFF", "access" => 0));
            }
            $cat->store();
            $catid = $cat->id;
        } else {
            $catid = 0;
        }
        /**
         * create table if it doesn't exit
         * 
         * For now : 
         * 
         * I'm ignoring attach,comment, resources, transp, attendee, related to, rdate, request-status
         * 
         * note that icaltype = 0 for imported from URL, 1 for imported from file, 2 for created natively
         * Separate tables for rrule and exrule
         * 
         */
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_icsfile(
\tics_id int(12) NOT NULL auto_increment,
\tsrcURL VARCHAR(255) NOT NULL default "",
\tlabel varchar(30) NOT NULL UNIQUE default "",

\tfilename VARCHAR(120) NOT NULL default "",
\ticaltype tinyint(3) NOT NULL default 0,
\tisdefault tinyint(3) NOT NULL default 0,
\tignoreembedcat  tinyint(3) NOT NULL default 0,
\tstate tinyint(3) NOT NULL default 1,
\taccess int(11) unsigned NOT NULL default 0,
\tcatid int(11) NOT NULL default 1,
\tcreated datetime  NOT NULL default '0000-00-00 00:00:00',
\tcreated_by int(11) unsigned NOT NULL default '0',
\tcreated_by_alias varchar(100) NOT NULL default '',
\tmodified_by int(11) unsigned NOT NULL default '0',
\trefreshed datetime  NOT NULL default '0000-00-00 00:00:00',
\tautorefresh tinyint(3) NOT NULL default 0,
\toverlaps tinyint(3) NOT NULL default 0,
\t\t
\tPRIMARY KEY  (ics_id),
\tINDEX stateidx (state)
\t
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jevents_icsfile` ADD overlaps tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "alter table #__jevents_icsfile add index stateidx (`state`)";
        $db->setQuery($sql);
        @$db->query();
        // Alter table
        $sql = "Alter table #__jevents_icsfile ADD COLUMN isdefault tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "Alter table #__jevents_icsfile ADD COLUMN ignoreembedcat tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "Alter table #__jevents_icsfile ADD COLUMN autorefresh tinyint(3) NOT NULL default 0";
        $db->setQuery($sql);
        @$db->query();
        $sql = "Alter table #__jevents_icsfile MODIFY COLUMN srcURL varchar(255) NOT NULL default '' ";
        $db->setQuery($sql);
        $db->query();
        // Add one native calendar by default if none exist already
        $sql = "SELECT ics_id from #__jevents_icsfile WHERE icaltype=2";
        $db->setQuery($sql);
        $ics = $db->loadResult();
        if (!$ics || is_null($ics) || $ics == 0) {
            if (JVersion::isCompatible("1.6.0")) {
                $sql = "INSERT INTO #__jevents_icsfile (label,filename,\ticaltype,state,\taccess,\tcatid, isdefault) VALUES ('Default','Initial ICS File',2,1,1,{$catid},1)";
            } else {
                $sql = "INSERT INTO #__jevents_icsfile (label,filename,\ticaltype,state,\taccess,\tcatid, isdefault) VALUES ('Default','Initial ICS File',2,1,0,{$catid},1)";
            }
            $db->setQuery($sql);
            $db->query();
            echo $db->getErrorMsg();
        }
        // 1. Make sure users table exists
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS `#__jev_users` (
\t`id` int( 11 ) unsigned NOT NULL AUTO_INCREMENT ,
\t`user_id` int( 11 ) NOT NULL default '0',
\t`published` tinyint( 2 ) NOT NULL default '0',

\t`canuploadimages` tinyint( 2 ) NOT NULL default '0',
\t`canuploadmovies` tinyint( 2 ) NOT NULL default '0',

\t`cancreate` tinyint( 2 ) NOT NULL default '0',
\t`canedit` tinyint( 2 ) NOT NULL default '0',

\t`canpublishown` tinyint( 2 ) NOT NULL default '0',
\t`candeleteown` tinyint( 2 ) NOT NULL default '0',

\t`canpublishall` tinyint( 2 ) NOT NULL default '0',
\t`candeleteall` tinyint( 2 ) NOT NULL default '0',

\t`cancreateown` tinyint( 2 ) NOT NULL default '0',
\t`cancreateglobal` tinyint( 2 ) NOT NULL default '0',
\t`eventslimit` int( 11 ) NOT NULL default '0',
\t`extraslimit` int( 11 ) NOT NULL default '0',
\t
\t`categories` varchar(255) NOT NULL default '',
\t`calendars` varchar(255) NOT NULL default '',
\t
\t`created` datetime  NOT NULL default '0000-00-00 00:00:00',\t
\t
\tPRIMARY KEY ( `id` ),
\tKEY `user` (`user_id`  )
);
SQL;
        $db->setQuery($sql);
        if (!$db->query()) {
            echo $db->getErrorMsg();
        }
        $sql = "ALTER TABLE `#__jev_users` ADD categories varchar(255) NOT NULL default ''";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jev_users` ADD calendars varchar(255) NOT NULL default ''";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jev_users` ADD created datetime  NOT NULL default '0000-00-00 00:00:00'";
        $db->setQuery($sql);
        @$db->query();
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jevents_repbyday (
\trptday DATE  NOT NULL default '0000-00-00',
\trp_id int(12) NOT NULL default 0,
\tcatid int(11) NOT NULL default 1,
\tINDEX (rptday),
\tINDEX `daycat` ( `rptday` , `catid` )\t
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = <<<SQL
CREATE TABLE IF NOT EXISTS #__jev_defaults (
\tid int( 11 ) unsigned NOT NULL AUTO_INCREMENT ,
\ttitle varchar(100) NOT NULL default "",
\tname varchar(50) NOT NULL default "",
\tsubject text NOT NULL default "",
\tvalue text NOT NULL default "",
\tstate tinyint(3) NOT NULL default 1,
\tparams text NOT NULL default "",
\tPRIMARY KEY  (id),
\tINDEX (name)
) ENGINE=MyISAM {$charset};
SQL;
        $db->setQuery($sql);
        $db->query();
        echo $db->getErrorMsg();
        $sql = "ALTER TABLE `#__jev_defaults` ADD params text NOT NULL default ''";
        $db->setQuery($sql);
        @$db->query();
        $sql = "SHOW COLUMNS FROM `#__jev_defaults`";
        $db->setQuery($sql);
        $cols = @$db->loadObjectList();
        foreach ($cols as $col) {
            if ($col->Field == 'name' && $col->Key == 'PRI') {
                $sql = "ALTER TABLE `#__jev_defaults` DROP PRIMARY KEY";
                $db->setQuery($sql);
                @$db->query();
            }
        }
        $sql = "ALTER TABLE `#__jev_defaults` ADD id int( 11 ) unsigned NOT NULL AUTO_INCREMENT , add key (id) ";
        $db->setQuery($sql);
        @$db->query();
        $sql = "ALTER TABLE `#__jev_defaults` ADD PRIMARY KEY id  (id)";
        $db->setQuery($sql);
        @$db->query();
        // get the view
        $this->view =& $this->getView("config", "html");
        // Set the layout
        $this->view->setLayout('dbsetup');
        $this->view->display();
    }
 function edit($tpl = null)
 {
     $document =& JFactory::getDocument();
     // this already includes administrator
     $livesite = JURI::base();
     if (JVersion::isCompatible("1.6.0")) {
         JEVHelper::stylesheet('eventsadmin16.css', 'administrator/components/' . JEV_COM_COMPONENT . '/assets/css/');
     } else {
         $document->addStyleSheet($livesite . 'components/' . JEV_COM_COMPONENT . '/assets/css/eventsadmin.css');
     }
     $document->setTitle(JText::_('JEVENTS') . ' :: ' . JText::_('JEVENTS'));
     // Set toolbar items for the page
     JToolBarHelper::title(JText::_('JEV_EDIT_USER'), 'jevents');
     JToolBarHelper::save("user.save");
     JToolBarHelper::cancel("user.overview");
     //JToolBarHelper::help( 'edit.user', true);
     $option = JRequest::getCmd('option', JEV_COM_COMPONENT);
     $db =& JFactory::getDBO();
     $params =& JComponentHelper::getParams(JEV_COM_COMPONENT);
     if (JVersion::isCompatible("1.6.0")) {
         $rules = JAccess::getAssetRules("com_jevents", true);
         $data = $rules->getData();
         $creatorgroups = $data["core.create"]->getData();
         foreach ($data["core.admin"]->getData() as $creatorgroup => $permission) {
             if ($permission) {
                 $creatorgroups[$creatorgroup] = $permission;
             }
         }
         // array_merge does a re-indexing !!
         //$creatorgroups = array_merge($creatorgroups["core.admin"]->getData(), $creatorgroups["core.create"]->getData());
         $users = array(0);
         foreach ($creatorgroups as $creatorgroup => $permission) {
             if ($permission == 1) {
                 $users = array_merge(JAccess::getUsersByGroup($creatorgroup, true), $users);
             }
         }
         $sql = "SELECT * FROM #__users where id IN (" . implode(",", array_values($users)) . ") ORDER BY name asc";
         $db->setQuery($sql);
         $users = $db->loadObjectList();
     } else {
         $minaccess = $params->getValue("jevcreator_level", 19);
         // get users AUTHORS and above
         $sql = "SELECT * FROM #__users where gid>=" . $minaccess;
         $db->setQuery($sql);
         $users = $db->loadObjectList();
     }
     $userOptions[] = JHTML::_('select.option', '-1', JText::_('SELECT_USER'));
     foreach ($users as $user) {
         $userOptions[] = JHTML::_('select.option', $user->id, $user->name . " ({$user->username})");
     }
     $jevuser =& $this->get('user');
     $userlist = JHTML::_('select.genericlist', $userOptions, 'user_id', 'class="inputbox" size="1" ', 'value', 'text', $jevuser->user_id);
     JLoader::register('JEventsCategory', JEV_ADMINPATH . "/libraries/categoryClass.php");
     $categories = JEventsCategory::categoriesTree();
     $lists['categories'] = JHTML::_('select.genericlist', $categories, 'categories[]', 'multiple="multiple" size="15"', 'value', 'text', explode("|", $jevuser->categories));
     // get calendars
     $sql = "SELECT label as text, ics_id as value FROM #__jevents_icsfile where icaltype=2";
     $db->setQuery($sql);
     $calendars = $db->loadObjectList();
     $lists['calendars'] = JHTML::_('select.genericlist', $calendars, 'calendars[]', 'multiple="multiple" size="15"', 'value', 'text', explode("|", $jevuser->calendars));
     $this->assignRef('lists', $lists);
     $this->assignRef("users", $userlist);
     $this->assignRef('jevuser', $jevuser);
     JHTML::_('behavior.tooltip');
 }