Example #1
0
 /**
  * start the app
  */
 public function run()
 {
     $this->_initRegister();
     date_default_timezone_set($this->config['timezone']);
     if (false === IS_CLI) {
         $this->route = Route::instance()->init();
         $this->controller = Controller::create($this->route);
     }
 }
Example #2
0
 /**
  * addNotification
  * add notification
  * 
  * @access public
  * @return boolean
  * 
  */
 public function addNotification($notification, $email = null)
 {
     if (!empty($notification)) {
         $this->_model->create();
         if ($this->_model->save($notification)) {
             if (!empty($email)) {
                 $this->_emailNotify($this->_model->read(), $email);
             }
             return true;
         } else {
             return false;
         }
     }
 }
Example #3
0
 /**
  * addNotification
  * add notification
  * 
  * @access public
  * @return boolean
  * 
  */
 public function addNotification($notification, $email = null)
 {
     if (!Configure::read('Tickets.notify')) {
         return true;
     }
     if (!empty($notification)) {
         $this->_model->create();
         if ($this->_model->save($notification)) {
             if (!empty($email)) {
                 $this->_model->recursive = 1;
                 $this->_emailNotify($this->_model->read(), $email);
             }
             return true;
         } else {
             return false;
         }
     }
 }
Example #4
0
        echo fread($handle, filesize(DATA_FILE));
        fclose($handle);
    }
    private function appendToFile($content)
    {
        $handle = $this->openFile('a');
        if (!fwrite($handle, $content)) {
            exit('write file failed');
        }
        fclose($handle);
        return true;
    }
}
$obj = new Controller();
$method = isset($_GET['m']) ? trim($_GET['m']) : '';
switch ($method) {
    case 'getList':
        $obj->getList();
        break;
    case '':
        $obj->index();
        break;
    case 'create':
        $obj->create();
        break;
    case 'getLineNum':
        $obj->getLineNum();
    case 'compareCode':
        $obj->compareCode();
}
exit;
Example #5
0
$target = gmdate('U') - 300 . '000';
$parts = Controller::service('PostgreSQL')->execSql('SELECT part.user_info_id as "user", co.id as "schedulable", co.type_id as "type", co.allDay as "allDay" ,co.dtend as "endTime", co.dtstart as "startTime", co.summary as "summary", co.tzid as "timezone", co.location as "location", al.id as "id" FROM calendar_object as co INNER JOIN calendar_alarm al ON co.id = al.object_id JOIN calendar_participant part  ON part.id = al.participant_id LEFT JOIN calendar_repeat rep ON  rep.object_id = co.id  LEFT JOIN calendar_repeat_occurrence occ ON occ.repeat_id = rep.id WHERE ( al.action_id = \'' . ALARM_MAIL . '\' AND al.sent = \'0\' AND CASE WHEN occ.occurrence > 0 THEN occ.occurrence - al.alarm_offset ELSE co.dtstart - al.alarm_offset END BETWEEN \'' . $target . '\' AND \'' . ($target + 360000) . '\') ');
if (!is_array($parts)) {
    return;
}
$ids = array();
foreach ($parts as $i => $part) {
    ///Montando lista de participantes
    $users = Controller::find(array('concept' => 'participant'), array('user', 'id', 'isExternal'), array('filter' => array('=', 'schedulable', $part['schedulable']), 'deepness' => 1));
    $attList = array();
    foreach ($users as $user) {
        if ($part['user'] === $user['user']['id']) {
            $part['mail'] = $user['user']['mail'];
        }
        $attList[] = $user['user']['name'];
    }
    $timezone = new DateTimeZone('UTC');
    $sTime = new DateTime('@' . (int) ($part['startTime'] / 1000), $timezone);
    $eTime = new DateTime('@' . (int) ($part['endTime'] / 1000), $timezone);
    $timezone = $part['timezone'];
    $sTime->setTimezone(new DateTimeZone($part['timezone']));
    $eTime->setTimezone(new DateTimeZone($part['timezone']));
    $data = array('startDate' => date_format($sTime, 'd/m/Y'), 'startTime' => $part['allDay'] ? '' : date_format($sTime, 'H:i'), 'endDate' => date_format($eTime, 'd/m/Y'), 'endTime' => $part['allDay'] ? '' : date_format($eTime, 'H:i'), 'eventTitle' => $part['summary'], 'eventLocation' => $part['location'], 'timezone' => $timezone, 'participants' => '<UL> <LI> ' . implode('<LI></LI> ', $attList) . '</LI> </UL>');
    Controller::create(array('service' => 'SMTP'), array('body' => parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . ($parts['type'] == '1' ? 'notify_alarm_body.tpl' : 'notify_alarm_body_task.tpl')), 'isHtml' => true, 'subject' => 'Alarme de Calendario', 'from' => $part['mail'], 'to' => $part['mail']));
    Config::regSet('noAlarm', TRUE);
    //Evita o envio de notificação ?????
    $ids[] = $part['id'];
}
if (!empty($ids)) {
    Controller::update(array('concept' => 'alarm'), array('sent' => '1'), array('filter' => array('IN', 'id', $ids)));
}
Example #6
0
<?php

include 'library/bootstrap.php';
Routing::init();
try {
    if (Routing::isAPI()) {
        $controller = APIController::create(array('controller' => Routing::controllerName()));
    } else {
        $controller = Controller::create(array('controller' => Routing::controllerName()));
    }
} catch (Exception $e) {
    Util::redirect('/404.html');
}
$controller->beforeFilter();
$controller->filter(Routing::action(), Routing::args());
$controller->afterFilter();
 /**
  * Throws a HTTP error response encased in a {@link SS_HTTPResponse_Exception}, which is later caught in
  * {@link RequestHandler::handleAction()} and returned to the user.
  *
  * @param int $errorCode
  * @param string $errorMessage Plaintext error message
  * @uses SS_HTTPResponse_Exception
  */
 public function httpError($errorCode, $errorMessage = null)
 {
     $request = $this->getRequest();
     // Call a handler method such as onBeforeHTTPError404
     $this->extend('onBeforeHTTPError' . $errorCode, $request);
     // Call a handler method such as onBeforeHTTPError, passing 404 as the first arg
     $this->extend('onBeforeHTTPError', $errorCode, $request);
     /**
      * @andrelohmann
      * 
      * This code allows to return custom Error Pages without using the CMS Module
      * 
      */
     $template = array('ErrorPage', 'Page');
     $C = Controller::create();
     $C->onBeforeInit();
     $C->init();
     $C->onAfterInit();
     $result = $C->customise(new ArrayData(array('Title' => $errorCode, 'Content' => DBField::create_field('HTMLText', $errorMessage))));
     // Throw a new exception
     throw new SS_HTTPResponse_Exception(new SS_HTTPResponse($result->renderWith($template)), $errorCode);
     /**
      * Original Code
      *
      * // Throw a new exception
      * throw new SS_HTTPResponse_Exception($errorMessage, $errorCode);
      * 
      */
 }
Example #8
0
<?

include 'Library/bootstrap.php';

try {
	$controller = Controller::create(Routing::controllerName());
} catch (Exception $e){
	Util::redirect('404.html');
}

$controller->beforeFilter();
$controller->filter(Routing::action(), Routing::args());
$controller->afterFilter();

?>
 /**
  * Store the supplied access token values to storage.
  *
  * We need to store access token data as we create and verify tokens.
  *
  * @param $oauth_token
  * oauth_token to be stored.
  * @param $client_id
  * Client identifier to be stored.
  * @param $user_id
  * User identifier to be stored.
  * @param $expires
  * Expiration to be stored.
  * @param $scope
  * (optional) Scopes to be stored in space-separated string.
  *
  * @ingroup oauth2_section_4
  */
 public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL, $refresh_token)
 {
     $data = array();
     $data['oauth_token'] = $oauth_token;
     $data['client_id'] = $client_id;
     $data['user_id'] = $user_id;
     $data['expires'] = $expires;
     $data['scope'] = $scope;
     $data['refresh_token'] = $refresh_token;
     Controller::create(array('concept' => 'oauthToken'), $data);
 }
Example #10
0
 private static function _makeVTODO($schedulable, $component, $params)
 {
     $interation = array();
     $todoID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
     /* Data de Inicio */
     $startTime = $component->getProperty('dtstart', false, true);
     $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
     /* Tiem zone do evento */
     if ($tzid) {
         $tzid = self::nomalizeTZID($tzid);
         $schedulable['timezone'] = $tzid;
     } else {
         $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
     }
     $objTimezone = new DateTimeZone($schedulable['timezone']);
     if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
         $schedulable['allDay'] = 1;
         $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
     } elseif ($tzid && !isset($startTime['value']['tz'])) {
         /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
         $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
         $schedulable['allDay'] = 0;
     } else {
         $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
         if (strpos($params['prodid'], 'Outlook') !== false) {
             //Se o ics veio em utc não aplicar horario de verão
             $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
             $sTime->setTimezone($objTimezone);
             if ($sTime->format('I')) {
                 //Se o ics veio em utc não aplicar horario de verão
                 $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
             }
         }
     }
     /* Data de Termino */
     if ($due = $component->getProperty('due', false, true)) {
         $tzid = isset($due['params']['TZID']) ? $due['params']['TZID'] : $params['X-WR-TIMEZONE'];
         if ($tzid) {
             $tzid = self::nomalizeTZID($tzid);
         }
         if (isset($due['params']['VALUE']) && $due['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
             $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($due['value'])) . '000';
         } else {
             if ($tzid && !isset($due['value']['tz'])) {
                 /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
                 $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($due['value'])) . '000';
             } else {
                 $schedulable['due'] = self::date2timestamp($due['value']) . '000';
                 if (strpos($params['prodid'], 'Outlook') !== false) {
                     //Se o ics veio em utc não aplicar horario de verão
                     $dueTime = new DateTime('@' . (int) ($schedulable['due'] / 1000), new DateTimeZone('UTC'));
                     $dueTime->setTimezone($objTimezone);
                     if ($dueTime->format('I')) {
                         $schedulable['due'] = $schedulable['due'] - 3600000;
                     }
                 }
             }
         }
         $schedulable['endTime'] = $schedulable['due'];
     } else {
         $schedulable['endTime'] = $schedulable['startTime'];
     }
     $schedulable['type'] = '2';
     //type schedulable
     $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
     /* Definindo Description */
     if ($desc = $component->getProperty('description', false, false)) {
         $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\\n', '\\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
     }
     /* Definindo Class */
     $class = $component->getProperty('class', false, false);
     if ($class && defined(constant(strtoupper('CLASS_' . $class)))) {
         $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
     } else {
         if (!isset($schedulable['class'])) {
             $schedulable['class'] = CLASS_PRIVATE;
         }
     }
     // padrão classe private
     $schedulable['calendar'] = $params['calendar'];
     $participantsInTodo = array();
     //TODO: Participants com delegated nao estao sendo levados em conta
     while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
         $participant = array();
         $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
         $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
         $participant['schedulable'] = $todoID;
         if (isset($params['status']) && $mailUser == Config::me('mail')) {
             $participant['status'] = $params['status'];
         } else {
             $participant['status'] = isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
         }
         $participant['isOrganizer'] = '0';
         /* Verifica se este usuario é um usuario interno do ldap */
         $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
         $user = null;
         if ($intUser && count($intUser) > 0) {
             $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
             $participant['user'] = $intUser[0]['id'];
         } else {
             $participant['isExternal'] = 1;
             /* Gera um randon id para o contexto formater */
             $userID = mt_rand() . '4(Formatter)';
             $user['mail'] = $mailUser;
             $user['isExternal'] = '1';
             $user['name'] = isset($property['params']['CN']) ? $property['params']['CN'] : '';
             $user['participants'] = array($participantID);
             $participant['user'] = $userID;
             $interation['user://' . $userID] = $user;
         }
         $interation['participant://' . $participantID] = $participant;
         $schedulable['participants'][] = $participantID;
     }
     if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
         $participant = array();
         $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
         if ($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)) {
             $participantID = $participant['id'];
         } else {
             $participant = array();
             $participantID = mt_rand() . '2(Formatter)';
             $participant['schedulable'] = $todoID;
             $participant['status'] = isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
             $participant['isOrganizer'] = '1';
             $participant['acl'] = 'rowi';
         }
         /* Verifica se este usuario é um usuario interno do ldap */
         $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
         $user = null;
         if ($intUser && count($intUser) > 0) {
             $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
             $participant['user'] = $intUser[0]['id'];
         } else {
             $participant['isExternal'] = 1;
             /* Gera um randon id para o contexto formater */
             $userID = mt_rand() . '4(Formatter)';
             $user['mail'] = $mailUser;
             $user['name'] = isset($property['params']['CN']) ? $property['params']['CN'] : '';
             $user['participants'] = array($participantID);
             $user['isExternal'] = '1';
             $participant['user'] = $userID;
             $interation['user://' . $userID] = $user;
         }
         $interation['participant://' . $participantID] = $participant;
         $schedulable['participants'][] = $participantID;
     } else {
         if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {
             //caso não tenha organizador o usuario se torna organizador
             $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
             if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
                 $participantID = mt_rand() . '2(Formatter)';
                 $participant['schedulable'] = $todoID;
                 $participant['status'] = STATUS_CONFIRMED;
                 $participant['isOrganizer'] = '1';
                 $participant['acl'] = 'rowi';
                 $participant['isExternal'] = 0;
                 $participant['user'] = $params['owner'];
                 $interation['participant://' . $participantID] = $participant;
                 $schedulable['participants'][] = $participantID;
             }
         }
     }
     $alarms = array();
     /* Definindo ALARMES */
     while ($alarmComp = $component->getComponent('valarm')) {
         $alarm = array();
         $alarmID = mt_rand() . '6(Formatter)';
         $action = $alarmComp->getProperty('action', false, true);
         $trygger = $alarmComp->getProperty('trigger', false, true);
         $alarm['type'] = self::decodeAlarmAction($action['value']);
         if (isset($trygger['value']['day'])) {
             $alarm['time'] = $trygger['value']['day'];
             $alarm['unit'] = 'd';
         } else {
             if (isset($trygger['value']['hour'])) {
                 $alarm['time'] = $trygger['value']['hour'];
                 $alarm['unit'] = 'h';
             } else {
                 if (isset($trygger['value']['min'])) {
                     $alarm['time'] = $trygger['value']['min'];
                     $alarm['unit'] = 'm';
                 }
             }
         }
         foreach ($interation as $iint => &$vint) {
             if (isset($vint['user']) && $vint['user'] == Config::me('uidNumber')) {
                 $alarm['participant'] = str_replace('participant://', '', $iint);
                 $vint['alarms'][] = $alarmID;
             }
         }
         $alarm['schedulable'] = $eventID;
         $interation['alarm://' . $alarmID] = $alarm;
     }
     /* Definindo DTSTAMP */
     if ($dtstamp = self::_getTime($component, 'dtstamp')) {
         $schedulable['dtstamp'] = $dtstamp;
     }
     /* Definindo TRANSP */
     if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE') {
         $schedulable['transparent'] = 1;
     }
     /* Definindo last_update */
     if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED')) {
         $schedulable['lastUpdate'] = $lastUpdate;
     }
     if ($status = $component->getProperty('status', false, false)) {
         $schedulable['status'] = self::decodeStatusTodo(mb_convert_encoding(str_ireplace(array('\\n', '\\t'), array("\n", "\t"), $status), 'UTF-8', 'UTF-8,ISO-8859-1'));
     }
     if ($sequence = $component->getProperty('SEQUENCE', false, false)) {
         $schedulable['sequence'] = $sequence;
     }
     if ($uid = $component->getProperty('uid', false, false)) {
     }
     $schedulable['uid'] = $uid;
     while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
         $attachCurrent = array('name' => $attach['params']['X-FILENAME'], 'size' => strlen($attach['value']), 'type' => self::_getContentType($attach['params']['X-FILENAME']));
         $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
         if (!is_array($ids)) {
             $attachCurrent['source'] = $attach['value'];
             //insere o anexo no banco e pega id para colcar no relacionamento
             $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
         } else {
             $idAttachment = array('id' => $ids[0]['id']);
         }
         $calendarToAttachmentId = mt_rand() . '2(Formatter)';
         $calendarToAttachment['attachment'] = $idAttachment['id'];
         $calendarToAttachment['schedulable'] = $eventID;
         $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
         $schedulable['attachments'][] = $calendarToAttachmentId;
     }
     $interation['schedulable://' . $todoID] = $schedulable;
     return $interation;
 }
Example #11
0
 public function doImapFind(&$uri, &$result, &$criteria, $original)
 {
     $imap_uri = $uri;
     $imap_uri['service'] = 'Imap';
     $imap_criteria = $original['criteria'];
     if (self::in_arrayr('alarmDeadline', $original['criteria']) || self::in_arrayr('doneDeadline', $original['criteria']) || self::in_arrayr('followupflagId', $original['criteria'])) {
         if (empty($result)) {
             return $result;
         }
         $idList = array();
         foreach ($result as $r) {
             $idList[] = $r['messageId'];
         }
         $imap_criteria['filter'] = array('IN', 'messageId', $idList);
     }
     $imap_result = Controller::find($imap_uri, false, $imap_criteria);
     /**
      * Mescla os dados vindos do PostgreSQL com os dados vindos do Imap
      */
     $merge_result = array();
     if (is_array($imap_result)) {
         foreach ($imap_result as $j => $ir) {
             foreach ($result as $k => $r) {
                 if ($r['messageId'] == $ir['messageId']) {
                     if (!empty($r['messageId'])) {
                         $merge_result[] = $r + $ir;
                     }
                     unset($result[$k]);
                     unset($imap_result[$j]);
                     break;
                 }
             }
         }
     }
     /**
      * Faz a consistência do banco com o imap
      */
     /*
     if ($result) {
     	$idList = array();
     	foreach ($result as $ir) {
     		$idList[] = $ir['messageId'];
     	}
     	$filter = array('IN', 'messageId', $idList);
     	Controller::delete(array('concept' => 'followupflagged'), null , array('filter' => $filter));
     }
     */
     /**
      * Faz a consistência do banco com o imap
      */
     if ($imap_result) {
         foreach ($imap_result as $ir) {
             $n = $ir;
             $n['followupflagId'] = 1;
             $n['backgroundColor'] = '#FF2016';
             $n['id'] = Controller::create(array('concept' => 'followupflagged'), $n);
             $merge_result[] = $n;
         }
     }
     return $merge_result;
 }
 /**
  * Handle an HTTP request, defined with a SS_HTTPRequest object.
  *
  * @return SS_HTTPResponse|string
  */
 protected static function handleRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     $rules = Config::inst()->get('Director', 'rules');
     if (isset($_REQUEST['debug'])) {
         Debug::show($rules);
     }
     foreach ($rules as $pattern => $controllerOptions) {
         if (is_string($controllerOptions)) {
             if (substr($controllerOptions, 0, 2) == '->') {
                 $controllerOptions = array('Redirect' => substr($controllerOptions, 2));
             } else {
                 $controllerOptions = array('Controller' => $controllerOptions);
             }
         }
         if (($arguments = $request->match($pattern, true)) !== false) {
             $request->setRouteParams($controllerOptions);
             // controllerOptions provide some default arguments
             $arguments = array_merge($controllerOptions, $arguments);
             // Find the controller name
             if (isset($arguments['Controller'])) {
                 $controller = $arguments['Controller'];
             }
             // Pop additional tokens from the tokeniser if necessary
             if (isset($controllerOptions['_PopTokeniser'])) {
                 $request->shift($controllerOptions['_PopTokeniser']);
             }
             // Handle redirections
             if (isset($arguments['Redirect'])) {
                 return "redirect:" . Director::absoluteURL($arguments['Redirect'], true);
             } else {
                 Director::$urlParams = $arguments;
                 $controllerObj = Injector::inst()->create($controller);
                 $controllerObj->setSession($session);
                 try {
                     $result = $controllerObj->handleRequest($request, $model);
                 } catch (SS_HTTPResponse_Exception $responseException) {
                     $result = $responseException->getResponse();
                 }
                 if (!is_object($result) || $result instanceof SS_HTTPResponse) {
                     return $result;
                 }
                 user_error("Bad result from url " . $request->getURL() . " handled by " . get_class($controllerObj) . " controller: " . get_class($result), E_USER_WARNING);
             }
         }
     }
     /**
      * @andrelohmann
      * 
      * This code allows to return custom Error Pages without using the CMS Module
      * 
      */
     $template = array('ErrorPage', 'Page');
     $C = Controller::create();
     $C->onBeforeInit();
     $C->init();
     $C->onAfterInit();
     $result = $C->customise(new ArrayData(array('Title' => 404, 'Content' => DBField::create_field('HTMLText', 'No URL rule was matched'))));
     // No URL rules matched, so return a 404 error.
     return new SS_HTTPResponse($result->renderWith($template), 404);
     /**
      * Original Code
      *
      * // No URL rules matched, so return a 404 error.
      * return new SS_HTTPResponse('No URL rule was matched', 404);
      * 
      */
 }
Example #13
0
 /**
  * Monta o body e envia o email 
  *
  * @license    http://www.gnu.org/copyleft/gpl.html GPL
  * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
  * @sponsor    Caixa Econômica Federal
  * @author     Cristiano Corrêa Schmidt
  * @return     void
  * @access     public
  */
 private static function sendMail(&$data, &$ical, $to, &$subject, $template, $from = false)
 {
     $ical1['type'] = 'text/plain';
     $ical1['source'] = $ical['compatible'];
     $ical1['name'] = 'outlook2003.ics';
     $ical2['source'] = $ical['ical'];
     $ical2['type'] = 'text/calendar';
     $ical2['name'] = 'calendar.ics';
     unset($ical);
     $mail['attachments'][] = $ical2;
     $mail['attachments'][] = $ical1;
     unset($ical1);
     unset($ical2);
     $mail['isHtml'] = true;
     $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $template . '.tpl');
     $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
     $mail['from'] = $from ? '"' . $from['user']['name'] . '" <' . $from['user']['mail'] . '>' : '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
     $mail['to'] = $to;
     Controller::create(array('service' => 'SMTP'), $mail);
 }
Example #14
0
 public function createDefaultSignature(&$uri, &$result, &$criteria, $original)
 {
     if (count($result) == 0 && isset($criteria['filter'][3]) && isset($criteria['filter'][3]['isRecursion'])) {
         throw new Exception('It was not possible to find to calendar!');
         return false;
     }
     //Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
     $isValidSignature = false;
     //Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma
     if (count($result) > 0) {
         foreach ($result as $value) {
             if (isset($value['isOwner']) && $value['isOwner'] != 0 && isset($value['type']) && $value['type'] == 0) {
                 $isValidSignature = true;
             }
         }
     }
     if (!$isValidSignature && ($original['criteria']['filter'][1][0] == '=' && $original['criteria']['filter'][1][1] == 'user' && $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id'])) {
         if (Config::module('useCaldav', 'expressoCalendar')) {
             require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
             $calendario = DAViCalAdapter::findCalendars();
         }
         if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) {
             foreach ($calendario as $i => $v) {
                 $urlA = explode('/', $v->url);
                 $name = isset($v->displayname) ? $v->displayname : $urlA[count($urlA) - 2];
                 $cal = array('name' => $name, 'description' => isset($v->description) ? $v->description : $name, 'timezone' => isset($v->timezone) ? $v->timezone : date_default_timezone_get() ? date_default_timezone_get() : 'America/Sao_Paulo', 'dtstamp' => time() . '000', 'location' => $urlA[count($urlA) - 3] . '/' . $urlA[count($urlA) - 2]);
                 $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
                 if (!$calCreated) {
                     throw new Exception('Error to create calendar');
                     return false;
                 }
                 $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'], 'calendar' => $calCreated['id'], 'isOwner' => '1', 'dtstamp' => time() . '000', 'fontColor' => 'FFFFFF', 'backgroundColor' => '3366CC', 'borderColor' => '3366CC');
                 $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
                 if (!$sigCreated) {
                     throw new Exception('Error to create signature');
                     return false;
                 }
                 if ($i == 0) {
                     $pref = array();
                     $pref['user'] = $_SESSION['wallet']['user']['uidNumber'];
                     $pref['value'] = $calCreated['id'];
                     $pref['name'] = 'dafaultImportCalendar';
                     $pref['module'] = 'expressoCalendar';
                     Controller::create(array('concept' => 'modulePreference'), $pref);
                 }
             }
         } else {
             //Criaremos uma agenda padrão
             $cal = array('name' => 'Calendario', 'description' => 'Calendario Padrão', 'timezone' => date_default_timezone_get() ? date_default_timezone_get() : 'America/Sao_Paulo', 'dtstamp' => time() . '000');
             $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
             $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'], 'calendar' => $calCreated['id'], 'isOwner' => '1', 'dtstamp' => time() . '000', 'fontColor' => 'FFFFFF', 'backgroundColor' => '3366CC', 'borderColor' => '3366CC');
             $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
             $pref = array();
             $pref['user'] = $_SESSION['wallet']['user']['uidNumber'];
             $pref['value'] = $calCreated['id'];
             $pref['name'] = 'dafaultImportCalendar';
             $pref['module'] = 'expressoCalendar';
             Controller::create(array('concept' => 'modulePreference'), $pref);
         }
         $original['criteria']['filter'][] = array('isRecursion' => true);
         $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
         return false;
     }
 }
Example #15
0
<?php

$result = array();
require_once 'api/controller.php';
$URI = Controller::URI('attachment');
foreach ($_FILES as $name => $file) {
    $file['source'] = file_get_contents($file['tmp_name']);
    unset($file['tmp_name']);
    $result[$name] = Controller::create($URI, $file);
    unset($file['source']);
}
echo json_encode($result);
 /**
  * Método que aplica a ação do filtro nas mensagens da caixa de entrada
  *
  * @license    http://www.gnu.org/copyleft/gpl.html GPL
  * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
  * @sponsor    Caixa Econômica Federal
  * @author     Airton Bordin Junior <*****@*****.**>
  * @author	  Gustavo Pereira dos Santos <*****@*****.**>
  * @param      <Array> <$msgs> <Mensagens da caixa de entrada>
  * @param      <Array> <$proc> <ações do filtro>
  * @return     <Regras do usuário em Array>
  * @access public
  */
 function apliSieveFilter($msgs, $proc)
 {
     $ret = array();
     foreach ($msgs as $i => $msg) {
         switch ($proc['type']) {
             case 'fileinto':
                 $imap = $this->open_mbox('INBOX');
                 if ($proc['keep'] === true) {
                     $ret[$msg][] = imap_mail_copy($imap, $msg, $proc['value'], CP_UID);
                 } else {
                     /* Está sempre copiando a mensagem para a pasta destino */
                     //$ret[$msg][] = imap_mail_move($imap,$msg,$proc['parameter'], CP_UID);
                     $ret[$msg][] = imap_mail_move($imap, $msg, $proc['parameter'], CP_UID);
                     imap_expunge($imap);
                 }
                 break;
             case 'redirect':
                 foreach ($msgs as $msg) {
                     $info = $this->get_info_msg(array('msg_folder' => 'INBOX', 'msg_number' => $msg));
                     Controller::create(array('service' => 'SMTP'), array('body' => $info['body'], 'isHtml' => true, 'subject' => $info['subject'], 'from' => $info['from']['full'], 'to' => $proc['parameter']));
                     if ($proc['keep'] !== true) {
                         $this->delete_msgs(array('msgs_number' => $msg, 'folder' => 'INBOX'));
                     }
                 }
                 break;
             case 'setflag':
                 foreach ($msgs as $msg) {
                     $ret[$msg][] = $this->set_messages_flag(array('folder' => 'INBOX', 'msgs_to_set' => $msg, 'flag' => $proc['parameter']));
                 }
                 break;
         }
     }
     return $ret;
 }
 /**
  * Salva um contato recente
  *
  * @license    http://www.gnu.org/copyleft/gpl.html GPL
  * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
  * @sponsor    Caixa Econômica Federal
  * @author     José Vicente Tezza Jr. 
  * @return     retorna a uri do contato recente
  * @access     public
  * */
 function post($request)
 {
     $this->secured();
     //verificar se a preferencia de contatos dinamicos nao esta ativada
     if (!$this->isEnabledDynamicContacts(Config::me("uidNumber"))) {
         $response = new Response($request);
         $this->createException($request, $response, Response::UNAUTHORIZED, 'Resource unauthorized', 'disabled dynamic contacts preference');
         return $response;
     }
     if (count($_POST) == 0) {
         $response = new Response($request);
         $response->code = Response::INTERNALSERVERERROR;
         return $response;
     }
     //recuperar os atributos definidos no conceito 'user'
     $map = Config::get('dynamicContact', 'PostgreSQL.mapping');
     $params = array();
     foreach ($_POST as $key => $value) {
         if (!isset($map[$key]) || $key == 'id' || $key == 'timestamp' || $key == 'number_of_messages') {
             continue;
         }
         $params[$key] = $value;
     }
     if (count($params) == 0) {
         $response = new Response($request);
         $response->code = Response::INTERNALSERVERERROR;
         return $response;
     }
     $response = new Response($request);
     $response->addHeader('Content-type', 'aplication/json');
     $response->code = Response::CREATED;
     //completar os atributos
     $params['owner'] = Config::me("uidNumber");
     $params['number_of_messages'] = '1';
     $params['timestamp'] = time();
     try {
         //verificar o limite maximo de contatos dinamicos nas preferencias do administrador
         $sql = "SELECT config_value " . "FROM phpgw_config " . "WHERE config_app = 'expressoMail' " . "AND config_name = 'expressoMail_Number_of_dynamic_contacts'";
         $numberOfMessages = Controller::service('PostgreSQL')->execResultSql($sql, true);
         $numberOfMessages = count($numberOfMessages) > 0 ? (int) $numberOfMessages['config_value'] : 0;
         //realizar busca de contatos dinamicos ordenados pela data de utilizacao
         $dynamicContacts = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('=', 'owner', Config::me("uidNumber")), 'order' => array('timestamp')));
         $numberOfDynamicContacts = $dynamicContacts !== false ? count($dynamicContacts) : 0;
         //se a quantidade de contatos dinamicos de usuario exceder o limite maximo definido nas preferencias do administrador,
         //remover o contato dinamico mais antigo
         if ($numberOfMessages > 0 && $numberOfDynamicContacts >= $numberOfMessages) {
             $id = $dynamicContacts[0]['id'];
             $delete = Controller::delete(array('concept' => 'dynamicContact', 'id' => $id));
             if (!$delete) {
                 $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
                 return $response;
             }
         }
         //inserir o novo contato dinamico
         $create = Controller::create(array('concept' => 'dynamicContact'), $params);
         if (!$create) {
             throw new Exception(Controller::service('PostgreSQL')->error);
         }
     } catch (Exception $ex) {
         $response->code = Response::INTERNALSERVERERROR;
         return $response;
     }
     $response->body = json_encode(null);
     return $response;
 }
 /**
  * Check catalogue URL's before we get to the CMS (if it exists)
  * 
  * @param SS_HTTPRequest $request
  * @param DataModel|null $model
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->request = $request;
     $this->setDataModel($model);
     $this->pushCurrent();
     // Create a response just in case init() decides to redirect
     $this->response = new SS_HTTPResponse();
     $this->init();
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         $this->popCurrent();
         return $this->response;
     }
     // If DB is not present, build
     if (!DB::isActive() || !ClassInfo::hasTable('CatalogueProduct') || !ClassInfo::hasTable('CatalogueCategory')) {
         return $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
     }
     $urlsegment = $request->param('URLSegment');
     $this->extend('onBeforeInit');
     $this->init();
     $this->extend('onAfterInit');
     // Find link, regardless of current locale settings
     if (class_exists('Translatable')) {
         Translatable::disable_locale_filter();
     }
     $filter = array('URLSegment' => $urlsegment, 'Disabled' => 0);
     if ($object = CatalogueProduct::get()->filter($filter)->first()) {
         $controller = $this->controller_for($object);
     } elseif ($object = CatalogueCategory::get()->filter($filter)->first()) {
         $controller = $this->controller_for($object);
     } elseif (class_exists('ModelAsController')) {
         // If CMS installed
         $controller = ModelAsController::create();
     } else {
         $controller = Controller::create();
     }
     if (class_exists('Translatable')) {
         Translatable::enable_locale_filter();
     }
     $result = $controller->handleRequest($request, $model);
     $this->popCurrent();
     return $result;
 }
 /**
  * Exercises SecuredFilesystem::get_numeric_identifier() with both types of expected controller
  * Ensures expected outputs given a variety of inputs
  *
  * @todo Add 'ParentID' ensure this works as expected
  * @todo  Test with "unexpected" class, assert exedcption or error thrown as expecced (Zero is returned)
  */
 public function testGetNumericIdentifierPost()
 {
     $controller = $this->getTestController(array('ID' => '40'), 'POST', AssetAdmin::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(40, $result);
     $controller = $this->getTestController(array('ID' => '40'), 'POST', CMSFileAddController::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(40, $result);
     $controller = $this->getTestController(array('ID' => '0'), 'POST', AssetAdmin::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('ID' => '0'), 'POST', CMSFileAddController::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('ParentID' => '40'), 'POST', AssetAdmin::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ParentID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(40, $result);
     $controller = $this->getTestController(array('ParentID' => '40'), 'POST', CMSFileAddController::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ParentID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(40, $result);
     $controller = $this->getTestController(array('ParentID' => '0'), 'POST', AssetAdmin::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ParentID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('ParentID' => '0'), 'POST', CMSFileAddController::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ParentID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('DUMMY' => '40'), 'POST', AssetAdmin::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('DUMMY' => '40'), 'POST', CMSFileAddController::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
     $controller = $this->getTestController(array('ID' => '40'), 'POST', Controller::create());
     $result = SecuredFilesystem::get_numeric_identifier($controller, 'ID');
     $this->assertInternalType('integer', $result);
     $this->assertEquals(0, $result);
 }